From 064100a73382eb91ad805cd7711b1d1fb9a030dc Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 20 Nov 2026 20:03:49 +0000 Subject: [PATCH 01/62] fix(evo): partition Evo-derived caches by view Isolating the snapshot generation's records is not enough while the managers keep one cache for both chainstates. The snapshot chainstate derives values at and below its base from state the snapshot carries, which nothing has validated yet. The background chainstate connects the same block hashes and, through a shared cache, took those values instead of deriving its own: a list, quorum member set, mined-commitment location or deployment state. For the credit pool at the base, the background capture then recorded the carried pool, so completion compared the carried pool with itself. EvoViewCache keeps one partition per Evo view (EvoDB, identity, generation). Every cache keyed by a block or quorum hash now resolves the calling operation's view and uses only that partition: the MN-list lists, diffs, tip and initial-snapshot anchor; quorum snapshots; MNHF signals; credit pools; mined-commitment locations and the qc-hash caches, including the active quorum set GetQcHashes derives from the previous block's; the quorum member caches; the quorum manager's quorum, scan and commitment-scan caches; the versionbits cache; and the previous-coinbase ChainLock slot, which a snapshot block's validation must read from the same view the miner of its template did. The versionbits partition and the EHF signals SignalHeight reads both come from the calling thread's view. Caches of data parsed from block bytes and the vvec/skshare stores stay shared, and so do the warning cache, the quorum proof caches and the quorum-data cleanup cache: only the active view fills them, a rejected snapshot shuts the node down, and a promoted one has been validated. What a block mined is read from the block itself, so the record of the commitments recent blocks mined stays shared. Retiring a generation drops its partitions at the next lookup and leaves NORMAL's, so a failed snapshot load no longer empties the active masternode list until the next block. Promoting a generation, like opening a CEvoDB, bumps an epoch that drops every partition. DeploymentActiveAfter/At through a ChainstateManager decide a buried deployment by height alone, without resolving a view. The MN-list cache of a view is pruned against the higher of its tip and the highest block it processed: a view stops receiving tip notifications once its chainstate is no longer the active one, so a stale tip would keep its cache from ever being pruned. EvoViewToken::AtOrBelowSnapshotBase() names the heights at which a snapshot view holds only carried state, and ReadBlockInView() reads a block body for a view, raising BlockDataUnavailableError where the snapshot view lacks it instead of reporting the body as unreadable. A snapshot view has no quorum history at or below its base once DIP3 is active there (a base at or above the DIP3 height), so lookups that would need it raise BlockDataUnavailableError instead of answering from partial data: a mined-commitment scan that comes up short (GetMinedCommitmentsUntilBlock, and the rotating per-index scan on a miss), a HasMinedCommitment miss for a quorum at or below the base, and the coinbase ChainLock read of a block at or below the base whose body is not stored. EHF signal lookups only read, as on develop since dashpay/dash#8098, so the signals are still written only when a block is connected or rebuilt at startup, inside an Evo transaction. The MNHF signal cache keeps one partition per view like the others. A snapshot view holds only what its snapshot carried and its chainstate connected, and what else it lacks is recovered by the startup that promotes the validated snapshot, so a lookup there that finds no record raises BlockDataUnavailableError (a stall) instead of EvoDbMissingStateError, which NORMAL keeps. The startup rebuild never walks a snapshot view at or below its base, whose blocks are unvalidated and whose bodies it lacks. Adds CDeterministicMNManager::SetListSnapshotMissHookForTesting, which reports lookups that miss both the cache and the stored lists, and CachedListHeightsForTesting, for the partition and pruning tests and the tests that need one lookup to fail. With the hook, a test also rejects a snapshot in the middle of a block connection and checks that the background chainstate becomes the active one. A quorum scan is cached only when its start block is on the chain that its view's mined-commitment index describes (dashpay/dash#8102), now the chain of the usable chainstate with the view's Evo identity (ChainstateManager::EvoChain) instead of the active chain. A background view's index follows the background chainstate, so its scans from blocks it has not connected are not cached, and a view no usable chainstate reads caches nothing. chainstatemanager_rejection_mid_connect_activates_background checks that mapping during dual operation and after a rejection. RequireSatisfiedScan raises for a short height-index scan under a snapshot view based at or above DIP3 only when the type was enabled at the end of the missing range or at DIP3 activation: a type not enabled up to the base has no commitments there, so its short scan is complete, and a CbTx quorum-root check over it must not stall the snapshot chainstate. Deployment-gated types stay enabled once enabled, and the types DIP0024 retires are enabled from DIP3 on. The check runs before the EvoDB lock is taken, because deployment state can read EvoDB. The mined-commitment walkers that getPlatformQuorum reads its window with throw BlockDataUnavailableError under such a view when the window reaches history the view lacks, even for a quorum in the part of the window above the base. The base is checked first, and the DIP3 ancestor is only looked up when that check fails: a chain that does not reach genesis, such as the testnet-height chain quorum_proofs_tests builds, has no such ancestor. With the MN-list miss hook this adds, a test also rejects the snapshot in an ActivateBestChain step that first disconnected one of its blocks, which must not leave that block's transactions queued. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- src/evo/cbtx.cpp | 24 +- src/evo/cbtx.h | 13 +- src/evo/creditpool.cpp | 21 +- src/evo/creditpool.h | 12 +- src/evo/deterministicmns.cpp | 119 +++-- src/evo/deterministicmns.h | 63 ++- src/evo/evodb.cpp | 19 +- src/evo/evodb.h | 88 +++- src/evo/mnhftx.cpp | 33 +- src/evo/mnhftx.h | 12 +- src/evo/smldiff.cpp | 6 +- src/evo/specialtxman.cpp | 27 +- src/evo/viewcache.h | 115 +++++ src/llmq/blockprocessor.cpp | 175 +++++-- src/llmq/blockprocessor.h | 51 +- src/llmq/quorumsman.cpp | 65 ++- src/llmq/quorumsman.h | 22 +- src/llmq/snapshot.cpp | 22 +- src/llmq/snapshot.h | 14 +- src/llmq/utils.cpp | 73 ++- src/net_processing.cpp | 14 +- src/node/miner.cpp | 7 +- src/rpc/rawtransaction.cpp | 3 +- src/test/evo_db_tests.cpp | 305 +++++++++++ src/test/evo_deterministicmns_tests.cpp | 30 ++ src/test/quorum_proofs_tests.cpp | 21 +- .../validation_chainstatemanager_tests.cpp | 483 +++++++++++++++++- src/validation.cpp | 19 + src/validation.h | 105 +++- src/versionbits.cpp | 67 ++- src/versionbits.h | 20 +- 31 files changed, 1768 insertions(+), 280 deletions(-) create mode 100644 src/evo/viewcache.h diff --git a/src/evo/cbtx.cpp b/src/evo/cbtx.cpp index e0fbbb91056d..e1caffe8816c 100644 --- a/src/evo/cbtx.cpp +++ b/src/evo/cbtx.cpp @@ -4,6 +4,8 @@ #include +#include +#include #include #include #include @@ -193,7 +195,9 @@ std::string CCbTx::ToString() const creditPoolBalance / COIN, creditPoolBalance % COIN, merkleRootAssetUnlocks.ToString()); } -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex) +std::optional> GetNonNullCoinbaseChainlock(const EvoViewToken& view, + const node::BlockManager& blockman, + const CBlockIndex* pindex) { if (pindex == nullptr) { return std::nullopt; @@ -205,13 +209,23 @@ std::optional> GetNonNullCoinbaseChainlock(co } CBlock block; - if (!blockman.ReadBlockFromDisk(block, *pindex)) { - return std::nullopt; - } - + if (!ReadBlockInView(view, blockman, *pindex, block)) return std::nullopt; return GetNonNullCoinbaseChainlock(block, pindex->nHeight); } +bool ReadBlockInView(const EvoViewToken& view, const node::BlockManager& blockman, const CBlockIndex& index, + CBlock& block) +{ + if (blockman.ReadBlockFromDisk(block, index)) return true; + // A snapshot view lacks the bodies at or below its base, where a block that + // cannot be read cannot be told from one whose data does not matter. + if (view.AtOrBelowSnapshotBase(index.nHeight) && !WITH_LOCK(::cs_main, return index.nStatus & BLOCK_HAVE_DATA)) { + throw BlockDataUnavailableError(strprintf("block %s at or below the snapshot base is not available", + index.GetBlockHash().ToString())); + } + return false; +} + std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, int32_t height) { if (block.vtx.empty() || !block.vtx[0]->IsCoinBase() || block.vtx[0]->nType != TRANSACTION_COINBASE) { diff --git a/src/evo/cbtx.h b/src/evo/cbtx.h index 09201841ef8c..26a71ca8add7 100644 --- a/src/evo/cbtx.h +++ b/src/evo/cbtx.h @@ -19,6 +19,7 @@ class CBlock; class CBlockIndex; class CDeterministicMNList; class TxValidationState; +struct EvoViewToken; struct RPCResult; namespace node { @@ -87,7 +88,17 @@ bool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPre BlockValidationState& state); uint256 CalcCbTxMerkleRootAssetUnlocks(const CBlock& block); -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex); +//! The non-null ChainLock in the coinbase of `pindex`, read from its body. In a +//! snapshot `view` at or below its base, a body this node lacks raises +//! BlockDataUnavailableError instead of reading as no ChainLock. +std::optional> GetNonNullCoinbaseChainlock(const EvoViewToken& view, + const node::BlockManager& blockman, + const CBlockIndex* pindex); +/** Read the body of `index` for a reader working in `view`. Returns false if it + * cannot be read, and raises BlockDataUnavailableError when the view is a + * snapshot view without that body at or below its base. */ +bool ReadBlockInView(const EvoViewToken& view, const node::BlockManager& blockman, const CBlockIndex& index, + CBlock& block); std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, int32_t height); #endif // BITCOIN_EVO_CBTX_H diff --git a/src/evo/creditpool.cpp b/src/evo/creditpool.cpp index d4fac2c010f7..4354c153ce80 100644 --- a/src/evo/creditpool.cpp +++ b/src/evo/creditpool.cpp @@ -157,8 +157,9 @@ std::optional CCreditPoolManager::GetFromCache(const CBlockIndex& b if (!DeploymentActiveAt(block_index, m_chainman.GetConsensus(), Consensus::DEPLOYMENT_V20)) return CCreditPool{}; const uint256 block_hash = block_index.GetBlockHash(); + const EvoViewToken view{evoDb.CurrentView()}; CCreditPool pool; - if (WITH_LOCK(cache_mutex, return creditPoolCache.get(block_hash, pool))) { + if (WITH_LOCK(cache_mutex, return creditPoolCache.For(view).get(block_hash, pool))) { // The pool may have been constructed, and cached, outside a block-scoped transaction // (mempool acceptance, template creation, RPC), where its snapshot cannot be written. // Persist it from the first transaction-scoped lookup instead, or the snapshot would be @@ -169,7 +170,7 @@ std::optional CCreditPoolManager::GetFromCache(const CBlockIndex& b if (block_index.nHeight % DISK_SNAPSHOT_PERIOD == 0) { if (evoDb.Read(std::make_pair(DB_CREDITPOOL_SNAPSHOT, block_hash), pool)) { LOCK(cache_mutex); - creditPoolCache.insert(block_hash, pool); + creditPoolCache.For(view).insert(block_hash, pool); return pool; } } @@ -196,14 +197,16 @@ void CCreditPoolManager::MaybeWriteSnapshot(const uint256& block_hash, int heigh } } -void CCreditPoolManager::AddToCache(const uint256& block_hash, int height, const CCreditPool& pool) +void CCreditPoolManager::AddToCache(const EvoViewToken& view, const uint256& block_hash, int height, + const CCreditPool& pool) { MaybeWriteSnapshot(block_hash, height, pool); LOCK(cache_mutex); - creditPoolCache.insert(block_hash, pool); + creditPoolCache.For(view).insert(block_hash, pool); } -CCreditPool CCreditPoolManager::ConstructCreditPool(const gsl::not_null block_index, CCreditPool prev) +CCreditPool CCreditPoolManager::ConstructCreditPool(const EvoViewToken& view, + const gsl::not_null block_index, CCreditPool prev) { std::optional opt_block_data = GetCreditDataFromBlock(block_index, m_chainman.m_blockman, m_chainman.GetConsensus()); if (!opt_block_data) { @@ -217,7 +220,7 @@ CCreditPool CCreditPoolManager::ConstructCreditPool(const gsl::not_nullGetBlockHash(), block_index->nHeight, emptyPool); + AddToCache(view, block_index->GetBlockHash(), block_index->nHeight, emptyPool); return emptyPool; } const CreditPoolDataPerBlock& blockData{*opt_block_data}; @@ -274,7 +277,7 @@ CCreditPool CCreditPoolManager::ConstructCreditPool(const gsl::not_nullGetBlockHash(), block_index->nHeight, pool); + AddToCache(view, block_index->GetBlockHash(), block_index->nHeight, pool); return pool; } @@ -290,6 +293,7 @@ CCreditPool CCreditPoolManager::GetCreditPool(const CBlockIndex* block_index) { std::stack> to_calculate; + const EvoViewToken view{evoDb.CurrentView()}; std::optional poolTmp; while (block_index != nullptr && !(poolTmp = GetFromCache(*block_index)).has_value()) { // Not emplace: gsl::not_null captures the caller's source_location as a @@ -301,7 +305,7 @@ CCreditPool CCreditPoolManager::GetCreditPool(const CBlockIndex* block_index) } if (block_index == nullptr) poolTmp = CCreditPool{}; while (!to_calculate.empty()) { - poolTmp = ConstructCreditPool(to_calculate.top(), *poolTmp); + poolTmp = ConstructCreditPool(view, to_calculate.top(), *poolTmp); to_calculate.pop(); } return *poolTmp; @@ -311,6 +315,7 @@ CCreditPoolManager::CCreditPoolManager(CEvoDB& _evoDb, const ChainstateManager& evoDb{_evoDb}, m_chainman{chainman} { + creditPoolCache.SetOwner(_evoDb); } CCreditPoolManager::~CCreditPoolManager() = default; diff --git a/src/evo/creditpool.h b/src/evo/creditpool.h index 2d02bf251c85..31f0d1de3e95 100644 --- a/src/evo/creditpool.h +++ b/src/evo/creditpool.h @@ -6,6 +6,7 @@ #define BITCOIN_EVO_CREDITPOOL_H #include +#include #include #include #include @@ -121,7 +122,8 @@ class CCreditPoolManager private: static constexpr size_t CreditPoolCacheSize = 1000; Mutex cache_mutex; - Uint256LruHashMap creditPoolCache GUARDED_BY(cache_mutex){CreditPoolCacheSize}; + EvoViewCache> creditPoolCache GUARDED_BY(cache_mutex){ + [] { return Uint256LruHashMap{CreditPoolCacheSize}; }}; CEvoDB& evoDb; const ChainstateManager& m_chainman; @@ -184,13 +186,15 @@ class CCreditPoolManager private: std::optional GetFromCache(const CBlockIndex& block_index) EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); - void AddToCache(const uint256& block_hash, int height, const CCreditPool& pool) EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); + //! Cache a pool derived from reads made after `view` was resolved. + void AddToCache(const EvoViewToken& view, const uint256& block_hash, int height, const CCreditPool& pool) + EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); /** Write the disk snapshot of a snapshot-height pool when a block-scoped EvoDB transaction * is open on this thread; a no-op otherwise. */ void MaybeWriteSnapshot(const uint256& block_hash, int height, const CCreditPool& pool); - CCreditPool ConstructCreditPool(const gsl::not_null block_index, CCreditPool prev) - EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); + CCreditPool ConstructCreditPool(const EvoViewToken& view, const gsl::not_null block_index, + CCreditPool prev) EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); }; std::optional GetCreditPoolDiffForBlock(CCreditPoolManager& cpoolman, diff --git a/src/evo/deterministicmns.cpp b/src/evo/deterministicmns.cpp index 151d150313ff..2193e1a32b8e 100644 --- a/src/evo/deterministicmns.cpp +++ b/src/evo/deterministicmns.cpp @@ -710,6 +710,7 @@ CDeterministicMNManager::CDeterministicMNManager(CEvoDB& evoDb, CMasternodeMetaM m_evoDb{evoDb}, m_mn_metaman{mn_metaman} { + m_views.SetOwner(evoDb); } CDeterministicMNManager::~CDeterministicMNManager() = default; @@ -733,6 +734,7 @@ bool CDeterministicMNManager::ProcessBlock(gsl::not_null pin newList.to_sml(); // to populate the SML cache LOCK(cs); + auto& view{View()}; diff = oldList.BuildDiff(newList); @@ -745,21 +747,22 @@ bool CDeterministicMNManager::ProcessBlock(gsl::not_null pin notifications.fatalError(msg); return state.Error(msg); } - if ((nHeight % DISK_SNAPSHOT_PERIOD) == 0 || pindex->pprev == m_initial_snapshot_index) { + if ((nHeight % DISK_SNAPSHOT_PERIOD) == 0 || pindex->pprev == view.m_initial_snapshot_index) { if (!m_evoDb.WriteDerived(std::make_pair(DB_LIST_SNAPSHOT, newList.GetBlockHash()), newList)) { const std::string msg = strprintf("CDeterministicMNManager::%s -- EvoDB list snapshot mismatch for block %s", __func__, newList.GetBlockHash().ToString()); notifications.fatalError(msg); return state.Error(msg); } - mnListsCache.insert_or_assign(newList.GetBlockHash(), newList); + view.mnListsCache.insert_or_assign(newList.GetBlockHash(), newList); LogPrintf("CDeterministicMNManager::%s -- Wrote snapshot. nHeight=%d, mapCurMNs.allMNsCount=%d\n", __func__, nHeight, newList.GetCounts().total()); } diff.nHeight = pindex->nHeight; - mnListDiffsCache.emplace(pindex->GetBlockHash(), diff); - mnListsCache.insert_or_assign(newList.GetBlockHash(), newList); + view.mnListDiffsCache.emplace(pindex->GetBlockHash(), diff); + view.processed_height = std::max(view.processed_height, nHeight); + view.mnListsCache.insert_or_assign(newList.GetBlockHash(), newList); } catch (const std::exception& e) { LogPrintf("CDeterministicMNManager::%s -- internal error: %s\n", __func__, e.what()); return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "failed-dmn-block"); @@ -812,8 +815,9 @@ void CDeterministicMNManager::ResetPlatformBans(const CBlock& block, const CBloc void CDeterministicMNManager::DiscardBlock(const uint256& block_hash) { LOCK(cs); - mnListsCache.erase(block_hash); - mnListDiffsCache.erase(block_hash); + auto& view{View()}; + view.mnListsCache.erase(block_hash); + view.mnListDiffsCache.erase(block_hash); } bool CDeterministicMNManager::UndoBlock(gsl::not_null pindex, MNListUpdates& updatesRet) @@ -825,15 +829,18 @@ bool CDeterministicMNManager::UndoBlock(gsl::not_null pindex CDeterministicMNListDiff diff; { LOCK(cs); + const EvoViewToken view_token{m_evoDb.CurrentView()}; + auto& view{m_views.For(view_token)}; m_evoDb.Read(std::make_pair(DB_LIST_DIFF, blockHash), diff); if (diff.HasChanges()) { // need to call this before erasing - prevList = GetListForBlockInternal(pindex->pprev); + prevList = GetListForBlockInternal(pindex->pprev, view, view_token); } - mnListsCache.erase(blockHash); - mnListDiffsCache.erase(blockHash); + view.mnListsCache.erase(blockHash); + view.mnListDiffsCache.erase(blockHash); + view.processed_height = std::min(view.processed_height, nHeight - 1); } if (diff.HasChanges()) { CDeterministicMNList curList{prevList}; @@ -857,10 +864,11 @@ void CDeterministicMNManager::UpdatedBlockTip(gsl::not_null { LOCK(cs); - tipIndex = pindex; + View().tipIndex = pindex; } -CDeterministicMNList CDeterministicMNManager::GetListForBlockInternal(gsl::not_null pindex) +CDeterministicMNList CDeterministicMNManager::GetListForBlockInternal(gsl::not_null pindex, + ViewState& view, const EvoViewToken& view_token) { CDeterministicMNList snapshot; @@ -870,28 +878,37 @@ CDeterministicMNList CDeterministicMNManager::GetListForBlockInternal(gsl::not_n AssertLockHeld(cs); - if (tipIndex != nullptr && mnListsCache.size() > MAX_CACHED_LISTS) { - CleanupCache(tipIndex->nHeight); + // A view stops receiving tip notifications when its chainstate stops being + // the active one, so its tip can lag far behind the blocks it processes. + if (const int cleanup_height{std::max(view.tipIndex != nullptr ? view.tipIndex->nHeight : -1, view.processed_height)}; + cleanup_height >= 0 && view.mnListsCache.size() > MAX_CACHED_LISTS) { + CleanupCache(view, cleanup_height); } std::list listDiffIndexes; + // What is read is cached once every read is done, and only if all of them + // resolved to `view_token`'s view. + bool list_read{false}; + const CBlockIndex* initial_snapshot_index{nullptr}; + Uint256HashMap diffs_read; while (true) { // try using cache before reading from disk - auto itLists = mnListsCache.find(pindex->GetBlockHash()); - if (itLists != mnListsCache.end()) { + auto itLists = view.mnListsCache.find(pindex->GetBlockHash()); + if (itLists != view.mnListsCache.end()) { snapshot = itLists->second; break; } if (m_evoDb.Read(std::make_pair(DB_LIST_SNAPSHOT, pindex->GetBlockHash()), snapshot)) { - mnListsCache.emplace(pindex->GetBlockHash(), snapshot); + list_read = true; break; } + if (m_list_snapshot_miss_hook) m_list_snapshot_miss_hook(pindex); // no snapshot found yet, check diffs - auto itDiffs = mnListDiffsCache.find(pindex->GetBlockHash()); - if (itDiffs != mnListDiffsCache.end()) { + auto itDiffs = view.mnListDiffsCache.find(pindex->GetBlockHash()); + if (itDiffs != view.mnListDiffsCache.end()) { listDiffIndexes.emplace_front(pindex); pindex = pindex->pprev; continue; @@ -917,26 +934,34 @@ CDeterministicMNList CDeterministicMNManager::GetListForBlockInternal(gsl::not_n __func__, pindex->GetBlockHash().ToString(), BLOCK_DATA_UNAVAILABLE_SUFFIX)); } // no snapshot and no diff on disk means that it's the initial snapshot - m_initial_snapshot_index = pindex; + initial_snapshot_index = pindex; snapshot = CDeterministicMNList(pindex->GetBlockHash(), pindex->nHeight, 0); - mnListsCache.emplace(pindex->GetBlockHash(), snapshot); + list_read = true; LogPrintf("CDeterministicMNManager::%s -- initial snapshot. blockHash=%s nHeight=%d\n", __func__, snapshot.GetBlockHash().ToString(), snapshot.GetHeight()); break; } diff.nHeight = pindex->nHeight; - mnListDiffsCache.emplace(pindex->GetBlockHash(), std::move(diff)); + diffs_read.emplace(pindex->GetBlockHash(), std::move(diff)); listDiffIndexes.emplace_front(pindex); pindex = pindex->pprev; } + const bool cache{!m_evoDb.IsOvertaken(view_token)}; + if (cache) { + if (list_read) view.mnListsCache.emplace(snapshot.GetBlockHash(), snapshot); + if (initial_snapshot_index != nullptr) view.m_initial_snapshot_index = initial_snapshot_index; + view.mnListDiffsCache.merge(diffs_read); + } + for (const auto& diffIndex : listDiffIndexes) { - const auto& diff = mnListDiffsCache.at(diffIndex->GetBlockHash()); + const auto it{diffs_read.find(diffIndex->GetBlockHash())}; + const auto& diff{it != diffs_read.end() ? it->second : view.mnListDiffsCache.at(diffIndex->GetBlockHash())}; snapshot.ApplyDiff(diffIndex, diff); static constexpr int MINI_SNAPSHOT_INTERVAL = 32; - if (!node::fReindex && snapshot.GetHeight() % MINI_SNAPSHOT_INTERVAL == 0) { + if (cache && !node::fReindex && snapshot.GetHeight() % MINI_SNAPSHOT_INTERVAL == 0) { // Add this temporary mini-snapshot to the cache. // Persistent masternode list snapshots are stored in evo-db every 576 blocks. // To answer GetListForBlock() between these snapshots, the node must rebuild @@ -949,24 +974,22 @@ CDeterministicMNList CDeterministicMNManager::GetListForBlockInternal(gsl::not_n // There is also separate in-memory caching for the current tip and active quorums, // but this mini-snapshot cache specifically speeds up repeated requests // for nearby historical blocks. - mnListsCache.emplace(snapshot.GetBlockHash(), snapshot); + view.mnListsCache.emplace(snapshot.GetBlockHash(), snapshot); } } - if (tipIndex) { + if (cache && view.tipIndex) { // always keep a snapshot for the tip - if (const auto snapshot_hash = snapshot.GetBlockHash(); snapshot_hash == tipIndex->GetBlockHash()) { - mnListsCache.emplace(snapshot_hash, snapshot); + if (const auto snapshot_hash = snapshot.GetBlockHash(); snapshot_hash == view.tipIndex->GetBlockHash()) { + view.mnListsCache.emplace(snapshot_hash, snapshot); } else { // keep snapshots for yet alive quorums - if (std::ranges::any_of(Params().GetConsensus().llmqs, [&snapshot, this]( - const auto& params) EXCLUSIVE_LOCKS_REQUIRED(cs) { - AssertLockHeld(cs); + if (std::ranges::any_of(Params().GetConsensus().llmqs, [&snapshot, &view](const auto& params) { return (snapshot.GetHeight() % params.dkgInterval == 0) && (snapshot.GetHeight() + params.dkgInterval * (params.keepOldConnections + 1) >= - tipIndex->nHeight); + view.tipIndex->nHeight); })) { - mnListsCache.emplace(snapshot_hash, snapshot); + view.mnListsCache.emplace(snapshot_hash, snapshot); } } } @@ -979,10 +1002,12 @@ CDeterministicMNList CDeterministicMNManager::GetListAtChainTip() { Assume(m_evoDb.ReadsActiveView()); LOCK(cs); - if (!tipIndex) { + const EvoViewToken view_token{m_evoDb.CurrentView()}; + auto& view{m_views.For(view_token)}; + if (!view.tipIndex) { return {}; } - return GetListForBlockInternal(tipIndex); + return GetListForBlockInternal(view.tipIndex, view, view_token); } bool CDeterministicMNManager::IsProTxWithCollateral(const CTransactionRef& tx, uint32_t n) @@ -1010,19 +1035,18 @@ bool CDeterministicMNManager::IsProTxWithCollateral(const CTransactionRef& tx, u return true; } -void CDeterministicMNManager::CleanupCache(int nHeight) +void CDeterministicMNManager::CleanupCache(ViewState& view, int nHeight) { - AssertLockHeld(cs); std::vector toDeleteLists; std::vector toDeleteDiffs; - for (const auto& p : mnListsCache) { + for (const auto& p : view.mnListsCache) { if (p.second.GetHeight() + LIST_DIFFS_CACHE_SIZE < nHeight) { // too old, drop it toDeleteLists.emplace_back(p.first); continue; } - if (tipIndex != nullptr && p.first == tipIndex->GetBlockHash()) { + if (view.tipIndex != nullptr && p.first == view.tipIndex->GetBlockHash()) { // it's a snapshot for the tip, keep it continue; } @@ -1038,15 +1062,15 @@ void CDeterministicMNManager::CleanupCache(int nHeight) toDeleteLists.emplace_back(p.first); } for (const auto& h : toDeleteLists) { - mnListsCache.erase(h); + view.mnListsCache.erase(h); } - for (const auto& p : mnListDiffsCache) { + for (const auto& p : view.mnListDiffsCache) { if (p.second.nHeight + LIST_DIFFS_CACHE_SIZE < nHeight) { toDeleteDiffs.emplace_back(p.first); } } for (const auto& h : toDeleteDiffs) { - mnListDiffsCache.erase(h); + view.mnListDiffsCache.erase(h); } } @@ -1253,8 +1277,7 @@ bool CDeterministicMNManager::MigrateLegacyDiffs(const CBlockIndex* const tip_in // Clear caches to force reload with new format LOCK(cs); - mnListsCache.clear(); - mnListDiffsCache.clear(); + m_views.Clear(); LogPrintf("CDeterministicMNManager::%s -- Successfully migrated %d diffs to nVersion-first format\n", __func__, keys_to_erase.size()); @@ -1596,10 +1619,12 @@ void CDeterministicMNManager::WriteRepairedDiffs( // Clear caches for repaired diffs so next read gets fresh data from disk // Must clear both diff cache and list cache since lists were built from old diffs LOCK(cs); - for (const auto& [block_hash, diff] : recalculated_diffs) { - mnListDiffsCache.erase(block_hash); - mnListsCache.erase(block_hash); - } + m_views.ForEach([&](ViewState& view) { + for (const auto& [block_hash, diff] : recalculated_diffs) { + view.mnListDiffsCache.erase(block_hash); + view.mnListsCache.erase(block_hash); + } + }); LogPrintf("CDeterministicMNManager::%s -- Successfully repaired %d diffs (caches cleared)\n", __func__, recalculated_diffs.size()); diff --git a/src/evo/deterministicmns.h b/src/evo/deterministicmns.h index 9c0e1882f055..ee350a7d2058 100644 --- a/src/evo/deterministicmns.h +++ b/src/evo/deterministicmns.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -23,6 +24,7 @@ #include #include +#include #include #include #include @@ -817,10 +819,23 @@ class CDeterministicMNManager CEvoDB& m_evoDb; CMasternodeMetaMan& m_mn_metaman; - Uint256HashMap mnListsCache GUARDED_BY(cs); - Uint256HashMap mnListDiffsCache GUARDED_BY(cs); - const CBlockIndex* tipIndex GUARDED_BY(cs) {nullptr}; - const CBlockIndex* m_initial_snapshot_index GUARDED_BY(cs) {nullptr}; + //! Lists and diffs derived under one Evo view, with the view's own tip and + //! initial-snapshot anchor. + struct ViewState { + Uint256HashMap mnListsCache; + Uint256HashMap mnListDiffsCache; + const CBlockIndex* tipIndex{nullptr}; + const CBlockIndex* m_initial_snapshot_index{nullptr}; + //! Highest block this view processed and has not undone since. Bounds + //! the cache of a view that is not active, and so never learns a tip + //! from UpdatedBlockTip. + int processed_height{-1}; + }; + EvoViewCache m_views GUARDED_BY(cs); + std::function m_list_snapshot_miss_hook GUARDED_BY(cs); + + //! The partition of the calling operation's Evo view. + ViewState& View() EXCLUSIVE_LOCKS_REQUIRED(cs) { return m_views.For(m_evoDb.CurrentView()); } public: CDeterministicMNManager() = delete; @@ -844,14 +859,43 @@ class CDeterministicMNManager CDeterministicMNList GetListForBlock(gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); - return GetListForBlockInternal(pindex); + const EvoViewToken view{m_evoDb.CurrentView()}; + return GetListForBlockInternal(pindex, m_views.For(view), view); }; CDeterministicMNList GetListAtChainTip() EXCLUSIVE_LOCKS_REQUIRED(!cs); + //! The EvoDB this manager reads, for callers that bind an Evo view. + const CEvoDB& EvoDb() const { return m_evoDb; } void SetListForBlockForTesting(const CDeterministicMNList& list) EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); - mnListsCache.insert_or_assign(list.GetBlockHash(), list); + View().mnListsCache.insert_or_assign(list.GetBlockHash(), list); + } + + /** Test-only hook invoked whenever a list lookup misses both the cache and + * the stored full lists, before diff-chain reconstruction. */ + void SetListSnapshotMissHookForTesting(std::function hook) EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + m_list_snapshot_miss_hook = std::move(hook); + } + + //! Heights of the lists cached for the current view. + std::vector CachedListHeightsForTesting() EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + std::vector heights; + for (const auto& [_, list] : View().mnListsCache) { + heights.push_back(list.GetHeight()); + } + return heights; + } + + //! The tip the current view was last told of. + const CBlockIndex* TipForTesting() EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + return View().tipIndex; } // Test if given TX is a ProRegTx which also contains the collateral at index n @@ -890,8 +934,11 @@ class CDeterministicMNManager [[nodiscard]] bool MigrateLegacyDiffs(const CBlockIndex* const tip_index) EXCLUSIVE_LOCKS_REQUIRED(!cs, ::cs_main); private: - void CleanupCache(int nHeight) EXCLUSIVE_LOCKS_REQUIRED(cs); - CDeterministicMNList GetListForBlockInternal(gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(cs); + static void CleanupCache(ViewState& view, int nHeight); + //! The list for `pindex` in `view_token`, whose partition is `view`. What + //! it reads is cached only if `view_token` is not overtaken by then. + CDeterministicMNList GetListForBlockInternal(gsl::not_null pindex, ViewState& view, + const EvoViewToken& view_token) EXCLUSIVE_LOCKS_REQUIRED(cs); // Helper methods for RecalculateAndRepairDiffs static std::vector CollectSnapshotBlocks(const CBlockIndex* start_index, diff --git a/src/evo/evodb.cpp b/src/evo/evodb.cpp index 9a8df32a2d30..b91d2cd03d43 100644 --- a/src/evo/evodb.cpp +++ b/src/evo/evodb.cpp @@ -87,6 +87,7 @@ CEvoDB::CEvoDB(const util::DbWrapperParams& db_params) : db{util::MakeDbWrapper({db_params.path / "evodb", db_params.memory, db_params.wipe, /*cache_size=*/64 << 20, db_params.options})} { transaction_contexts.emplace(EvoDbIdentity::NORMAL, std::make_unique(*db, DataStream{})); + ++g_view_cache_epoch; } CEvoDB::~CEvoDB() = default; @@ -112,6 +113,13 @@ const CEvoDB::TransactionContext& CEvoDB::GetContext(EvoDbIdentity identity) con return *transaction_contexts.at(identity); } +bool CEvoDB::IsLiveLocked(const EvoViewToken& view) const +{ + if (view.db != this) return false; + if (view.identity == EvoDbIdentity::NORMAL) return true; + return m_snapshot_generation && MakeView(EvoDbIdentity::SNAPSHOT) == view; +} + EvoViewToken CEvoDB::MakeView(EvoDbIdentity identity) const { if (identity == EvoDbIdentity::SNAPSHOT && m_snapshot_generation) { @@ -127,7 +135,9 @@ EvoViewToken CEvoDB::MakeView(EvoDbIdentity identity) const EvoViewToken CEvoDB::ResolveView() const { if (HoldsTransaction()) return MakeView(*active_transaction); - return MakeView(m_default_identity); + EvoViewToken view{MakeView(m_default_identity)}; + view.default_epoch = m_default_epoch; + return view; } EvoViewToken CEvoDB::CurrentView() const @@ -274,7 +284,7 @@ void CEvoDB::BindSnapshotGeneration(std::optional record) transaction_contexts.erase(it); } m_snapshot_generation = std::move(record); - if (!m_snapshot_generation) m_default_identity = EvoDbIdentity::NORMAL; + SetDefaultIdentityLocked(m_snapshot_generation ? m_default_identity : EvoDbIdentity::NORMAL); } bool CEvoDB::TransactionsClean() const @@ -641,7 +651,7 @@ bool CEvoDB::PromoteSnapshotMarkers(const uint256& expected_snapshot_tip) !m_snapshot_generation && !db->Exists(EVODB_DUAL_CHAINSTATE) && !db->Exists(EVODB_SNAPSHOT_MNLIST_HASH) && !db->Exists(EVODB_BACKGROUND_MNLIST_HASH); - if (already_promoted) m_default_identity = EvoDbIdentity::NORMAL; + if (already_promoted) SetDefaultIdentityLocked(EvoDbIdentity::NORMAL); return already_promoted; } if (!IsValid(journal) || journal.tip != expected_snapshot_tip) return false; @@ -670,6 +680,7 @@ bool CEvoDB::PromoteSnapshotMarkers(const uint256& expected_snapshot_tip) if (!db->WriteBatch(batch, /*fSync=*/true)) return false; // The dual-chainstate run is over: the promoted state is the NORMAL // identity, so transaction-less access must resolve there again. - m_default_identity = EvoDbIdentity::NORMAL; + SetDefaultIdentityLocked(EvoDbIdentity::NORMAL); + ++g_view_cache_epoch; return true; } diff --git a/src/evo/evodb.h b/src/evo/evodb.h index d7dc4e454627..4bafd962e96d 100644 --- a/src/evo/evodb.h +++ b/src/evo/evodb.h @@ -15,11 +15,13 @@ #include #include +#include #include #include #include #include #include +#include namespace util { struct DbWrapperParams; @@ -83,8 +85,26 @@ struct EvoViewToken { uint32_t generation{0}; uint256 base{}; int base_height{-1}; + //! For a view resolved through the default identity, the CEvoDB's default + //! epoch at that moment, else 0. It says when the view was resolved, not + //! which view it is, so tokens compare equal without it. + uint64_t default_epoch{0}; - bool operator==(const EvoViewToken&) const = default; + //! Whether a switch of the default identity can overtake this view. + bool ResolvedByDefault() const { return default_epoch != 0; } + + //! Whether `height` is at or below the base of this snapshot view, where it + //! holds only the state its snapshot carried and none of the block bodies. + bool AtOrBelowSnapshotBase(int height) const + { + return identity == EvoDbIdentity::SNAPSHOT && height <= base_height; + } + + bool operator==(const EvoViewToken& other) const + { + return std::tie(db, identity, generation, base, base_height) == + std::tie(other.db, other.identity, other.generation, other.base, other.base_height); + } }; enum class EvoGenerationState : uint8_t { @@ -304,11 +324,22 @@ class CEvoDB // P2P serving) resolve against active-chain state rather than always // falling back to NORMAL. EvoDbIdentity m_default_identity GUARDED_BY(cs){EvoDbIdentity::NORMAL}; + //! Grows, under cs, whenever transaction-less accesses may start resolving + //! to another view: whenever the default identity is set or a snapshot + //! generation is bound or retired, even if that leaves the default view + //! as it was. + std::atomic m_default_epoch{1}; TransactionContext& GetContext(EvoDbIdentity identity) EXCLUSIVE_LOCKS_REQUIRED(cs); const TransactionContext& GetContext(EvoDbIdentity identity) const EXCLUSIVE_LOCKS_REQUIRED(cs); EvoDbIdentity GetCurrentIdentity() const EXCLUSIVE_LOCKS_REQUIRED(cs) { return ResolveView().identity; } EvoViewToken MakeView(EvoDbIdentity identity) const EXCLUSIVE_LOCKS_REQUIRED(cs); + bool IsLiveLocked(const EvoViewToken& view) const EXCLUSIVE_LOCKS_REQUIRED(cs); + void SetDefaultIdentityLocked(EvoDbIdentity identity) EXCLUSIVE_LOCKS_REQUIRED(cs) + { + m_default_identity = identity; + ++m_default_epoch; + } EvoViewToken ResolveView() const EXCLUSIVE_LOCKS_REQUIRED(cs); bool HoldsTransaction() const EXCLUSIVE_LOCKS_REQUIRED(cs) { @@ -335,6 +366,40 @@ class CEvoDB return HoldsTransaction(); } + //! Changes whenever cached Evo-derived state of every view may have gone + //! stale: a CEvoDB was opened, or a snapshot generation was promoted into + //! NORMAL. EvoViewCache drops every partition when it changes. Retiring a + //! generation any other way leaves NORMAL untouched. + static uint64_t ViewCacheEpoch() { return g_view_cache_epoch.load(); } + //! Run `f(ViewCacheEpoch(), live_generation, overtaken)` if `view` is a + //! live view of this CEvoDB (NORMAL, or the snapshot generation bound now, + //! published or not), and return whether it ran. `live_generation` is that + //! bound generation, or 0 if there is none; `overtaken` is + //! IsOvertaken(view). `f` runs under the lock that retires generations and + //! switches the default identity, so neither happens before `f` returns. + //! `f` must not call back into this CEvoDB. + template + bool WithLiveView(const EvoViewToken& view, F&& f) const EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + if (view.db != this) return false; + LOCK(cs); + if (!IsLiveLocked(view)) return false; + f(g_view_cache_epoch.load(), m_snapshot_generation ? m_snapshot_generation->generation : uint32_t{0}, + IsOvertaken(view)); + return true; + } + + //! Whether `view` was resolved through the default identity and + //! transaction-less accesses may have resolved to another view since. A + //! value derived from reads made after `view` was resolved then may mix + //! views, and must not be stored as `view`'s. Ask after the last such read: + //! the default epoch only grows, so a view that is not overtaken then was + //! not overtaken during the reads. + bool IsOvertaken(const EvoViewToken& view) const + { + return view.ResolvedByDefault() && view.default_epoch != m_default_epoch.load(); + } + //! The view this thread's Evo accesses resolve to: its open transaction, //! else the default identity. EvoViewToken CurrentView() const EXCLUSIVE_LOCKS_REQUIRED(!cs); @@ -408,6 +473,23 @@ class CEvoDB return db->WriteBatch(batch); } + /** WriteImmediate in `view`, which must still be the current view of its + * identity and not overtaken (IsOvertaken): once a snapshot generation has + * been discarded or replaced, or the default identity has moved on, a + * write decided under it is dropped and this returns false. */ + template + bool WriteImmediate(const EvoViewToken& view, const K& key, const V& value) EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + if (MakeView(view.identity) != view || IsOvertaken(view)) return false; + const auto& store{GetContext(view.identity).store}; + CDBBatch batch{*db}; + DataStream ssKey{}; + ssKey << key; + batch.Write(store.Key(ssKey), value); + return db->WriteBatch(batch); + } + /** Write `value` under `key` as WriteDerived does, as part of a snapshot * generation's seed. In a SNAPSHOT view, which must be an unpublished * generation, the key is also recorded in the generation's seed manifest, @@ -483,7 +565,7 @@ class CEvoDB void SetDefaultIdentity(EvoDbIdentity identity) EXCLUSIVE_LOCKS_REQUIRED(!cs) { LOCK(cs); - m_default_identity = identity; + SetDefaultIdentityLocked(identity); } bool ReadBestBlock(EvoDbIdentity identity, uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(!cs); @@ -594,6 +676,8 @@ class CEvoDB bool MergeGeneration(EvoPromotionJournal& journal) EXCLUSIVE_LOCKS_REQUIRED(cs); bool DiscardBoundGeneration() EXCLUSIVE_LOCKS_REQUIRED(cs); + static inline std::atomic g_view_cache_epoch{0}; + //! The live generation the SNAPSHOT identity reads and writes. std::optional m_snapshot_generation GUARDED_BY(cs); PromotionFailpoint m_promotion_failpoint GUARDED_BY(cs){PromotionFailpoint::NONE}; diff --git a/src/evo/mnhftx.cpp b/src/evo/mnhftx.cpp index 03235efd2e67..c6f3a62a359e 100644 --- a/src/evo/mnhftx.cpp +++ b/src/evo/mnhftx.cpp @@ -51,6 +51,7 @@ CMNHFManager::CMNHFManager(CEvoDB& evoDb, const node::BlockManager& blockman, co m_consensus_params{consensus_params}, m_notifications{notifications} { + mnhfCache.SetOwner(evoDb); assert(globalInstance == nullptr); globalInstance = this; } @@ -288,6 +289,13 @@ bool CMNHFManager::UndoBlock(const CBlock& block, const CBlockIndex* const pinde CMNHFManager::Signals CMNHFManager::GetForBlock(const CBlockIndex* pindex) { if (auto signals = GetFromCache(pindex)) return *signals; + // A snapshot view holds only what its snapshot carried and its chainstate + // connected: what else it lacks is unavailable to it, never a statement + // about the block. + if (m_evoDb.CurrentView().identity == EvoDbIdentity::SNAPSHOT) { + throw BlockDataUnavailableError(strprintf("MNHF signals unavailable for block %s in the snapshot view", + pindex->GetBlockHash().ToString())); + } throw EvoDbMissingStateError(strprintf("MNHF signals unavailable for block %s", pindex->GetBlockHash().ToString())); } @@ -295,10 +303,14 @@ void CMNHFManager::RebuildSignals(const CBlockIndex* pindex) { AssertLockHeld(::cs_main); + const EvoViewToken view{m_evoDb.CurrentView()}; std::stack to_calculate; std::optional signalsTmp; while (!(signalsTmp = GetFromCache(pindex)).has_value()) { + if (view.AtOrBelowSnapshotBase(pindex->nHeight)) { + throw BlockDataUnavailableError("failed-getehfforblock-below-snapshot-base"); + } // Only the level counts: a block that was connected and later invalidated did pass validation. if ((pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) { throw std::runtime_error("failed-getehfforblock-unvalidated"); @@ -351,29 +363,27 @@ std::optional CMNHFManager::GetFromCache(const CBlockInde const uint256& blockHash = pindex->GetBlockHash(); - { - LOCK(cs_cache); - if (mnhfCache.get(blockHash, signals)) { - return signals; - } + const EvoViewToken view{m_evoDb.CurrentView()}; + if (WITH_LOCK(cs_cache, return mnhfCache.For(view).get(blockHash, signals))) { + return signals; } { LOCK(cs_cache); if (!DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_V20)) { - mnhfCache.insert(blockHash, signals); + mnhfCache.For(view).insert(blockHash, signals); return signals; } } if (m_evoDb.Read(std::make_pair(DB_SIGNALS_v2, blockHash), signals)) { LOCK(cs_cache); - mnhfCache.insert(blockHash, signals); + mnhfCache.For(view).insert(blockHash, signals); return signals; } if (!DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_MN_RR)) { // before mn_rr activation we are safe if (m_evoDb.Read(std::make_pair(DB_SIGNALS, blockHash), signals)) { LOCK(cs_cache); - mnhfCache.insert(blockHash, signals); + mnhfCache.For(view).insert(blockHash, signals); return signals; } } @@ -395,10 +405,9 @@ void CMNHFManager::AddToCache(const Signals& signals, const CBlockIndex* const p m_notifications.fatalError(msg); throw EvoDbInconsistencyError(msg); } - { - LOCK(cs_cache); - mnhfCache.insert(blockHash, signals); - } + const EvoViewToken view{m_evoDb.CurrentView()}; + LOCK(cs_cache); + mnhfCache.For(view).insert(blockHash, signals); } bool CMNHFManager::ForceSignalDBUpdate(const CBlockIndex* tip) diff --git a/src/evo/mnhftx.h b/src/evo/mnhftx.h index 72d405a9d96f..c883a21e1c83 100644 --- a/src/evo/mnhftx.h +++ b/src/evo/mnhftx.h @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -109,7 +110,8 @@ class CMNHFManager : public AbstractEHFManager static constexpr size_t MNHFCacheSize = 1000; Mutex cs_cache; // versionBit <-> height - Uint256LruHashMap mnhfCache GUARDED_BY(cs_cache){MNHFCacheSize}; + EvoViewCache> mnhfCache GUARDED_BY(cs_cache){ + [] { return Uint256LruHashMap{MNHFCacheSize}; }}; public: CMNHFManager() = delete; @@ -143,8 +145,9 @@ class CMNHFManager : public AbstractEHFManager /** * Recompute missing state from block data, walking back from pindex to the first block whose - * state is stored. Throws for a block that did not pass script validation. Only for startup, - * inside an EvoDB transaction: pindex must be a block that was connected. + * state is stored. Throws for a block that did not pass script validation, and + * BlockDataUnavailableError for a block at or below the base of a snapshot view. Only for + * startup, inside an EvoDB transaction: pindex must be a block that was connected. */ void RebuildSignals(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache); @@ -153,7 +156,8 @@ class CMNHFManager : public AbstractEHFManager /** * Returns the signals stored for pindex, from the cache or evo db. Throws EvoDbMissingStateError - * if there are none, e.g. because the block was never connected. + * if there are none, e.g. because the block was never connected, or BlockDataUnavailableError + * in a snapshot view, which lacks what its snapshot did not carry. * NOTE: that some signals could expired between blocks. */ Signals GetForBlock(const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); diff --git a/src/evo/smldiff.cpp b/src/evo/smldiff.cpp index 6413b3bf58c1..9f417611b4ea 100644 --- a/src/evo/smldiff.cpp +++ b/src/evo/smldiff.cpp @@ -21,7 +21,9 @@ // Forward declaration -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex); +std::optional> GetNonNullCoinbaseChainlock(const EvoViewToken& view, + const node::BlockManager& blockman, + const CBlockIndex* pindex); CSimplifiedMNListDiff::CSimplifiedMNListDiff() = default; @@ -94,7 +96,7 @@ bool CSimplifiedMNListDiff::BuildQuorumChainlockInfo(const llmq::CQuorumManager& for (auto it = workBaseBlockIndexMap.begin(); it != workBaseBlockIndexMap.end();) { // Process each key (CBlockIndex containing the expected CL signature in CbTx) of the std::multimap once const CBlockIndex* pWorkBaseBlockIndex = it->first; - const auto cbcl = GetNonNullCoinbaseChainlock(blockman, pWorkBaseBlockIndex); + const auto cbcl = GetNonNullCoinbaseChainlock(qman.CurrentView(), blockman, pWorkBaseBlockIndex); CBLSSignature sig; if (cbcl.has_value()) { sig = cbcl.value().first; diff --git a/src/evo/specialtxman.cpp b/src/evo/specialtxman.cpp index b1a64860b094..126973dd0ee9 100644 --- a/src/evo/specialtxman.cpp +++ b/src/evo/specialtxman.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -155,6 +156,7 @@ bool CheckCbTxBestChainlock(const CCbTx& cbTx, const CBlockIndex* pindex, const } const CBLSSignature& cbtx_sig{cbTx.bestCLSignature.Get()}; + // The previous block's coinbase ChainLock, remembered per Evo view. struct CachedChainlock { const CBlockIndex* pindex{nullptr}; CBLSSignature sig; @@ -164,24 +166,28 @@ bool CheckCbTxBestChainlock(const CCbTx& cbTx, const CBlockIndex* pindex, const bool verified_here{false}; }; static Mutex cached_mutex; - static std::optional cached GUARDED_BY(cached_mutex); + static EvoViewCache> cached_by_view GUARDED_BY(cached_mutex); + const EvoViewToken view{qman.CurrentView()}; auto best_clsig = chainlocks.GetBestChainLock(); if (best_clsig.getHeight() == pindex->nHeight - 1 && cbTx.bestCLHeightDiff == 0 && cbtx_sig == best_clsig.getSig()) { // matches our best clsig which still hold values for the previous block - WITH_LOCK(cached_mutex, cached.emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, /*verified_here=*/false)); + WITH_LOCK(cached_mutex, + cached_by_view.For(view).emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, /*verified_here=*/false)); return true; } std::optional> prevBlockCoinbaseChainlock{std::nullopt}; bool prev_verified_here{false}; - if (LOCK(cached_mutex); cached && cached->pindex == pindex->pprev) { - prevBlockCoinbaseChainlock = std::make_pair(cached->sig, cached->height_diff); - prev_verified_here = cached->verified_here; + if (LOCK(cached_mutex); const auto& cached{cached_by_view.For(view)}) { + if (cached->pindex == pindex->pprev) { + prevBlockCoinbaseChainlock = std::make_pair(cached->sig, cached->height_diff); + prev_verified_here = cached->verified_here; + } } if (!prevBlockCoinbaseChainlock.has_value()) { - prevBlockCoinbaseChainlock = GetNonNullCoinbaseChainlock(blockman, pindex->pprev); + prevBlockCoinbaseChainlock = GetNonNullCoinbaseChainlock(view, blockman, pindex->pprev); } // If std::optional prevBlockCoinbaseChainlock is empty, then up to the previous block, coinbase Chainlock is null. if (prevBlockCoinbaseChainlock.has_value()) { @@ -204,7 +210,8 @@ bool CheckCbTxBestChainlock(const CCbTx& cbTx, const CBlockIndex* pindex, const int curBlockCoinbaseCLHeight = pindex->nHeight - static_cast(cbTx.bestCLHeightDiff) - 1; if (best_clsig.getHeight() == curBlockCoinbaseCLHeight && best_clsig.getSig() == cbtx_sig) { // matches our best (but outdated) clsig, no need to verify it again - WITH_LOCK(cached_mutex, cached.emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, /*verified_here=*/false)); + WITH_LOCK(cached_mutex, cached_by_view.For(view).emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, + /*verified_here=*/false)); return true; } // The previous block's coinbase chainlock was verified by this process; carried into this @@ -212,7 +219,8 @@ bool CheckCbTxBestChainlock(const CCbTx& cbTx, const CBlockIndex* pindex, const if (prev_verified_here && prevBlockCoinbaseChainlock.has_value() && cbTx.bestCLHeightDiff == prevBlockCoinbaseChainlock->second + 1 && cbtx_sig == prevBlockCoinbaseChainlock->first) { - WITH_LOCK(cached_mutex, cached.emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, /*verified_here=*/true)); + WITH_LOCK(cached_mutex, cached_by_view.For(view).emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, + /*verified_here=*/true)); return true; } const CBlockIndex* pAncestor = pindex->GetAncestor(curBlockCoinbaseCLHeight); @@ -227,7 +235,8 @@ bool CheckCbTxBestChainlock(const CCbTx& cbTx, const CBlockIndex* pindex, const if (ret != llmq::VerifyRecSigStatus::Valid) { return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cbtx-invalid-clsig"); } - WITH_LOCK(cached_mutex, cached.emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, /*verified_here=*/true)); + WITH_LOCK(cached_mutex, cached_by_view.For(view).emplace(pindex, cbtx_sig, cbTx.bestCLHeightDiff, + /*verified_here=*/true)); } else if (cbTx.bestCLHeightDiff != 0) { // Null bestCLSignature is allowed only with bestCLHeightDiff = 0 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cbtx-cldiff"); diff --git a/src/evo/viewcache.h b/src/evo/viewcache.h new file mode 100644 index 000000000000..49b7c8704803 --- /dev/null +++ b/src/evo/viewcache.h @@ -0,0 +1,115 @@ +// Copyright (c) 2026 The Dash Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_EVO_VIEWCACHE_H +#define BITCOIN_EVO_VIEWCACHE_H + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +/** A cache of Evo-derived state, partitioned by Evo view so that state derived + * under one view is never served to another. A retired snapshot generation's + * partitions are dropped at the next lookup, and every partition when a + * generation is promoted into NORMAL. Callers resolve the view + * once per operation, before its first Evo read. Not thread-safe: guard it + * with the owner's lock. + * + * A view overtaken by a switch of the default identity (CEvoDB::IsOvertaken) + * gets a scratch partition: lookups miss and what is stored in it is + * dropped. So take the partition a value is stored in after the reads the + * value derives from, never before them: a value whose reads straddled the + * switch then never reaches the partition of the view it was resolved under. + * An erase through an overtaken view is dropped too, so invalidate through a + * view no switch overtakes: a transaction's, or one named with ViewFor(). + * + * For() may drop every partition, so a reference it returned is valid only + * until the next For() on the same cache: never hold one across another + * For() call, and hand out shared_ptr partitions when a reference must + * outlive the owner's lock. `make` may run under CEvoDB::cs, so it must not + * call into the CEvoDB. */ +template +class EvoViewCache +{ +public: + explicit EvoViewCache(std::function make = [] { return T{}; }) : + m_make{std::move(make)} + { + } + + //! Restrict the cache to views of `owner`. + void SetOwner(const CEvoDB& owner) { m_owner = &owner; } + + //! The partition of `view`, which must be a live view of the owner's + //! CEvoDB: a retired snapshot generation or another CEvoDB's view raises + //! EvoViewBindingError before any partition is touched. An overtaken view + //! gets an empty scratch partition. + T& For(const EvoViewToken& view) + { + if (view.db == nullptr || (m_owner != nullptr && view.db != m_owner)) { + throw EvoViewBindingError("Evo view cache: view of another EvoDB"); + } + // The partitions are checked against the epoch, and the partition of + // `view` found, while its generation is held live; dropped partitions + // are destroyed after CEvoDB::cs is released. + std::map dropped; + T* part{nullptr}; + const bool live{view.db->WithLiveView(view, [&](uint64_t epoch, uint32_t live_generation, bool overtaken) { + if (epoch > m_epoch) { + dropped.swap(m_parts); + m_epoch = epoch; + } + for (auto it{m_parts.begin()}; it != m_parts.end();) { + const auto& [db, identity, generation] = it->first; + if (db == view.db && identity == EvoDbIdentity::SNAPSHOT && generation != live_generation) { + dropped.insert(m_parts.extract(it++)); + } else { + ++it; + } + } + if (overtaken) return; + const Key key{view.db, view.identity, view.generation}; + auto it{m_parts.find(key)}; + if (it == m_parts.end()) it = m_parts.emplace(key, m_make()).first; + part = &it->second; + })}; + if (!live) { + throw EvoViewBindingError(strprintf("Evo view cache: snapshot generation %u is retired", view.generation)); + } + if (part == nullptr) return m_overtaken.emplace(m_make()); + m_overtaken.reset(); + return *part; + } + + template + void ForEach(F&& f) + { + for (auto& [_, part] : m_parts) + f(part); + } + + void Clear() + { + m_parts.clear(); + m_overtaken.reset(); + } + +private: + using Key = std::tuple; + + std::function m_make; + const CEvoDB* m_owner{nullptr}; + std::map m_parts; + std::optional m_overtaken; + uint64_t m_epoch{CEvoDB::ViewCacheEpoch()}; +}; + +#endif // BITCOIN_EVO_VIEWCACHE_H diff --git a/src/llmq/blockprocessor.cpp b/src/llmq/blockprocessor.cpp index b6917a17cd1d..a3c91bc25bb1 100644 --- a/src/llmq/blockprocessor.cpp +++ b/src/llmq/blockprocessor.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -78,15 +79,21 @@ static bool SerializedEqual(const T& lhs, const T& rhs) std::equal(lhs_stream.begin(), lhs_stream.end(), rhs_stream.begin()); } -CQuorumBlockProcessor::CQuorumBlockProcessor(ChainstateManager& chainman, CDeterministicMNManager& dmnman, CEvoDB& evoDb, - CQuorumSnapshotManager& qsnapman, int8_t bls_threads) : +CQuorumBlockProcessor::CQuorumBlockProcessor(ChainstateManager& chainman, CDeterministicMNManager& dmnman, + CEvoDB& evoDb, CQuorumSnapshotManager& qsnapman, int8_t bls_threads) : m_chainman{chainman}, m_dmnman{dmnman}, m_evoDb{evoDb}, m_qsnapman{qsnapman}, - m_bls_queue{/*batch_size=*/4, bls_threads} + m_bls_queue{/*batch_size=*/4, bls_threads}, + mapMinedCommitmentBlockCache{[&consensus = chainman.GetConsensus()] { + PerLlmqTypeCache cache; + cache.Init(consensus); + return cache; + }} { - mapMinedCommitmentBlockCache.Init(m_chainman.GetConsensus()); + mapMinedCommitmentBlockCache.SetOwner(evoDb); + m_qc_hashes.SetOwner(evoDb); LogPrintf("BLS verification uses %d additional threads\n", bls_threads); } @@ -455,7 +462,10 @@ bool CQuorumBlockProcessor::ProcessCommitment(Chainstate& chainstate, int nHeigh // invalidation should not depend on that. DropQcHashesCache(llmq_params.type, quorumHash); - WITH_LOCK(minableCommitmentsCs, mapMinedCommitmentBlockCache.erase(qc.llmqType, qc.quorumHash)); + { + const EvoViewToken view{m_evoDb.CurrentView()}; + WITH_LOCK(minableCommitmentsCs, mapMinedCommitmentBlockCache.For(view).erase(qc.llmqType, qc.quorumHash)); + } LogPrint(BCLog::LLMQ, "%s -- processed commitment from block. type=%d, quorumIndex=%d, quorumHash=%s\n", __func__, std23::to_underlying(qc.llmqType), qc.quorumIndex, quorumHash.ToString()); @@ -466,41 +476,45 @@ bool CQuorumBlockProcessor::ProcessCommitment(Chainstate& chainstate, int nHeigh void CQuorumBlockProcessor::DropQcHashesCache(Consensus::LLMQType llmqType, const uint256& quorumHash) { LOCK(m_qc_hashes_cache_mutex); - m_quorums_cached.clear(); - m_qc_hashes_cached.clear(); - m_qc_indexed_hashes_cached.clear(); - m_qc_hashes_lru.erase(llmqType, quorumHash); + m_qc_hashes.ForEach([&](QcHashesCache& cache) { + cache.m_quorums_cached.clear(); + cache.m_qc_hashes_cached.clear(); + cache.m_qc_indexed_hashes_cached.clear(); + cache.m_qc_hashes_lru.erase(llmqType, quorumHash); + }); } std::optional> CQuorumBlockProcessor::GetQcHashes(const CBlockIndex* pindexPrev) const { - auto quorums = GetActiveCommitmentsCached(pindexPrev); + const EvoViewToken view{m_evoDb.CurrentView()}; + auto quorums = GetActiveCommitmentsCached(view, pindexPrev); LOCK(m_qc_hashes_cache_mutex); - if (quorums == m_quorums_cached) { - return std::make_pair(m_qc_hashes_cached, m_qc_indexed_hashes_cached); + auto& cache = m_qc_hashes.For(view); + if (quorums == cache.m_quorums_cached) { + return std::make_pair(cache.m_qc_hashes_cached, cache.m_qc_indexed_hashes_cached); } // Quorums set is different, reset cached values - m_quorums_cached.clear(); - m_qc_hashes_cached.clear(); - m_qc_indexed_hashes_cached.clear(); - if (!m_qc_hashes_lru.IsInitialized()) { - m_qc_hashes_lru.Init(m_chainman.GetConsensus()); + cache.m_quorums_cached.clear(); + cache.m_qc_hashes_cached.clear(); + cache.m_qc_indexed_hashes_cached.clear(); + if (!cache.m_qc_hashes_lru.IsInitialized()) { + cache.m_qc_hashes_lru.Init(m_chainman.GetConsensus()); } for (const auto& [llmqType, vecBlockIndexes] : quorums) { const auto& llmq_params_opt = m_chainman.GetParams().GetLLMQ(llmqType); assert(llmq_params_opt.has_value()); bool rotation_enabled = IsQuorumRotationEnabled(llmq_params_opt.value(), pindexPrev); - auto& vec_hashes = m_qc_hashes_cached[llmqType]; + auto& vec_hashes = cache.m_qc_hashes_cached[llmqType]; vec_hashes.reserve(vecBlockIndexes.size()); - auto& map_indexed_hashes = m_qc_indexed_hashes_cached[llmqType]; + auto& map_indexed_hashes = cache.m_qc_indexed_hashes_cached[llmqType]; for (const auto& blockIndex : vecBlockIndexes) { uint256 block_hash{blockIndex->GetBlockHash()}; std::pair qc_hash; - if (!m_qc_hashes_lru.get(llmqType, block_hash, qc_hash)) { + if (!cache.m_qc_hashes_lru.get(llmqType, block_hash, qc_hash)) { auto [pqc, dummy_hash] = GetMinedCommitment(llmqType, block_hash); if (dummy_hash == uint256::ZERO) { // this should never happen @@ -508,7 +522,7 @@ std::optional> CQuorumBlockProcessor::Get } qc_hash.first = ::SerializeHash(pqc); qc_hash.second = rotation_enabled ? pqc.quorumIndex : 0; - m_qc_hashes_lru.insert(llmqType, block_hash, qc_hash); + cache.m_qc_hashes_lru.insert(llmqType, block_hash, qc_hash); } if (rotation_enabled) { map_indexed_hashes[qc_hash.second] = qc_hash.first; @@ -517,8 +531,8 @@ std::optional> CQuorumBlockProcessor::Get } } } - std::swap(m_quorums_cached, quorums); - return std::make_pair(m_qc_hashes_cached, m_qc_indexed_hashes_cached); + std::swap(cache.m_quorums_cached, quorums); + return std::make_pair(cache.m_qc_hashes_cached, cache.m_qc_indexed_hashes_cached); } bool CQuorumBlockProcessor::UndoBlock(const Chainstate& chainstate, const CBlock& block, gsl::not_null pindex) @@ -529,8 +543,10 @@ bool CQuorumBlockProcessor::UndoBlock(const Chainstate& chainstate, const CBlock { LOCK(m_qc_hashes_cache_mutex); - m_active_quorums_block.SetNull(); - m_active_quorums.clear(); + m_qc_hashes.ForEach([](QcHashesCache& cache) { + cache.m_active_quorums_block.SetNull(); + cache.m_active_quorums.clear(); + }); m_recent_mined.clear(); } @@ -562,7 +578,8 @@ bool CQuorumBlockProcessor::UndoBlock(const Chainstate& chainstate, const CBlock // Only once this commitment's state change is complete; see ProcessCommitment. DropQcHashesCache(qc.llmqType, qc.quorumHash); - WITH_LOCK(minableCommitmentsCs, mapMinedCommitmentBlockCache.erase(qc.llmqType, qc.quorumHash)); + const EvoViewToken view{m_evoDb.CurrentView()}; + WITH_LOCK(minableCommitmentsCs, mapMinedCommitmentBlockCache.For(view).erase(qc.llmqType, qc.quorumHash)); // if a reorg happened, we should allow to mine this commitment later AddMineableCommitment(qc); @@ -687,11 +704,50 @@ uint256 CQuorumBlockProcessor::GetQuorumBlockHash(const Consensus::LLMQParams& l return pindex->GetBlockHash(); } +//! Whether `view` is a snapshot view lacking quorum history: it holds the +//! commitments mined above its base and none at or below it, where DIP3 may +//! already have let quorums be mined. +static bool LacksQuorumHistory(const EvoViewToken& view, const Consensus::Params& consensus) +{ + return view.identity == EvoDbIdentity::SNAPSHOT && view.base_height >= consensus.DIP0003Height; +} + +//! Whether a height-index scan from `pindex` reaches history such a view +//! lacks: a commitment of `llmqType` may have been mined at a height up to +//! both `pindex` and the base. None can be below DIP3 or in genesis. A +//! deployment-gated type stays enabled once enabled, and the types DIP0024 +//! retires are enabled from DIP3 on, so a type enabled at neither end of that +//! range has none in it. +//! Evaluated before taking the EvoDB lock: deployment state may read EvoDB. +static bool ScanNeedsMissingHistory(const ChainstateManager& chainman, const EvoViewToken& view, + Consensus::LLMQType llmqType, const CBlockIndex* pindex) +{ + const auto& consensus{chainman.GetConsensus()}; + if (!LacksQuorumHistory(view, consensus)) return false; + const int first_minable_height{std::max(1, consensus.DIP0003Height)}; + const int last_missing_height{std::min(pindex->nHeight, view.base_height)}; + if (last_missing_height < first_minable_height) return false; + const CBlockIndex* last_missing{pindex->GetAncestor(last_missing_height)}; + if (chainman.IsQuorumTypeEnabled(llmqType, last_missing->pprev)) return true; + const CBlockIndex* first_minable{pindex->GetAncestor(first_minable_height)}; + return chainman.IsQuorumTypeEnabled(llmqType, first_minable->pprev); +} + +//! A short scan that needs the missing history has an unknown result, not a +//! short one. +static void RequireSatisfiedScan(bool needs_missing_history, const char* func, Consensus::LLMQType llmqType) +{ + if (!needs_missing_history) return; + throw BlockDataUnavailableError( + strprintf("%s: commitments of LLMQ type %d at or below the snapshot base are not available", func, + std23::to_underlying(llmqType))); +} + bool CQuorumBlockProcessor::HasMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash) const { - Assume(m_evoDb.ReadsActiveView()); LOCK(::cs_main); - return HasMinedCommitment(llmqType, quorumHash, m_chainman.ActiveChain()); + const CChain* chain{m_chainman.EvoChain(m_evoDb.CurrentView().identity)}; + return HasMinedCommitment(llmqType, quorumHash, chain ? *chain : m_chainman.ActiveChain()); } bool CQuorumBlockProcessor::HasMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash, @@ -701,9 +757,10 @@ bool CQuorumBlockProcessor::HasMinedCommitment(Consensus::LLMQType llmqType, con uint256 mined_block_hash; bool cached; + const EvoViewToken view{m_evoDb.CurrentView()}; { LOCK(minableCommitmentsCs); - cached = mapMinedCommitmentBlockCache.get(llmqType, quorumHash, mined_block_hash); + cached = mapMinedCommitmentBlockCache.For(view).get(llmqType, quorumHash, mined_block_hash); } if (!cached) { mined_block_hash = GetMinedCommitment(llmqType, quorumHash).second; @@ -711,7 +768,16 @@ bool CQuorumBlockProcessor::HasMinedCommitment(Consensus::LLMQType llmqType, con // outside ProcessCommitment's normal cache-invalidation path. if (!mined_block_hash.IsNull()) { LOCK(minableCommitmentsCs); - mapMinedCommitmentBlockCache.insert(llmqType, quorumHash, mined_block_hash); + mapMinedCommitmentBlockCache.For(view).insert(llmqType, quorumHash, mined_block_hash); + } else if (LacksQuorumHistory(view, m_chainman.GetConsensus())) { + // A quorum based at or below the base may have been mined there, in + // history the view lacks: the miss does not mean it never was. + const CBlockIndex* quorum_base{m_chainman.m_blockman.LookupBlockIndex(quorumHash)}; + if (quorum_base != nullptr && view.AtOrBelowSnapshotBase(quorum_base->nHeight)) { + throw BlockDataUnavailableError( + strprintf("%s: commitment for quorum %s at or below the snapshot base is not available", __func__, + quorumHash.ToString())); + } } } @@ -734,6 +800,8 @@ std::pair CQuorumBlockProcessor::GetMinedCommitment(C std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilBlock(Consensus::LLMQType llmqType, gsl::not_null pindex, size_t maxCount) const { AssertLockNotHeld(m_evoDb.cs); + const bool needs_missing_history{ + ScanNeedsMissingHistory(m_chainman, m_evoDb.CurrentView(), llmqType, pindex)}; LOCK(m_evoDb.cs); auto dbIt = m_evoDb.GetCurTransaction().NewIteratorUniquePtr(); @@ -772,12 +840,19 @@ std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilB dbIt->Next(); } + if (ret.size() < maxCount) RequireSatisfiedScan(needs_missing_history, __func__, llmqType); return ret; } std::optional CQuorumBlockProcessor::GetLastMinedCommitmentsByQuorumIndexUntilBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex, int quorumIndex, size_t cycle) const { AssertLockNotHeld(m_evoDb.cs); + const bool needs_missing_history{ + ScanNeedsMissingHistory(m_chainman, m_evoDb.CurrentView(), llmqType, pindex)}; + const auto not_found{[&]() -> std::optional { + RequireSatisfiedScan(needs_missing_history, "GetLastMinedCommitmentsByQuorumIndexUntilBlock", llmqType); + return std::nullopt; + }}; LOCK(m_evoDb.cs); auto dbIt = m_evoDb.GetCurTransaction().NewIteratorUniquePtr(); @@ -793,19 +868,19 @@ std::optional CQuorumBlockProcessor::GetLastMinedCommitments decltype(firstKey) curKey; int quorumHeight; if (!dbIt->GetKey(curKey) || curKey >= lastKey) { - return std::nullopt; + return not_found(); } if (std::get<0>(curKey) != DB_MINED_COMMITMENT_BY_INVERSED_HEIGHT_Q_INDEXED || std::get<1>(curKey) != llmqType) { - return std::nullopt; + return not_found(); } if (uint32_t nMinedHeight = std::numeric_limits::max() - be32toh_internal(std::get<3>(curKey)); nMinedHeight > static_cast(pindex->nHeight)) { - return std::nullopt; + return not_found(); } if (!dbIt->GetValue(quorumHeight)) { - return std::nullopt; + return not_found(); } const auto* pQuorumBaseBlockIndex = pindex->GetAncestor(quorumHeight); @@ -820,7 +895,7 @@ std::optional CQuorumBlockProcessor::GetLastMinedCommitments dbIt->Next(); } - return std::nullopt; + return not_found(); } std::vector CQuorumBlockProcessor::GetLastMinedCommitmentsPerQuorumIndexUntilBlock( @@ -979,11 +1054,12 @@ CQuorumBlockProcessor::ActiveQuorums CQuorumBlockProcessor::WalkActiveQuorums(gs return ret; } -std::optional CQuorumBlockProcessor::DeriveActiveQuorums(gsl::not_null pindex) const +std::optional CQuorumBlockProcessor::DeriveActiveQuorums( + const QcHashesCache& cache, gsl::not_null pindex) const { AssertLockHeld(m_qc_hashes_cache_mutex); - if (pindex->pprev == nullptr || m_active_quorums_block != pindex->pprev->GetBlockHash()) { + if (pindex->pprev == nullptr || cache.m_active_quorums_block != pindex->pprev->GetBlockHash()) { return std::nullopt; } const uint256 block_hash{pindex->GetBlockHash()}; @@ -993,7 +1069,7 @@ std::optional CQuorumBlockProcessor::Deriv return std::nullopt; } - ActiveQuorums ret{m_active_quorums}; + ActiveQuorums ret{cache.m_active_quorums}; for (const auto& params : m_chainman.GetConsensus().llmqs) { const bool rotation = IsQuorumRotationEnabled(params, pindex); if (rotation != IsQuorumRotationEnabled(params, pindex->pprev)) { @@ -1044,19 +1120,22 @@ std::map> CQuorumBlockProce } std::map> CQuorumBlockProcessor::GetActiveCommitmentsCached( - gsl::not_null pindex) const + const EvoViewToken& view, gsl::not_null pindex) const { LOCK(m_qc_hashes_cache_mutex); - if (m_active_quorums_block != pindex->GetBlockHash()) { - if (auto derived = DeriveActiveQuorums(pindex)) { - m_active_quorums = std::move(*derived); - } else { - m_active_quorums = WalkActiveQuorums(pindex); - } - m_active_quorums_block = pindex->GetBlockHash(); - } - return ToQuorumBases(m_active_quorums); + const uint256 block_hash{pindex->GetBlockHash()}; + const auto& cached = m_qc_hashes.For(view); + if (cached.m_active_quorums_block == block_hash) { + return ToQuorumBases(cached.m_active_quorums); + } + auto derived = DeriveActiveQuorums(cached, pindex); + ActiveQuorums active{derived ? std::move(*derived) : WalkActiveQuorums(pindex)}; + // Stored after the reads it derives from; see EvoViewCache. + auto& cache = m_qc_hashes.For(view); + cache.m_active_quorums = active; + cache.m_active_quorums_block = block_hash; + return ToQuorumBases(active); } bool CQuorumBlockProcessor::HasMineableCommitment(const uint256& hash) const diff --git a/src/llmq/blockprocessor.h b/src/llmq/blockprocessor.h index b68768e84dbf..8ce8189342dd 100644 --- a/src/llmq/blockprocessor.h +++ b/src/llmq/blockprocessor.h @@ -7,6 +7,7 @@ #include #include +#include #include // IWYU pragma: export #include #include @@ -76,7 +77,7 @@ class CQuorumBlockProcessor // Cache the block in which a commitment was mined. Membership in a // particular chain is checked on every call so reorgs need no cache flush. - mutable PerLlmqTypeCache mapMinedCommitmentBlockCache GUARDED_BY(minableCommitmentsCs); + mutable EvoViewCache> mapMinedCommitmentBlockCache GUARDED_BY(minableCommitmentsCs); // Memoizes GetQcHashes(). The whole-result cache is keyed on the set of active // quorum base blocks, the LRU on those base-block hashes; neither key identifies @@ -85,11 +86,30 @@ class CQuorumBlockProcessor // DropQcHashesCache). Owning them here keeps that invalidation next to the writes it // has to follow, and ties their lifetime to the block index whose CBlockIndex* the // outer cache stores. + // + // The active quorum set of a block is its parent's set plus the commitments the block + // mined, so the lookup for consecutive blocks derives it from the previous answer instead + // of walking the mined-commitment tables (one iterator seek per quorum index for rotation). + // The set depends on the EvoDB view it is read through, so it is kept per view with the + // rest; only GetQcHashes uses it, history lookups (MN list diffs, quorum proofs) always walk. + // What a block mined is a property of the block, so m_recent_mined is shared. mutable Mutex m_qc_hashes_cache_mutex; - mutable std::map> m_quorums_cached GUARDED_BY(m_qc_hashes_cache_mutex); - mutable PerLlmqTypeCache> m_qc_hashes_lru GUARDED_BY(m_qc_hashes_cache_mutex); - mutable QcHashMap m_qc_hashes_cached GUARDED_BY(m_qc_hashes_cache_mutex); - mutable QcIndexedHashMap m_qc_indexed_hashes_cached GUARDED_BY(m_qc_hashes_cache_mutex); + struct MinedCommitmentRef { + Consensus::LLMQType type; + int quorumIndex; + const CBlockIndex* base; + }; + using ActiveQuorums = std::map>>; + struct QcHashesCache { + std::map> m_quorums_cached; + PerLlmqTypeCache> m_qc_hashes_lru; + QcHashMap m_qc_hashes_cached; + QcIndexedHashMap m_qc_indexed_hashes_cached; + uint256 m_active_quorums_block; + ActiveQuorums m_active_quorums; + }; + mutable EvoViewCache m_qc_hashes GUARDED_BY(m_qc_hashes_cache_mutex); + mutable std::deque>> m_recent_mined GUARDED_BY(m_qc_hashes_cache_mutex); using ValidMemberSigners = std::vector>; mutable Mutex m_signing_records_mutex; @@ -105,21 +125,6 @@ class CQuorumBlockProcessor mutable Mutex m_commitment_payload_mutex; mutable Uint256LruHashMap, 64> m_commitment_payload_cache GUARDED_BY(m_commitment_payload_mutex); - // The active quorum set of a block is its parent's set plus the commitments the block - // mined, so the lookup for consecutive blocks derives it from the previous answer instead - // of walking the mined-commitment tables (one iterator seek per quorum index for rotation). - // The set depends on the EvoDB view it is read through, which the key does not capture, so - // only GetQcHashes uses it; history lookups (MN list diffs, quorum proofs) always walk. - struct MinedCommitmentRef { - Consensus::LLMQType type; - int quorumIndex; - const CBlockIndex* base; - }; - using ActiveQuorums = std::map>>; - mutable uint256 m_active_quorums_block GUARDED_BY(m_qc_hashes_cache_mutex); - mutable ActiveQuorums m_active_quorums GUARDED_BY(m_qc_hashes_cache_mutex); - mutable std::deque>> m_recent_mined GUARDED_BY(m_qc_hashes_cache_mutex); - public: CQuorumBlockProcessor() = delete; CQuorumBlockProcessor(const CQuorumBlockProcessor&) = delete; @@ -212,10 +217,12 @@ class CQuorumBlockProcessor ActiveQuorums WalkActiveQuorums(gsl::not_null pindex) const; //! GetMinedAndActiveCommitmentsUntilBlock through the rolling cache, for GetQcHashes only. std::map> GetActiveCommitmentsCached( - gsl::not_null pindex) const EXCLUSIVE_LOCKS_REQUIRED(!m_qc_hashes_cache_mutex); + const EvoViewToken& view, gsl::not_null pindex) const + EXCLUSIVE_LOCKS_REQUIRED(!m_qc_hashes_cache_mutex); //! The active set of pindex derived from its parent's cached set, if both the parent's set //! and pindex's mined commitments are known. - std::optional DeriveActiveQuorums(gsl::not_null pindex) const + std::optional DeriveActiveQuorums(const QcHashesCache& cache, + gsl::not_null pindex) const EXCLUSIVE_LOCKS_REQUIRED(m_qc_hashes_cache_mutex); bool GetCommitmentsFromBlock(const CBlock& block, gsl::not_null pindex, std::multimap& ret, BlockValidationState& state) const diff --git a/src/llmq/quorumsman.cpp b/src/llmq/quorumsman.cpp index 14e2a8d2a0f6..e7b373bb4e83 100644 --- a/src/llmq/quorumsman.cpp +++ b/src/llmq/quorumsman.cpp @@ -38,10 +38,17 @@ CQuorumManager::CQuorumManager(CBLSWorker& _blsWorker, CDeterministicMNManager& quorumBlockProcessor{_quorumBlockProcessor}, m_qsnapman{qsnapman}, m_chainman{chainman}, - db{util::MakeDbWrapper({db_params.path / "llmq" / "quorumdb", db_params.memory, db_params.wipe, /*cache_size=*/1 << 20, db_params.options})} + m_evoDb{_evoDb}, + db{util::MakeDbWrapper({db_params.path / "llmq" / "quorumdb", db_params.memory, db_params.wipe, + /*cache_size=*/1 << 20, db_params.options})}, + m_view_caches{[&consensus = chainman.GetConsensus()] { + ViewCaches caches; + caches.mapQuorumsCache.Init(consensus, /*limit_by_connections=*/false); + return caches; + }} { AssertLockHeld(::cs_main); - mapQuorumsCache.Init(m_chainman.GetConsensus(), /*limit_by_connections=*/false); + m_view_caches.SetOwner(_evoDb); MigrateOldQuorumDB(_evoDb); m_cache_interrupt.reset(); m_cache_thread = std::thread(&util::TraceThread, "q-cache", [this] { CacheWarmingThreadMain(); }); @@ -68,6 +75,7 @@ bool CQuorumManager::GetEncryptedContributions(Consensus::LLMQType llmq_type, co CQuorumPtr CQuorumManager::BuildQuorumFromCommitment(const Consensus::LLMQType llmqType, gsl::not_null pQuorumBaseBlockIndex, bool populate_cache) const { const uint256& quorumHash{pQuorumBaseBlockIndex->GetBlockHash()}; + const EvoViewToken view{m_evoDb.CurrentView()}; auto [qc, minedBlockHash] = quorumBlockProcessor.GetMinedCommitment(llmqType, quorumHash); if (minedBlockHash == uint256::ZERO) { @@ -84,7 +92,7 @@ CQuorumPtr CQuorumManager::BuildQuorumFromCommitment(const Consensus::LLMQType l std::make_unique(std::move(qc)), pQuorumBaseBlockIndex, minedBlockHash, members); if (populate_cache && llmq_params_opt->size == 1) { - WITH_LOCK(m_cs_maps, mapQuorumsCache.insert(llmqType, quorumHash, quorum)); + WITH_LOCK(m_cs_maps, m_view_caches.For(view).mapQuorumsCache.insert(llmqType, quorumHash, quorum)); return quorum; } @@ -108,7 +116,7 @@ CQuorumPtr CQuorumManager::BuildQuorumFromCommitment(const Consensus::LLMQType l QueueQuorumForWarming(quorum); } - WITH_LOCK(m_cs_maps, mapQuorumsCache.insert(llmqType, quorumHash, quorum)); + WITH_LOCK(m_cs_maps, m_view_caches.For(view).mapQuorumsCache.insert(llmqType, quorumHash, quorum)); return quorum; } @@ -177,14 +185,23 @@ std::vector CQuorumManager::ScanQuorums(Consensus::LLMQType llmqTyp return ScanQuorums(llmqType, pindexStart, nCountRequested, &chain); } +bool CQuorumManager::IsOnViewChain(const EvoViewToken& view, gsl::not_null pindex) const +{ + AssertLockHeld(::cs_main); + const CChain* chain{m_chainman.EvoChain(view.identity)}; + return chain && chain->Contains(pindex); +} + template -PerLlmqTypeCache>& CQuorumManager::ScanCache() const +PerLlmqTypeCache>& CQuorumManager::ScanCache(const EvoViewToken& view) const { + // cppcheck-suppress constVariableReference + auto& caches{m_view_caches.For(view)}; if constexpr (std::is_same_v) { - return scanQuorumsCache; + return caches.scanQuorumsCache; } else { static_assert(std::is_same_v); - return scanCommitmentsCache; + return caches.scanCommitmentsCache; } } @@ -223,9 +240,10 @@ std::vector CQuorumManager::ScanMined(Consensus::LLMQType llmqType, gsl::not_ std::vector vecResult; bool resume{false}; + const EvoViewToken view{m_evoDb.CurrentView()}; if (use_cache) { LOCK(m_cs_maps); - auto& cache = ScanCache(); + auto& cache = ScanCache(view); if (!cache.IsInitialized()) { // NOTE: We store it for each block hash in the DKG mining phase here // and not for a single quorum hash per quorum like we do for other caches. @@ -270,15 +288,15 @@ std::vector CQuorumManager::ScanMined(Consensus::LLMQType llmqType, gsl::not_ } // Get the block indexes of the mined commitments to build the required results from. - // The mined commitment index follows the active chain, so a scan from a block that is - // not on it (e.g. a tip notification processed after a reorg) reads another branch. + // The view's mined commitment index follows its chainstate's chain, so a scan from a + // block that is not on it (e.g. a tip notification processed after a reorg, or a + // background view scanning above its chainstate's tip) reads another branch. // Check that under the same cs_main hold so a reorg cannot slip in between. - bool scan_on_active_chain{false}; + bool scan_on_view_chain{false}; std::vector pQuorumBaseBlockIndexes; { LOCK(::cs_main); - const CChain& active_chain{m_chainman.ActiveChain()}; - scan_on_active_chain = active_chain.Contains(pindexStore) && active_chain.Contains(pIndexScanCommitments); + scan_on_view_chain = IsOnViewChain(view, pindexStore) && IsOnViewChain(view, pIndexScanCommitments); pQuorumBaseBlockIndexes = llmq_params_opt->useRotation ? quorumBlockProcessor.GetMinedCommitmentsIndexedUntilBlock(llmqType, pIndexScanCommitments, @@ -304,17 +322,17 @@ std::vector CQuorumManager::ScanMined(Consensus::LLMQType llmqType, gsl::not_ } const size_t nCountResult{vecResult.size()}; - if (nCountResult > 0 && use_cache && scan_on_active_chain) { + if (nCountResult > 0 && use_cache && scan_on_view_chain) { LOCK2(::cs_main, m_cs_maps); - // build() read commitments by quorum hash without cs_main; if pindexStore was disconnected - // meanwhile they may be another branch's commitments for the same quorums. - if (m_chainman.ActiveChain().Contains(pindexStore)) { + // build() read commitments by quorum hash without cs_main; if pindexStore left the + // view's chain meanwhile they may be another branch's commitments for the same quorums. + if (IsOnViewChain(view, pindexStore)) { // Don't cache more than keepOldConnections elements // because signing by old quorums requires the exact quorum hash // to be specified and quorum scanning isn't needed there. const size_t nCacheEndIndex = std::min(nCountResult, static_cast(llmq_params_opt->keepOldConnections)); - ScanCache().emplace(llmqType, pindexStore->GetBlockHash(), - {vecResult.begin(), vecResult.begin() + nCacheEndIndex}); + ScanCache(view).emplace(llmqType, pindexStore->GetBlockHash(), + {vecResult.begin(), vecResult.begin() + nCacheEndIndex}); } } // Don't return more than nCountRequested elements @@ -501,8 +519,9 @@ CQuorumCPtr CQuorumManager::GetQuorum(Consensus::LLMQType llmqType, gsl::not_nul CQuorumPtr pQuorum; { + const EvoViewToken view{m_evoDb.CurrentView()}; LOCK(m_cs_maps); - if (mapQuorumsCache.get(llmqType, quorumHash, pQuorum)) { + if (m_view_caches.For(view).mapQuorumsCache.get(llmqType, quorumHash, pQuorum)) { return pQuorum; } } @@ -522,7 +541,8 @@ CQuorumCPtr CQuorumManager::GetQuorum(Consensus::LLMQType llmqType, } CQuorumPtr pQuorum; - if (LOCK(m_cs_maps); mapQuorumsCache.get(llmqType, quorumHash, pQuorum)) { + const EvoViewToken view{m_evoDb.CurrentView()}; + if (LOCK(m_cs_maps); m_view_caches.For(view).mapQuorumsCache.get(llmqType, quorumHash, pQuorum)) { return pQuorum; } @@ -583,8 +603,9 @@ CQuorumManager::DataResponseValidation CQuorumManager::ValidateDataResponse( CQuorumPtr CQuorumManager::GetCachedMutableQuorum(Consensus::LLMQType llmqType, const uint256& quorumHash) const { CQuorumPtr pQuorum; + const EvoViewToken view{m_evoDb.CurrentView()}; LOCK(m_cs_maps); - mapQuorumsCache.get(llmqType, quorumHash, pQuorum); + m_view_caches.For(view).mapQuorumsCache.get(llmqType, quorumHash, pQuorum); return pQuorum; } diff --git a/src/llmq/quorumsman.h b/src/llmq/quorumsman.h index 47248d6189cd..173143979af6 100644 --- a/src/llmq/quorumsman.h +++ b/src/llmq/quorumsman.h @@ -7,6 +7,7 @@ #include #include +#include #include // IWYU pragma: export #include #include @@ -71,6 +72,7 @@ class CQuorumManager final CQuorumBlockProcessor& quorumBlockProcessor; CQuorumSnapshotManager& m_qsnapman; const ChainstateManager& m_chainman; + CEvoDB& m_evoDb; llmq::CDKGSessionManager* m_qdkgsman{nullptr}; llmq::QuorumRole* m_handler{nullptr}; @@ -85,9 +87,12 @@ class CQuorumManager final mutable size_t m_inbound_request_count GUARDED_BY(cs_data_requests){0}; mutable Mutex m_cs_maps; - mutable PerLlmqTypeCache> scanCommitmentsCache GUARDED_BY(m_cs_maps); - mutable PerLlmqTypeCache mapQuorumsCache GUARDED_BY(m_cs_maps); - mutable PerLlmqTypeCache> scanQuorumsCache GUARDED_BY(m_cs_maps); + struct ViewCaches { + PerLlmqTypeCache> scanCommitmentsCache; + PerLlmqTypeCache mapQuorumsCache; + PerLlmqTypeCache> scanQuorumsCache; + }; + mutable EvoViewCache m_view_caches GUARDED_BY(m_cs_maps); // On mainnet, we have around 62 quorums active at any point; let's cache a little more than double that to be safe. // it maps `quorum_hash` to `pindex` @@ -133,6 +138,9 @@ class CQuorumManager final const uint256& quorumHash, const CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + //! The Evo view the calling operation reads. + EvoViewToken CurrentView() const { return m_evoDb.CurrentView(); } + // all these methods will lock cs_main for a short period of time CQuorumCPtr GetQuorum(Consensus::LLMQType llmqType, const uint256& quorumHash) const EXCLUSIVE_LOCKS_REQUIRED(!cs_db, !m_cs_maps, !m_cache_cs); @@ -191,13 +199,17 @@ class CQuorumManager final //! Walks the mined commitments back from the DKG mining phase closest to pindexStart and builds an //! element for each. resume_block maps the last cached element to the block to continue below. //! Unless the full result is cached it locks cs_main, so that only results computed against the - //! active chain are cached. + //! chain the calling view's mined-commitment index describes are cached. template std::vector ScanMined(Consensus::LLMQType llmqType, gsl::not_null pindexStart, size_t nCountRequested, bool use_cache, ResumeFn&& resume_block, BuildFn&& build) const EXCLUSIVE_LOCKS_REQUIRED(!m_cs_maps); + //! The scan cache of `view`'s partition; a reference is valid only until the next m_view_caches lookup. template - PerLlmqTypeCache>& ScanCache() const EXCLUSIVE_LOCKS_REQUIRED(m_cs_maps); + PerLlmqTypeCache>& ScanCache(const EvoViewToken& view) const EXCLUSIVE_LOCKS_REQUIRED(m_cs_maps); + //! Whether pindex is on the chain that `view`'s mined-commitment index describes. + bool IsOnViewChain(const EvoViewToken& view, gsl::not_null pindex) const + EXCLUSIVE_LOCKS_REQUIRED(::cs_main); bool BuildQuorumContributions(const CFinalCommitmentPtr& fqc, const std::shared_ptr& quorum) const; CQuorumPtr BuildQuorumFromCommitment(Consensus::LLMQType llmqType, diff --git a/src/llmq/snapshot.cpp b/src/llmq/snapshot.cpp index d01c9a8d94c0..756fd672b1f1 100644 --- a/src/llmq/snapshot.cpp +++ b/src/llmq/snapshot.cpp @@ -83,7 +83,7 @@ namespace llmq { bool CQuorumSnapshotManager::IsCarriedOnly(const CBlockIndex* pindex) const { const EvoViewToken view{m_evoDb.CurrentView()}; - return view.identity == EvoDbIdentity::SNAPSHOT && pindex->nHeight <= view.base_height; + return view.AtOrBelowSnapshotBase(pindex->nHeight); } bool BuildQuorumRotationInfo(CDeterministicMNManager& dmnman, CQuorumSnapshotManager& qsnapman, @@ -304,8 +304,9 @@ std::vector CQuorumRotationInfo::GetCycles() CQuorumSnapshotManager::CQuorumSnapshotManager(CEvoDB& evoDb) : m_evoDb{evoDb}, - quorumSnapshotCache{32} + quorumSnapshotCache{[] { return Uint256LruHashMap{32}; }} { + quorumSnapshotCache.SetOwner(evoDb); } CQuorumSnapshotManager::~CQuorumSnapshotManager() = default; @@ -315,28 +316,31 @@ std::optional CQuorumSnapshotManager::GetSnapshotForBlock(const CQuorumSnapshot snapshot = {}; auto snapshotHash = ::SerializeHash(std::make_pair(llmqType, pindex->GetBlockHash())); + const EvoViewToken view{m_evoDb.CurrentView()}; LOCK(snapshotCacheCs); // try using cache before reading from disk - if (quorumSnapshotCache.get(snapshotHash, snapshot)) { + if (quorumSnapshotCache.For(view).get(snapshotHash, snapshot)) { return snapshot; } if (m_evoDb.Read(std::make_pair(DB_QUORUM_SNAPSHOT, snapshotHash), snapshot)) { - quorumSnapshotCache.insert(snapshotHash, snapshot); + quorumSnapshotCache.For(view).insert(snapshotHash, snapshot); return snapshot; } return std::nullopt; } -void CQuorumSnapshotManager::StoreSnapshotForBlock(const Consensus::LLMQType llmqType, const CBlockIndex* pindex, const CQuorumSnapshot& snapshot) +void CQuorumSnapshotManager::StoreSnapshotForBlock(const EvoViewToken& view, const Consensus::LLMQType llmqType, + const CBlockIndex* pindex, const CQuorumSnapshot& snapshot) { auto snapshotHash = ::SerializeHash(std::make_pair(llmqType, pindex->GetBlockHash())); const auto key{std::make_pair(DB_QUORUM_SNAPSHOT, snapshotHash)}; AssertLockNotHeld(m_evoDb.cs); - const EvoViewToken view{m_evoDb.CurrentView()}; - if (view.identity == EvoDbIdentity::SNAPSHOT && pindex->nHeight <= view.base_height) { + // The checks below read in the current view, which is no longer `view`. + if (m_evoDb.IsOvertaken(view)) return; + if (view.AtOrBelowSnapshotBase(pindex->nHeight)) { // At or below the snapshot base the snapshot view holds only carried // state. A carried quarter must match the one just computed from // complete inputs. An uncarried one is a reconstruction output, never a @@ -351,7 +355,7 @@ void CQuorumSnapshotManager::StoreSnapshotForBlock(const Consensus::LLMQType llm } LOCK(snapshotCacheCs); - m_evoDb.WriteImmediate(key, snapshot); - quorumSnapshotCache.insert(snapshotHash, snapshot); + if (!m_evoDb.WriteImmediate(view, key, snapshot)) return; + quorumSnapshotCache.For(view).insert(snapshotHash, snapshot); } } // namespace llmq diff --git a/src/llmq/snapshot.h b/src/llmq/snapshot.h index 12bafc2bf9a8..d4df740c491b 100644 --- a/src/llmq/snapshot.h +++ b/src/llmq/snapshot.h @@ -6,6 +6,7 @@ #define BITCOIN_LLMQ_SNAPSHOT_H #include +#include #include #include #include @@ -237,7 +238,8 @@ class CQuorumSnapshotManager CEvoDB& m_evoDb; - Uint256LruHashMap quorumSnapshotCache GUARDED_BY(snapshotCacheCs); + EvoViewCache> quorumSnapshotCache GUARDED_BY(snapshotCacheCs){ + [] { return Uint256LruHashMap{32}; }}; public: CQuorumSnapshotManager() = delete; @@ -246,8 +248,16 @@ class CQuorumSnapshotManager explicit CQuorumSnapshotManager(CEvoDB& evoDb); ~CQuorumSnapshotManager(); + //! The Evo view the calling operation reads, for callers that partition + //! their own caches of state derived from quorum snapshots. + EvoViewToken CurrentView() const { return m_evoDb.CurrentView(); } + std::optional GetSnapshotForBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex); - void StoreSnapshotForBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex, const CQuorumSnapshot& snapshot); + //! Store a snapshot computed under `view`, which the computation resolved + //! before its first read: once `view` is overtaken or retired the store is + //! dropped. + void StoreSnapshotForBlock(const EvoViewToken& view, Consensus::LLMQType llmqType, const CBlockIndex* pindex, + const CQuorumSnapshot& snapshot); //! Whether the calling operation reads the snapshot view and `pindex` is //! at or below its base, where only carried quarters exist. bool IsCarriedOnly(const CBlockIndex* pindex) const; diff --git a/src/llmq/utils.cpp b/src/llmq/utils.cpp index ba7a69a36e82..5e684e3afa19 100644 --- a/src/llmq/utils.cpp +++ b/src/llmq/utils.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -29,7 +30,9 @@ /** * Forward declarations */ -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex); +std::optional> GetNonNullCoinbaseChainlock(const EvoViewToken& view, + const node::BlockManager& blockman, + const CBlockIndex* pindex); namespace { using QuorumMembers = std::vector; @@ -86,9 +89,10 @@ arith_uint256 calculateQuorumScore(const CDeterministicMNCPtr& dmn, const uint25 return UintToArith256(h); } -uint256 GetHashModifierFromWorkBlock(const Consensus::LLMQParams& llmqParams, const node::BlockManager& blockman, const CBlockIndex* pWorkBlockIndex) +uint256 GetHashModifierFromWorkBlock(const Consensus::LLMQParams& llmqParams, const node::BlockManager& blockman, + const EvoViewToken& view, const CBlockIndex* pWorkBlockIndex) { - auto cbcl = GetNonNullCoinbaseChainlock(blockman, pWorkBlockIndex); + auto cbcl = GetNonNullCoinbaseChainlock(view, blockman, pWorkBlockIndex); if (cbcl.has_value()) { // We have a non-null CL signature: calculate modifier using this CL signature auto& [bestCLSignature, bestCLHeightDiff] = cbcl.value(); @@ -99,14 +103,15 @@ uint256 GetHashModifierFromWorkBlock(const Consensus::LLMQParams& llmqParams, co } uint256 GetHashModifier(const Consensus::LLMQParams& llmqParams, const Consensus::Params& consensus_params, - const node::BlockManager& blockman, gsl::not_null pCycleQuorumBaseBlockIndex) + const node::BlockManager& blockman, const EvoViewToken& view, + gsl::not_null pCycleQuorumBaseBlockIndex) { ASSERT_IF_DEBUG(pCycleQuorumBaseBlockIndex->nHeight % llmqParams.dkgInterval == 0); const CBlockIndex* pWorkBlockIndex = pCycleQuorumBaseBlockIndex->GetAncestor(pCycleQuorumBaseBlockIndex->nHeight - llmq::WORK_DIFF_DEPTH); if (DeploymentActiveAfter(pWorkBlockIndex, consensus_params, Consensus::DEPLOYMENT_V20)) { // v20 is active: calculate modifier using the new way. - return GetHashModifierFromWorkBlock(llmqParams, blockman, pWorkBlockIndex); + return GetHashModifierFromWorkBlock(llmqParams, blockman, view, pWorkBlockIndex); } // v20 isn't active yet: calculate modifier using the usual way @@ -191,6 +196,7 @@ std::vector GetQuorumQuarterMembersBySnapshot(const Consensus::LL CDeterministicMNManager& dmnman, const Consensus::Params& consensus_params, const node::BlockManager& blockman, + const EvoViewToken& view, const CBlockIndex* pCycleQuorumBaseBlockIndex, const llmq::CQuorumSnapshot& snapshot, int nHeight) { @@ -204,7 +210,7 @@ std::vector GetQuorumQuarterMembersBySnapshot(const Consensus::LL const CBlockIndex* pWorkBlockIndex = pCycleQuorumBaseBlockIndex->GetAncestor( pCycleQuorumBaseBlockIndex->nHeight - llmq::WORK_DIFF_DEPTH); auto mn_list = dmnman.GetListForBlock(pWorkBlockIndex); - const auto modifier = GetHashModifier(llmqParams, consensus_params, blockman, pCycleQuorumBaseBlockIndex); + const auto modifier = GetHashModifier(llmqParams, consensus_params, blockman, view, pCycleQuorumBaseBlockIndex); auto sortedAllMns = CalculateQuorum(mn_list, modifier); std::vector usedMNs; @@ -292,7 +298,8 @@ std::vector GetQuorumQuarterMembersBySnapshot(const Consensus::LL } QuorumMembers ComputeQuorumMembers(Consensus::LLMQType llmqType, const CChainParams& chainparams, const node::BlockManager& blockman, - const CDeterministicMNList& mn_list, const CBlockIndex* pQuorumBaseBlockIndex) + const EvoViewToken& view, const CDeterministicMNList& mn_list, + const CBlockIndex* pQuorumBaseBlockIndex) { bool EvoOnly = (chainparams.GetConsensus().llmqTypePlatform == llmqType) && DeploymentActiveAfter(pQuorumBaseBlockIndex, chainparams.GetConsensus(), Consensus::DEPLOYMENT_V19); @@ -303,12 +310,13 @@ QuorumMembers ComputeQuorumMembers(Consensus::LLMQType llmqType, const CChainPar return {}; } - const auto modifier = GetHashModifier(llmq_params_opt.value(), chainparams.GetConsensus(), blockman, pQuorumBaseBlockIndex); + const auto modifier = GetHashModifier(llmq_params_opt.value(), chainparams.GetConsensus(), blockman, view, + pQuorumBaseBlockIndex); return CalculateQuorum(mn_list, modifier, llmq_params_opt->size, EvoOnly); } void BuildQuorumSnapshot(const Consensus::LLMQParams& llmqParams, const Consensus::Params& consensus_params, const node::BlockManager& blockman, - const CDeterministicMNList& allMns, const CDeterministicMNList& mnUsedAtH, + const EvoViewToken& view, const CDeterministicMNList& allMns, const CDeterministicMNList& mnUsedAtH, llmq::CQuorumSnapshot& quorumSnapshot, std::vector& skipList, const CBlockIndex* pCycleQuorumBaseBlockIndex) { @@ -319,7 +327,7 @@ void BuildQuorumSnapshot(const Consensus::LLMQParams& llmqParams, const Consensu const auto allMnsTotal = allMns.GetCounts().total(); quorumSnapshot.activeQuorumMembers.resize(allMnsTotal); - const auto modifier = GetHashModifier(llmqParams, consensus_params, blockman, pCycleQuorumBaseBlockIndex); + const auto modifier = GetHashModifier(llmqParams, consensus_params, blockman, view, pCycleQuorumBaseBlockIndex); auto sortedAllMns = CalculateQuorum(allMns, modifier); LogPrint(BCLog::LLMQ, "BuildQuorumSnapshot h[%d] numMns[%d]\n", pCycleQuorumBaseBlockIndex->nHeight, @@ -345,6 +353,7 @@ void BuildQuorumSnapshot(const Consensus::LLMQParams& llmqParams, const Consensu std::vector BuildNewQuorumQuarterMembers(const Consensus::LLMQParams& llmqParams, const llmq::UtilParameters& util_params, + const EvoViewToken& view, const CDeterministicMNList& allMns, const PreviousQuorumQuarters& previousQuarters, const uint256& modifier, @@ -460,9 +469,10 @@ std::vector BuildNewQuorumQuarterMembers(const Consensus::LLMQPar if (storeSnapshot) { llmq::CQuorumSnapshot quorumSnapshot{}; - BuildQuorumSnapshot(llmqParams, util_params.m_chainman.GetConsensus(), util_params.m_chainman.m_blockman, allMns, + BuildQuorumSnapshot(llmqParams, util_params.m_chainman.GetConsensus(), util_params.m_chainman.m_blockman, + util_params.m_qsnapman.CurrentView(), allMns, MnsUsedAtH, quorumSnapshot, skipList, util_params.m_base_index); - util_params.m_qsnapman.StoreSnapshotForBlock(llmqParams.type, util_params.m_base_index, quorumSnapshot); + util_params.m_qsnapman.StoreSnapshotForBlock(view, llmqParams.type, util_params.m_base_index, quorumSnapshot); } return quarterQuorumMembers; @@ -470,9 +480,11 @@ std::vector BuildNewQuorumQuarterMembers(const Consensus::LLMQPar // Computes the members of all quorum indexes of the cycle starting at cycleBaseHeight, which // is not required to be mined yet: everything is derived from the cycle's work block. Pass -// storeSnapshot=false when predicting a future cycle. +// storeSnapshot=false when predicting a future cycle. The cycle's snapshot is stored as `view`'s, the +// view the caller resolved before its first read. std::vector ComputeQuorumMembersByQuarterRotation(const Consensus::LLMQParams& llmqParams, const llmq::UtilParameters& util_params, + const EvoViewToken& view, gsl::not_null pWorkBlockIndex, int cycleBaseHeight, const uint256& modifier, bool predicting) @@ -517,12 +529,13 @@ std::vector ComputeQuorumMembersByQuarterRotation(const Consensus prev_cycles[idx]->m_members = GetQuorumQuarterMembersBySnapshot(llmqParams, util_params.m_dmnman, util_params.m_chainman.GetConsensus(), util_params.m_chainman.m_blockman, + util_params.m_qsnapman.CurrentView(), prev_cycles[idx]->m_cycle_index, prev_cycles[idx]->m_snap, cycleBaseHeight); } - auto newQuarterMembers = BuildNewQuorumQuarterMembers(llmqParams, util_params, allMns, previousQuarters, modifier, + auto newQuarterMembers = BuildNewQuorumQuarterMembers(llmqParams, util_params, view, allMns, previousQuarters, modifier, cycleBaseHeight, /*storeSnapshot=*/!predicting); // TODO: Check if it is triggered from outside (P2P, block validation) and maybe throw an exception // assert (!newQuarterMembers.empty()); @@ -691,7 +704,8 @@ std::optional> ComputeQuorumMembersFromWorkBlo return std::nullopt; } - const auto modifier = GetHashModifierFromWorkBlock(llmq_params, util_params.m_chainman.m_blockman, pWorkBlockIndex.get()); + const auto modifier = GetHashModifierFromWorkBlock(llmq_params, util_params.m_chainman.m_blockman, + util_params.m_qsnapman.CurrentView(), pWorkBlockIndex.get()); if (!llmq_params.useRotation) { // Canonical member selection gates EvoOnly on V19 at the future quorum base block; V19 @@ -703,7 +717,8 @@ std::optional> ComputeQuorumMembersFromWorkBlo EvoOnly); } - auto quorumMembers = ComputeQuorumMembersByQuarterRotation(llmq_params, util_params, pWorkBlockIndex, + auto quorumMembers = ComputeQuorumMembersByQuarterRotation(llmq_params, util_params, + util_params.m_qsnapman.CurrentView(), pWorkBlockIndex, cycleBaseHeight, modifier, /*predicting=*/true); if (quorumMembers.empty()) { return std::nullopt; @@ -714,9 +729,11 @@ std::optional> ComputeQuorumMembersFromWorkBlo QuorumMembers GetAllQuorumMembers(Consensus::LLMQType llmqType, const UtilParameters& util_params, bool reset_cache) { static RecursiveMutex cs_members; - static PerLlmqTypeCache mapQuorumMembers GUARDED_BY(cs_members); + static EvoViewCache> members_by_view GUARDED_BY(cs_members); static RecursiveMutex cs_indexed_members; - static PerLlmqTypeCache> mapIndexedQuorumMembers GUARDED_BY(cs_indexed_members); + static EvoViewCache>> indexed_members_by_view GUARDED_BY( + cs_indexed_members); + const EvoViewToken view{util_params.m_qsnapman.CurrentView()}; // A parentless base index (genesis) can never host a quorum. IsQuorumTypeEnabled() handles the // null, but say so explicitly here: this is reached with an attacker-supplied quorumHash via @@ -729,6 +746,7 @@ QuorumMembers GetAllQuorumMembers(Consensus::LLMQType llmqType, const UtilParame std::vector quorumMembers; { LOCK(cs_members); + auto& mapQuorumMembers{members_by_view.For(view)}; if (!mapQuorumMembers.IsInitialized()) { mapQuorumMembers.Init(util_params.m_chainman.GetConsensus()); } @@ -744,8 +762,8 @@ QuorumMembers GetAllQuorumMembers(Consensus::LLMQType llmqType, const UtilParame const auto& llmq_params = llmq_params_opt.value(); if (IsQuorumRotationEnabled(llmq_params, util_params.m_base_index)) { - if (LOCK(cs_indexed_members); !mapIndexedQuorumMembers.IsInitialized()) { - mapIndexedQuorumMembers.Init(util_params.m_chainman.GetConsensus()); + if (LOCK(cs_indexed_members); !indexed_members_by_view.For(view).IsInitialized()) { + indexed_members_by_view.For(view).Init(util_params.m_chainman.GetConsensus()); } /* * Quorums created with rotation are now created in a different way. All signingActiveQuorumCount are created @@ -770,24 +788,25 @@ QuorumMembers GetAllQuorumMembers(Consensus::LLMQType llmqType, const UtilParame */ if (reset_cache) { LOCK(cs_indexed_members); - mapIndexedQuorumMembers.clear(llmqType); - } else if (LOCK(cs_indexed_members); mapIndexedQuorumMembers.get( + indexed_members_by_view.For(view).clear(llmqType); + } else if (LOCK(cs_indexed_members); indexed_members_by_view.For(view).get( llmqType, std::pair(pCycleQuorumBaseBlockIndex->GetBlockHash(), quorumIndex), quorumMembers)) { LOCK(cs_members); - mapQuorumMembers.insert(llmqType, util_params.m_base_index->GetBlockHash(), quorumMembers); + members_by_view.For(view).insert(llmqType, util_params.m_base_index->GetBlockHash(), quorumMembers); return quorumMembers; } const CBlockIndex* pWorkBlockIndex = pCycleQuorumBaseBlockIndex->GetAncestor(cycleQuorumBaseHeight - WORK_DIFF_DEPTH); const auto modifier = GetHashModifier(llmq_params, util_params.m_chainman.GetConsensus(), - util_params.m_chainman.m_blockman, pCycleQuorumBaseBlockIndex); + util_params.m_chainman.m_blockman, view, pCycleQuorumBaseBlockIndex); auto q = ComputeQuorumMembersByQuarterRotation(llmq_params, util_params.replace_index(pCycleQuorumBaseBlockIndex), - pWorkBlockIndex, cycleQuorumBaseHeight, modifier, + view, pWorkBlockIndex, cycleQuorumBaseHeight, modifier, /*predicting=*/false); quorumMembers = q[quorumIndex]; LOCK(cs_indexed_members); + auto& mapIndexedQuorumMembers{indexed_members_by_view.For(view)}; for (const size_t i : util::irange(q.size())) { mapIndexedQuorumMembers.emplace(llmqType, std::make_pair(pCycleQuorumBaseBlockIndex->GetBlockHash(), i), std::move(q[i])); @@ -801,11 +820,11 @@ QuorumMembers GetAllQuorumMembers(Consensus::LLMQType llmqType, const UtilParame : util_params.m_base_index.get(); CDeterministicMNList mn_list = util_params.m_dmnman.GetListForBlock(pWorkBlockIndex); quorumMembers = ComputeQuorumMembers(llmqType, util_params.m_chainman.GetParams(), util_params.m_chainman.m_blockman, - mn_list, util_params.m_base_index); + view, mn_list, util_params.m_base_index); } LOCK(cs_members); - mapQuorumMembers.insert(llmqType, util_params.m_base_index->GetBlockHash(), quorumMembers); + members_by_view.For(view).insert(llmqType, util_params.m_base_index->GetBlockHash(), quorumMembers); return quorumMembers; } diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 2f9ae78e150d..1e253985afe0 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -53,6 +53,7 @@ #include #include #include +#include #include #include #include @@ -5739,9 +5740,16 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, llmq::CQuorumRotationInfo quorumRotationInfoRet; std::string strError; bool use_legacy_construction = pfrom.GetCommonVersion() < EFFICIENT_QRINFO_VERSION;; - const bool built{BuildQuorumRotationInfo(m_dmnman, *m_llmq_ctx.qsnapman, m_chainman, *m_llmq_ctx.qman, - *m_llmq_ctx.quorum_block_processor, cmd, use_legacy_construction, - quorumRotationInfoRet, strError)}; + bool built{false}; + try { + built = BuildQuorumRotationInfo(m_dmnman, *m_llmq_ctx.qsnapman, m_chainman, *m_llmq_ctx.qman, + *m_llmq_ctx.quorum_block_processor, cmd, use_legacy_construction, + quorumRotationInfoRet, strError); + } catch (const evo::LocalStateError& e) { + // This node's Evo state cannot answer: not the peer's fault, but + // charged below like any build that stopped partway. + strError = strprintf("%s %s", e.what(), BLOCK_DATA_UNAVAILABLE_SUFFIX); + } if (!pfrom.HasPermission(NetPermissionFlags::NoBan)) { // The token taken above paid for one diff. Charge the rest of the reply (the tip, H, the // target cycles and the snapshot diffs) now that its size is known. A build that failed diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 27c045c9c729..dbcdba66480b 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -104,7 +104,8 @@ void BlockAssembler::resetBlock() } // Helper to calculate best chainlock -static bool CalcCbTxBestChainlock(const chainlock::Chainlocks& chainlocks, const node::BlockManager& blockman, const CBlockIndex* pindexPrev, +static bool CalcCbTxBestChainlock(const chainlock::Chainlocks& chainlocks, const EvoViewToken& view, + const node::BlockManager& blockman, const CBlockIndex* pindexPrev, uint32_t& bestCLHeightDiff, CBLSSignature& bestCLSignature) { auto [best_clsig, pindexCL] = chainlocks.GetBestChainlockWithPindex(); @@ -119,7 +120,7 @@ static bool CalcCbTxBestChainlock(const chainlock::Chainlocks& chainlocks, const return true; } - auto prevBlockCoinbaseChainlock = GetNonNullCoinbaseChainlock(blockman, pindexPrev); + auto prevBlockCoinbaseChainlock = GetNonNullCoinbaseChainlock(view, blockman, pindexPrev); if (prevBlockCoinbaseChainlock.has_value()) { // Previous block Coinbase contains a non-null CL: We must insert the same sig or a better (newest) one if (best_clsig.IsNull()) { @@ -350,7 +351,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc } if (fV20Active_context) { CBLSSignature best_cl_sig; - const bool has_best_cl{CalcCbTxBestChainlock(m_chainlocks, m_chainstate.m_blockman, pindexPrev, cbTx.bestCLHeightDiff, best_cl_sig)}; + const bool has_best_cl{CalcCbTxBestChainlock(m_chainlocks, m_evoDb.CurrentView(), m_chainstate.m_blockman, pindexPrev, cbTx.bestCLHeightDiff, best_cl_sig)}; cbTx.bestCLSignature.Set(best_cl_sig); if (has_best_cl) { LogPrintf("CreateNewBlock() h[%d] CbTx bestCLHeightDiff[%d] CLSig[%s]\n", nHeight, cbTx.bestCLHeightDiff, cbTx.bestCLSignature.ToString()); diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index d7d5850845e1..8e38ca218ffe 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -852,7 +852,8 @@ static RPCHelpMan getassetunlockstatuses() return pTipBlockIndex->GetAncestor(best_clsig.getHeight()); } // If no CL info is available, try to use CbTx CL information - if (const auto cbtx_best_cl = GetNonNullCoinbaseChainlock(chainman.m_blockman, pTipBlockIndex)) { + if (const auto cbtx_best_cl = GetNonNullCoinbaseChainlock(CHECK_NONFATAL(node.evodb)->CurrentView(), + chainman.m_blockman, pTipBlockIndex)) { return pTipBlockIndex->GetAncestor(pTipBlockIndex->nHeight - cbtx_best_cl->second - 1); } // no CL info, no CbTx CL diff --git a/src/test/evo_db_tests.cpp b/src/test/evo_db_tests.cpp index 89df5dabfbca..a8964da4df4b 100644 --- a/src/test/evo_db_tests.cpp +++ b/src/test/evo_db_tests.cpp @@ -3,15 +3,25 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include +#include +#include +#include +#include #include +#include +#include #include #include #include #include +#include +#include #include #include +#include +#include #include #include #include @@ -189,6 +199,41 @@ BOOST_AUTO_TEST_CASE(transaction_less_access_uses_default_identity) } } +BOOST_AUTO_TEST_CASE(write_immediate_drops_a_write_decided_under_a_discarded_view) +{ + LOCK(::cs_main); + CEvoDB db{util::DbWrapperParams{.path = m_args.GetDataDirBase() / "evodb_write_immediate_view", .memory = true, .wipe = true}}; + PublishGeneration(db); + db.SetDefaultIdentity(EvoDbIdentity::SNAPSHOT); + const EvoViewToken snapshot_view{db.CurrentView()}; + BOOST_REQUIRE(snapshot_view.identity == EvoDbIdentity::SNAPSHOT); + + BOOST_CHECK(db.WriteImmediate(snapshot_view, PayloadKey(1), PayloadFor(1))); + Payload value; + BOOST_REQUIRE(db.Read(PayloadKey(1), value)); + BOOST_CHECK(value == PayloadFor(1)); + + BOOST_REQUIRE(db.AbandonSnapshotGeneration()); + BOOST_REQUIRE(db.CurrentView() == db.ViewFor(EvoDbIdentity::NORMAL)); + BOOST_CHECK(!db.WriteImmediate(snapshot_view, PayloadKey(2), PayloadFor(2))); + BOOST_CHECK(!db.Read(PayloadKey(2), value)); + BOOST_CHECK(!db.Read(PayloadKey(1), value)); + + const EvoViewToken normal_view{db.CurrentView()}; + BOOST_CHECK(db.WriteImmediate(normal_view, PayloadKey(3), PayloadFor(3))); + BOOST_REQUIRE(db.Read(PayloadKey(3), value)); + BOOST_CHECK(value == PayloadFor(3)); + + // A transaction-less view is overtaken by a switch of the default + // identity, even one that ends where it started. + PublishGeneration(db); + db.SetDefaultIdentity(EvoDbIdentity::SNAPSHOT); + db.SetDefaultIdentity(EvoDbIdentity::NORMAL); + BOOST_REQUIRE(db.CurrentView() == normal_view); + BOOST_CHECK(!db.WriteImmediate(normal_view, PayloadKey(4), PayloadFor(4))); + BOOST_CHECK(!db.Read(PayloadKey(4), value)); +} + BOOST_AUTO_TEST_CASE(write_derived_compares_within_its_own_view) { LOCK(::cs_main); @@ -382,6 +427,266 @@ BOOST_AUTO_TEST_CASE(open_transaction_does_not_capture_other_threads) BOOST_CHECK(other_thread == PayloadFor(30)); } +BOOST_AUTO_TEST_CASE(view_cache_serves_live_views_of_its_evodb) +{ + LOCK(::cs_main); + CEvoDB db{util::DbWrapperParams{.path = m_args.GetDataDirBase() / "evodb_view_cache", .memory = true, .wipe = true}}; + PublishGeneration(db); + const EvoViewToken normal{db.ViewFor(EvoDbIdentity::NORMAL)}; + const EvoViewToken snapshot{db.ViewFor(EvoDbIdentity::SNAPSHOT)}; + CEvoDB other{ + util::DbWrapperParams{.path = m_args.GetDataDirBase() / "evodb_view_cache_other", .memory = true, .wipe = true}}; + + // A cache of state derived from one CEvoDB serves only that CEvoDB's live + // views: neither another CEvoDB's view nor a retained token of a retired + // generation gets a partition. + EvoViewCache cache; + cache.SetOwner(db); + cache.For(normal) = 1; + cache.For(snapshot) = 2; + BOOST_CHECK_THROW(cache.For(other.ViewFor(EvoDbIdentity::NORMAL)), EvoViewBindingError); + BOOST_REQUIRE(db.AbandonSnapshotGeneration()); + BOOST_CHECK_THROW(cache.For(snapshot), EvoViewBindingError); + // With no generation bound the snapshot identity names no view at all. + BOOST_CHECK_THROW(cache.For(db.ViewFor(EvoDbIdentity::SNAPSHOT)), EvoViewBindingError); + // Retiring a generation drops its partition and leaves NORMAL's. + BOOST_CHECK_EQUAL(cache.For(normal), 1); + size_t partitions{0}; + cache.ForEach([&](int) { ++partitions; }); + BOOST_CHECK_EQUAL(partitions, 1U); +} + +BOOST_AUTO_TEST_CASE(view_cache_lookup_excludes_retirement) +{ + CEvoDB db{ + util::DbWrapperParams{.path = m_args.GetDataDirBase() / "evodb_cache_retirement", .memory = true, .wipe = true}}; + PublishGeneration(db); + const EvoViewToken snapshot{db.ViewFor(EvoDbIdentity::SNAPSHOT)}; + + // A generation cannot retire between a cache's liveness check and its + // partition lookup: a retirement started meanwhile waits for the lookup, + // and the view is refused once it completes. + std::atomic discarded{false}; + std::thread discard; + EvoViewCache cache{[&] { + discard = std::thread{[&] { discarded = db.DiscardSnapshotMarkers(); }}; + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + BOOST_CHECK(!discarded); + return 1; + }}; + cache.SetOwner(db); + BOOST_CHECK_EQUAL(cache.For(snapshot), 1); + discard.join(); + BOOST_CHECK(discarded); + BOOST_CHECK_THROW(cache.For(snapshot), EvoViewBindingError); +} + +BOOST_AUTO_TEST_CASE(retiring_a_generation_keeps_the_active_tip_list) +{ + CDeterministicMNManager& dmnman{*Assert(m_node.dmnman)}; + CEvoDB& evodb{*Assert(m_node.evodb)}; + const uint256 tip_hash{BlockHash(500)}; + CBlockIndex tip; + tip.nHeight = Params().GetConsensus().DIP0003Height; + tip.phashBlock = &tip_hash; + const auto tip_list_hash{[&] { return dmnman.GetListAtChainTip().GetBlockHash(); }}; + dmnman.UpdatedBlockTip(&tip); + BOOST_CHECK_EQUAL(tip_list_hash(), tip_hash); + + // A snapshot load that fails after creating its generation. + { + LOCK(::cs_main); + BOOST_REQUIRE(evodb.CreateSnapshotGeneration(BlockHash(600), 600)); + BOOST_REQUIRE(evodb.AbandonSnapshotGeneration()); + } + BOOST_CHECK_EQUAL(tip_list_hash(), tip_hash); + + // So does a published one that is rejected. + BOOST_REQUIRE(evodb.CreateSnapshotGeneration(BlockHash(600), 600)); + BOOST_REQUIRE(evodb.PublishSnapshotGeneration(std::nullopt)); + BOOST_REQUIRE(evodb.DiscardSnapshotMarkers()); + BOOST_CHECK_EQUAL(tip_list_hash(), tip_hash); +} + +BOOST_FIXTURE_TEST_CASE(credit_pool_carried_at_the_snapshot_base_is_not_served_to_the_background, ChainTestingSetup) +{ + LOCK(::cs_main); + CEvoDB& evodb{*Assert(m_node.evodb)}; + CCreditPoolManager cpoolman{evodb, *Assert(m_node.chainman)}; + constexpr int period{CCreditPoolManager::DISK_SNAPSHOT_PERIOD}; + const int base_height{(Params().GetConsensus().V20Height + period - 1) / period * period}; + const uint256 base_hash{BlockHash(base_height)}; + CBlockIndex base; + base.nHeight = base_height; + base.phashBlock = &base_hash; + BOOST_REQUIRE(DeploymentActiveAt(base, Params().GetConsensus(), Consensus::DEPLOYMENT_V20)); + + // The background chainstate derived the pool at the base itself; the + // snapshot carries a different one, which nothing has validated yet. + const auto key{std::make_pair(std::string{"cpm_S"}, base_hash)}; + CCreditPool derived; + derived.locked = 5 * COIN; + derived.currentLimit = 1 * COIN; + CCreditPool carried{derived}; + carried.currentLimit = 5 * COIN; + { + auto tx = evodb.BeginTransaction(EvoDbIdentity::NORMAL); + evodb.Write(key, derived); + tx->Commit(); + } + PublishGeneration(evodb, base_height); + const auto background_reads{[&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + auto tx = evodb.BeginTransaction(EvoDbIdentity::NORMAL); + BOOST_CHECK_EQUAL(cpoolman.GetCreditPool(&base).currentLimit, derived.currentLimit); + tx->Commit(); + }}; + // The background chainstate reads, and caches, the pool it derived. + background_reads(); + { + auto tx = evodb.BeginTransaction(EvoDbIdentity::SNAPSHOT); + evodb.Write(key, carried); + // Connecting the block after its base, the snapshot chainstate reads, + // and caches, the carried pool, not the background's. + BOOST_CHECK_EQUAL(cpoolman.GetCreditPool(&base).currentLimit, carried.currentLimit); + tx->Commit(); + } + + // The background chainstate reaching the same block hash again must still + // get the pool it derived, or completion would check the carried pool + // against itself. + background_reads(); +} + +BOOST_AUTO_TEST_CASE(view_cache_drops_values_of_an_overtaken_view) +{ + LOCK(::cs_main); + CEvoDB db{util::DbWrapperParams{.path = m_args.GetDataDirBase() / "evodb_cache_overtaken", .memory = true, .wipe = true}}; + PublishGeneration(db); + EvoViewCache cache; + cache.SetOwner(db); + + // An operation without a transaction resolves NORMAL, the active + // chainstate switches to the snapshot, and what it read since lands in + // the scratch partition, not in NORMAL's or the snapshot's. + const EvoViewToken normal{db.CurrentView()}; + BOOST_REQUIRE(normal.identity == EvoDbIdentity::NORMAL); + db.SetDefaultIdentity(EvoDbIdentity::SNAPSHOT); + cache.For(normal) = 1; + BOOST_CHECK_EQUAL(cache.For(db.ViewFor(EvoDbIdentity::NORMAL)), 0); + BOOST_CHECK_EQUAL(cache.For(db.CurrentView()), 0); + + // The reverse switch, and one that ends where it started. + const EvoViewToken snapshot{db.CurrentView()}; + db.SetDefaultIdentity(EvoDbIdentity::NORMAL); + const EvoViewToken normal_again{db.CurrentView()}; + db.SetDefaultIdentity(EvoDbIdentity::SNAPSHOT); + db.SetDefaultIdentity(EvoDbIdentity::NORMAL); + BOOST_REQUIRE(db.CurrentView() == normal_again); + cache.For(snapshot) = 2; + cache.For(normal_again) = 3; + BOOST_CHECK_EQUAL(cache.For(db.ViewFor(EvoDbIdentity::SNAPSHOT)), 0); + BOOST_CHECK_EQUAL(cache.For(db.ViewFor(EvoDbIdentity::NORMAL)), 0); + + // A view no switch overtook stores as before. + cache.For(db.CurrentView()) = 4; + BOOST_CHECK_EQUAL(cache.For(db.ViewFor(EvoDbIdentity::NORMAL)), 4); +} + +BOOST_AUTO_TEST_CASE(versionbits_states_of_an_overtaken_computation_stay_private) +{ + LOCK(::cs_main); + CEvoDB db{util::DbWrapperParams{.path = m_args.GetDataDirBase() / "evodb_versionbits", .memory = true, .wipe = true}}; + PublishGeneration(db); + // A plain BIP9 deployment that has started by the tip. + Consensus::Params consensus{Params().GetConsensus()}; + const auto pos{Consensus::DEPLOYMENT_TESTDUMMY}; + consensus.MinBIP9WarningHeight = 0; + consensus.nMinerConfirmationWindow = 144; + consensus.nRuleChangeActivationThreshold = 108; + consensus.vDeployments[pos].bit = 28; + consensus.vDeployments[pos].nStartTime = 0; + consensus.vDeployments[pos].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + consensus.vDeployments[pos].min_activation_height = 0; + consensus.vDeployments[pos].nWindowSize = 0; + consensus.vDeployments[pos].nThresholdStart = 0; + consensus.vDeployments[pos].useEHF = false; + std::vector blocks(2 * consensus.nMinerConfirmationWindow); + for (size_t i{0}; i < blocks.size(); ++i) { + blocks[i].nHeight = static_cast(i); + blocks[i].nTime = 1000 + i; + blocks[i].pprev = i > 0 ? &blocks[i - 1] : nullptr; + blocks[i].BuildSkip(); + } + const CBlockIndex* tip{&blocks.back()}; + // Inputs that differ from the real ones, standing for what the other view + // reads: the deployment has not started by the tip. + Consensus::Params other_inputs{consensus}; + other_inputs.vDeployments[pos].nStartTime = 1'000'000'000; + BOOST_REQUIRE(VersionBitsCache{}.State(tip, consensus, pos) == ThresholdState::STARTED); + BOOST_REQUIRE(VersionBitsCache{}.State(tip, other_inputs, pos) == ThresholdState::DEFINED); + + // A computation without a transaction fills its partition and the default + // identity switches under it before it ends. A reader of the same + // partition that comes in afterwards derives its own state. + EvoViewVersionBitsCache versionbits; + versionbits.SetEvoDb(&db); + versionbits.InCurrentView([&](VersionBitsCache& cache, const VersionBitsCache::KeepStates& keep) { + BOOST_REQUIRE(keep); + return cache.State(tip, other_inputs, pos, [&] { + db.SetDefaultIdentity(EvoDbIdentity::SNAPSHOT); + return keep(); + }); + }); + { + const auto normal{db.BeginTransaction(EvoDbIdentity::NORMAL)}; + BOOST_CHECK(versionbits.State(tip, consensus, pos) == ThresholdState::STARTED); + } + db.SetDefaultIdentity(EvoDbIdentity::NORMAL); + + // Nor does a computation that throws before its states are approved + // publish them. + EvoViewVersionBitsCache thrown; + thrown.SetEvoDb(&db); + BOOST_CHECK_THROW(thrown.InCurrentView([&](VersionBitsCache& cache, const VersionBitsCache::KeepStates&) { + return cache.State(tip, other_inputs, pos, [&]() -> bool { throw std::runtime_error{"test"}; }); + }), std::runtime_error); + BOOST_CHECK(thrown.State(tip, consensus, pos) == ThresholdState::STARTED); + + // A computation no switch overtakes publishes its states. + EvoViewVersionBitsCache published; + published.SetEvoDb(&db); + BOOST_CHECK(published.State(tip, other_inputs, pos) == ThresholdState::DEFINED); + BOOST_CHECK(published.State(tip, consensus, pos) == ThresholdState::DEFINED); +} + +BOOST_AUTO_TEST_CASE(list_read_across_a_default_switch_is_not_cached) +{ + CDeterministicMNManager& dmnman{*Assert(m_node.dmnman)}; + CEvoDB& evodb{*Assert(m_node.evodb)}; + const uint256 block_hash{BlockHash(700)}; + CBlockIndex block; + block.nHeight = Params().GetConsensus().DIP0003Height + 1; + block.phashBlock = &block_hash; + const auto cached{[&] { + const auto heights{dmnman.CachedListHeightsForTesting()}; + return std::ranges::count(heights, block.nHeight) > 0; + }}; + + // A list lookup without a transaction starts in NORMAL and the active + // chainstate switches to an unpublished snapshot generation after its + // first read: none of what it read is cached as NORMAL's. + BOOST_REQUIRE(evodb.CreateSnapshotGeneration(BlockHash(600), 600)); + dmnman.SetListSnapshotMissHookForTesting([&](const CBlockIndex*) { evodb.SetDefaultIdentity(EvoDbIdentity::SNAPSHOT); }); + dmnman.GetListForBlock(&block); + dmnman.SetListSnapshotMissHookForTesting({}); + evodb.SetDefaultIdentity(EvoDbIdentity::NORMAL); + BOOST_CHECK(!cached()); + + // Without a switch the same lookup is cached. + dmnman.GetListForBlock(&block); + BOOST_CHECK(cached()); +} + BOOST_AUTO_TEST_CASE(snapshot_markers_can_be_discarded) { LOCK(::cs_main); diff --git a/src/test/evo_deterministicmns_tests.cpp b/src/test/evo_deterministicmns_tests.cpp index 3ff9e6a82bf5..67e2315296bd 100644 --- a/src/test/evo_deterministicmns_tests.cpp +++ b/src/test/evo_deterministicmns_tests.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include @@ -2810,6 +2811,35 @@ struct TestChainV24PendingSetup : public TestChainV24SignalBeforeV19Setup { } }; +// A view whose tip notifications stopped, as NORMAL's do once a snapshot +// chainstate is active, still evicts cached lists as it processes blocks. +BOOST_AUTO_TEST_CASE(list_cache_follows_processed_blocks_past_a_stale_tip) +{ + TestChainDIP3Setup setup; + auto& chainman{*Assert(setup.m_node.chainman)}; + auto& dmnman{*Assert(setup.m_node.dmnman)}; + const CScript coinbase_script{GetScriptForRawPubKey(setup.coinbaseKey.GetPubKey())}; + const CBlockIndex* stale_tip{WITH_LOCK(::cs_main, return chainman.ActiveTip())}; + // Lists a live quorum may still use stay cached for this many blocks. + int quorum_window{0}; + for (const auto& params : Params().GetConsensus().llmqs) { + quorum_window = std::max(quorum_window, params.dkgInterval * (params.keepOldConnections + 1)); + } + for (int i{0}; i < 4 * quorum_window; ++i) { + setup.CreateAndProcessBlock({}, coinbase_script); + SyncWithValidationInterfaceQueue(); + dmnman.UpdatedBlockTip(stale_tip); + } + const int processed_height{WITH_LOCK(::cs_main, return chainman.ActiveHeight())}; + BOOST_REQUIRE_EQUAL(processed_height, stale_tip->nHeight + 4 * quorum_window); + // Cleanup runs once the cache holds more than MAX_CACHED_LISTS (64) lists, + // so lists added since the last cleanup are at most that many blocks old. + for (const int height : dmnman.CachedListHeightsForTesting()) { + BOOST_CHECK_MESSAGE(height == stale_tip->nHeight || height + quorum_window + 64 >= processed_height, + "list at height " << height << " outlived its quorums"); + } +} + // DIP3 activation is before v19, so operator keys registered here use the legacy encoding. BOOST_AUTO_TEST_CASE(dip3_activation_legacy) { diff --git a/src/test/quorum_proofs_tests.cpp b/src/test/quorum_proofs_tests.cpp index f6c4baf9264c..f20da3b9679c 100644 --- a/src/test/quorum_proofs_tests.cpp +++ b/src/test/quorum_proofs_tests.cpp @@ -1,7 +1,7 @@ // Copyright (c) 2025-2026 The Dash Core developers // Distributed under the MIT software license, see the accompanying file COPYING. -#include #include +#include #include #include #include @@ -345,6 +345,9 @@ BOOST_FIXTURE_TEST_CASE(generation_retries_retired_checkpoint_signer, QuorumProo BOOST_CHECK_THROW(Generate(0), UniValue); WITH_LOCK(cs_main, chain.SetTip(*tip)); + const auto normal_set{builder.ActiveCommitments(checkpoint)}; + BOOST_CHECK(!normal_set.empty()); + // Missing history is a hard error, not a reason to skip to another target. // A state read once is memoized by block hash, so start from a cold cache. llmq::ClearProofStateCacheForTesting(); @@ -352,6 +355,22 @@ BOOST_FIXTURE_TEST_CASE(generation_retries_retired_checkpoint_signer, QuorumProo BOOST_CHECK_EXCEPTION(Generate(checkpoint_height + 1), UniValue, [](const UniValue& error) { return error["message"].get_str().find("historical block unavailable") != std::string::npos; }); + + // A set is kept only once it matches the block's own quorum root, so a + // snapshot view, which has no quorum history at or below its base, is + // served the one NORMAL read. + CEvoDB& evodb{*m_node.evodb}; + { + LOCK(cs_main); + BOOST_REQUIRE(evodb.CreateSnapshotGeneration(chain.Tip()->GetBlockHash(), chain.Tip()->nHeight)); + BOOST_REQUIRE(evodb.PublishSnapshotGeneration(std::nullopt)); + } + { + LOCK(cs_main); + const auto snapshot_reads{evodb.BeginTransaction(EvoDbIdentity::SNAPSHOT)}; + BOOST_CHECK(::SerializeHash(builder.ActiveCommitments(checkpoint)) == ::SerializeHash(normal_set)); + } + BOOST_REQUIRE(WITH_LOCK(cs_main, return evodb.AbandonSnapshotGeneration())); } BOOST_FIXTURE_TEST_CASE(rotating_commitment_scan_resumes_below_cached_cycles, QuorumProofGenerationSetup) { diff --git a/src/test/validation_chainstatemanager_tests.cpp b/src/test/validation_chainstatemanager_tests.cpp index 28eeb1b3e700..0ce81c2f0207 100644 --- a/src/test/validation_chainstatemanager_tests.cpp +++ b/src/test/validation_chainstatemanager_tests.cpp @@ -4,8 +4,10 @@ // #include #include +#include #include #include +#include #include #include #include @@ -27,9 +29,12 @@ #include #include #include +#include #include #include +#include +#include #include #include #include @@ -43,6 +48,7 @@ #include +#include #include #include #include @@ -289,9 +295,9 @@ struct SnapshotTestSetup : TestChain100Setup { // Note that this means the tests run considerably slower than in-memory DB // tests, but we can't otherwise test this functionality since it relies on // destructive filesystem operations. - SnapshotTestSetup() : TestChain100Setup{ + explicit SnapshotTestSetup(const std::vector& extra_args = {}) : TestChain100Setup{ ChainType::REGTEST, - {}, + extra_args, /*coins_db_in_memory=*/false, /*block_tree_db_in_memory=*/false, /*dash_dbs_in_memory=*/false, @@ -607,7 +613,55 @@ struct SnapshotViewRecords { //! Test basic snapshot activation. BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup) { - this->SetupSnapshot(); + auto [background_chainstate, snapshot_chainstate] = this->SetupSnapshot(); + ChainstateManager& chainman = *Assert(m_node.chainman); + + // Evo-derived caches are partitioned by view: state warmed under the + // snapshot view at blocks the background chainstate also reaches is never + // served to NORMAL lookups, which must derive their own. + { + LOCK(::cs_main); + ScopedDIP3FromGenesis dip3_active; + const auto llmq_type{Consensus::LLMQType::LLMQ_TEST}; + const CBlockIndex* list_block{background_chainstate->m_chain[100]}; + const CBlockIndex* quorum_base{background_chainstate->m_chain[96]}; + const llmq::UtilParameters util_params{*m_node.dmnman, *m_node.llmq_ctx->qsnapman, chainman, quorum_base}; + auto& qblockman{*m_node.llmq_ctx->quorum_block_processor}; + const uint256 quorum_hash{GetRandHash()}; + std::shared_ptr snapshot_versionbits; + { + m_node.dmnman->SetListForBlockForTesting( + CDeterministicMNList{list_block->GetBlockHash(), list_block->nHeight, 1}); + m_node.dmnman->SetListForBlockForTesting( + CDeterministicMNList{quorum_base->GetBlockHash(), quorum_base->nHeight, 0}); + llmq::utils::GetAllQuorumMembers(llmq_type, util_params); + { + auto tx = m_node.evodb->BeginTransaction(EvoDbIdentity::SNAPSHOT); + const llmq::CFinalCommitment qc{Params().GetLLMQ(llmq_type).value(), quorum_hash}; + m_node.evodb->Write(std::make_pair(std::string{"q_mc"}, std::make_pair(llmq_type, quorum_hash)), + std::make_pair(qc, list_block->GetBlockHash())); + tx->Commit(); + } + BOOST_REQUIRE(qblockman.HasMinedCommitment(llmq_type, quorum_hash, snapshot_chainstate->m_chain)); + // A query above the base walks period boundaries at or below it. + chainman.m_versionbitscache.State(snapshot_chainstate->m_chain.Tip(), chainman.GetConsensus(), + Consensus::DEPLOYMENT_V24); + snapshot_versionbits = chainman.m_versionbitscache.ForCurrentView(); + } + + const auto normal_view{m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL)}; + std::vector list_misses; + m_node.dmnman->SetListSnapshotMissHookForTesting( + [&](const CBlockIndex* pindex) { list_misses.push_back(pindex); }); + // NORMAL has no MN-list history for these blocks, so deriving its own + // lists fails as unavailable rather than reusing the snapshot's. + BOOST_CHECK_THROW(m_node.dmnman->GetListForBlock(list_block), BlockDataUnavailableError); + BOOST_CHECK_THROW(llmq::utils::GetAllQuorumMembers(llmq_type, util_params), BlockDataUnavailableError); + BOOST_CHECK(list_misses == (std::vector{list_block, quorum_base})); + BOOST_CHECK(!qblockman.HasMinedCommitment(llmq_type, quorum_hash, snapshot_chainstate->m_chain)); + BOOST_CHECK(chainman.m_versionbitscache.ForCurrentView() != snapshot_versionbits); + m_node.dmnman->SetListSnapshotMissHookForTesting(nullptr); + } } //! A snapshot chainstate on a cold EvoDB, which never derived the MN lists @@ -615,7 +669,9 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_activate_snapshot, SnapshotTestSetup) //! is active at the base, so a block that needs one of those lists stalls the //! chainstate on its own Evo state. struct EvoStallTestSetup : SnapshotTestSetup { - Chainstate& m_snapshot_cs{*std::get<1>(SetupSnapshot())}; + const std::tuple m_chainstates{SetupSnapshot()}; + Chainstate& m_background_cs{*std::get<0>(m_chainstates)}; + Chainstate& m_snapshot_cs{*std::get<1>(m_chainstates)}; CBlockIndex* SnapshotTip() const { return WITH_LOCK(::cs_main, return m_snapshot_cs.m_chain.Tip()); } @@ -632,12 +688,133 @@ struct EvoStallTestSetup : SnapshotTestSetup { } }; +//! A block that stalls after its masternode list was derived leaves no list +//! for itself in its view's cache: the list's diff was rolled back with the +//! block's Evo transaction, and the block never connected. +BOOST_FIXTURE_TEST_CASE(chainstatemanager_stall_after_mn_list_evicts_it, SnapshotTestSetup) +{ + auto [background_chainstate, snapshot_chainstate] = this->SetupSnapshot(); + ChainstateManager& chainman = *Assert(m_node.chainman); + // Stay outside every regtest LLMQ mining window, so the block needs no + // quorum commitment. + while (WITH_LOCK(::cs_main, return (snapshot_chainstate->m_chain.Height() + 1) % 24) < 21) { + mineBlocks(1); + } + const CBlockIndex* tip{WITH_LOCK(::cs_main, return snapshot_chainstate->m_chain.Tip())}; + const CBlock template_block{CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), *snapshot_chainstate)}; + + // With DIP3 counted from genesis the block derives its list from its + // parent's, given here, and then needs the quorum history the snapshot + // does not carry. + ScopedDIP3FromGenesis dip3_active; + { + LOCK(::cs_main); + m_node.dmnman->SetListForBlockForTesting(CDeterministicMNList{tip->GetBlockHash(), tip->nHeight, 0}); + } + const auto block{std::make_shared(MakeCbTxBlock(template_block, tip->nHeight + 1))}; + { + ASSERT_DEBUG_LOG("GetMinedCommitmentsUntilBlock"); + BOOST_CHECK(!chainman.ProcessNewBlock(block, /*force_processing=*/true, /*new_block=*/nullptr)); + } + + LOCK(::cs_main); + const CBlockIndex* stalled{chainman.m_blockman.LookupBlockIndex(block->GetHash())}; + BOOST_REQUIRE(stalled); + BOOST_CHECK_EQUAL(snapshot_chainstate->m_chain.Tip(), tip); + BOOST_CHECK_EQUAL(stalled->nStatus & BLOCK_FAILED_MASK, 0U); + const auto heights{m_node.dmnman->CachedListHeightsForTesting()}; + BOOST_CHECK(std::find(heights.begin(), heights.end(), stalled->nHeight) == heights.end()); + BOOST_CHECK_THROW(m_node.dmnman->GetListForBlock(stalled), BlockDataUnavailableError); +} + +//! V19 activates above the snapshot base, so the background chainstate +//! connects blocks from before v19 and the snapshot chainstate from after it. +struct SnapshotAcrossV19Setup : SnapshotTestSetup { + SnapshotAcrossV19Setup() : SnapshotTestSetup{{"-testactivationheight=v19@115"}} {} +}; + +//! A snapshot rejected while its chainstate connects a block hands the active +//! role to the background chainstate for good and stops the node. +BOOST_FIXTURE_TEST_CASE(chainstatemanager_rejection_mid_connect_activates_background, SnapshotAcrossV19Setup) +{ + auto [background_chainstate, snapshot_chainstate] = this->SetupSnapshot(); + ChainstateManager& chainman = *Assert(m_node.chainman); + const auto evo_chain{ + [&](EvoDbIdentity identity) { return WITH_LOCK(::cs_main, return chainman.EvoChain(identity)); }}; + // Each view's Evo indexes describe its own chainstate's chain. + BOOST_CHECK(evo_chain(EvoDbIdentity::NORMAL) == &background_chainstate->m_chain); + BOOST_CHECK(evo_chain(EvoDbIdentity::SNAPSHOT) == &snapshot_chainstate->m_chain); + mineBlocks(6); + const CBlockIndex* snapshot_tip{WITH_LOCK(::cs_main, return snapshot_chainstate->m_chain.Tip())}; + const CBlock block{MakeCbTxBlock( + CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), *snapshot_chainstate), snapshot_tip->nHeight + 1)}; + + // The block's MN-list lookup finds the snapshot state inconsistent. + std::optional dip3_active{std::in_place}; + m_node.dmnman->SetListSnapshotMissHookForTesting([&](const CBlockIndex*) { + if (!dip3_active) return; + dip3_active.reset(); + throw evo::SnapshotStateMismatchError("test mismatch"); + }); + BOOST_REQUIRE_EQUAL(m_node.exit_status.load(), EXIT_SUCCESS); + chainman.ProcessNewBlock(std::make_shared(block), /*force_processing=*/true, /*new_block=*/nullptr); + m_node.dmnman->SetListSnapshotMissHookForTesting(nullptr); + BOOST_REQUIRE(!dip3_active); + + BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE); + BOOST_CHECK_EQUAL(&chainman.ActiveChainstate(), background_chainstate); + // No chainstate reads the rejected snapshot's view any more. + BOOST_CHECK(evo_chain(EvoDbIdentity::NORMAL) == &background_chainstate->m_chain); + BOOST_CHECK(!evo_chain(EvoDbIdentity::SNAPSHOT)); + m_node.kernel->interrupt.reset(); + SetMiscWarning(Untranslated("")); +} + +//! A snapshot rejected in the step that first disconnected one of its blocks +//! drops that block's queued transactions with the mempool it handed back. +BOOST_FIXTURE_TEST_CASE(chainstatemanager_rejection_after_disconnect, EvoStallTestSetup) +{ + ChainstateManager& chainman = *Assert(m_node.chainman); + // The tip is above the base, and the blocks of the branch replacing it + // are outside every regtest LLMQ mining window. + do { + mineBlocks(1); + } while (WITH_LOCK(::cs_main, return (m_snapshot_cs.m_chain.Height() + 1) % 24) < 22); + const CBlockIndex* snapshot_tip{SnapshotTip()}; + const CBlock block_template{CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), m_snapshot_cs)}; + CBlock parent; + BOOST_REQUIRE(chainman.m_blockman.ReadBlockFromDisk(parent, *snapshot_tip->pprev)); + // A branch from below the tip with more work: reorganizing onto it + // disconnects the tip before it connects the branch. + const auto sibling{ChildOf(block_template, parent, snapshot_tip->nHeight)}; + const auto branch_tip{ChildOf(block_template, *sibling, snapshot_tip->nHeight + 1)}; + + // Connecting the sibling, the MN-list lookup finds the snapshot state + // inconsistent. + std::optional dip3_active{std::in_place}; + m_node.dmnman->SetListSnapshotMissHookForTesting([&](const CBlockIndex*) { + if (!dip3_active || m_snapshot_cs.m_chain.Tip() == snapshot_tip) return; + dip3_active.reset(); + throw evo::SnapshotStateMismatchError("test mismatch"); + }); + chainman.ProcessNewBlock(sibling, /*force_processing=*/true, /*new_block=*/nullptr); + BOOST_REQUIRE(dip3_active); + chainman.ProcessNewBlock(branch_tip, /*force_processing=*/true, /*new_block=*/nullptr); + m_node.dmnman->SetListSnapshotMissHookForTesting(nullptr); + BOOST_REQUIRE(!dip3_active); + + BOOST_CHECK_EQUAL(m_node.exit_status.load(), EXIT_FAILURE); + BOOST_CHECK_EQUAL(&chainman.ActiveChainstate(), &m_background_cs); + m_node.kernel->interrupt.reset(); +} + //! A historical block body this node does not have is local state, not //! invalidity: a snapshot chainstate that has to rebuild the credit pool or the //! EHF signals from it stalls, and the block it was connecting stays valid. BOOST_FIXTURE_TEST_CASE(chainstatemanager_missing_body_stalls, EvoStallTestSetup) { ChainstateManager& chainman = *Assert(m_node.chainman); + Chainstate* background_chainstate{&m_background_cs}; Chainstate* snapshot_chainstate{&m_snapshot_cs}; CBlockIndex* tip{SnapshotTip()}; const CBlock template_block{CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), *snapshot_chainstate)}; @@ -720,8 +897,54 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_missing_body_stalls, EvoStallTestSetup tip->nStatus = pruned_status; } + // The block above the snapshot base checks its coinbase ChainLock against + // the base's, whose body a snapshot node does not have: it cannot tell a + // missing ChainLock from an unreadable one. + { + LOCK(::cs_main); + const int snapshot_base_height{m_node.evodb->ViewFor(EvoDbIdentity::SNAPSHOT).base_height}; + CBlockIndex* snapshot_base{snapshot_chainstate->m_chain[snapshot_base_height]}; + const uint32_t snapshot_base_status{snapshot_base->nStatus}; + // The background chainstate accepting the base's coinbase ChainLock + // remembers it for its own view only. + { + const auto normal_view{m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL)}; + CBLSSecretKey key; + key.MakeNewKey(); + const CBLSSignature sig{key.Sign(uint256::ONE)}; + BOOST_REQUIRE(m_node.chainlocks->UpdateBestChainlock( + GetRandHash(), chainlock::ChainLockSig{snapshot_base_height - 1, uint256::ONE, sig}, nullptr)); + CCbTx base_cbtx; + base_cbtx.nVersion = CCbTx::Version::CLSIG_AND_BALANCE; + base_cbtx.nHeight = snapshot_base_height; + base_cbtx.bestCLSignature.Set(sig); + BlockValidationState base_state; + BOOST_CHECK(CheckCbTxBestChainlock(base_cbtx, snapshot_base, consensus, m_node.chainman->m_blockman, + background_chainstate->m_chain, *m_node.llmq_ctx->qman, + *m_node.chainlocks, base_state)); + m_node.chainlocks->ResetChainlock(); + } + snapshot_base->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO); + CCbTx cbtx; + cbtx.nVersion = CCbTx::Version::CLSIG_AND_BALANCE; + cbtx.nHeight = snapshot_base_height + 1; + BlockValidationState cl_state; + BOOST_CHECK_THROW(CheckCbTxBestChainlock(cbtx, snapshot_chainstate->m_chain[snapshot_base_height + 1], + consensus, m_node.chainman->m_blockman, snapshot_chainstate->m_chain, + *m_node.llmq_ctx->qman, *m_node.chainlocks, cl_state), + BlockDataUnavailableError); + // The quorum modifier of a work block at or below the base reads the + // same coinbase through the same lookup. + BOOST_CHECK_THROW(GetNonNullCoinbaseChainlock(m_node.evodb->CurrentView(), m_node.chainman->m_blockman, snapshot_base), + BlockDataUnavailableError); + snapshot_base->nStatus = snapshot_base_status; + // With the body there, the coinbase is read. + BOOST_CHECK_NO_THROW( + GetNonNullCoinbaseChainlock(m_node.evodb->CurrentView(), m_node.chainman->m_blockman, snapshot_base)); + } + // Checking a child's EHF signals never rebuilds those of the block it - // extends, which was never connected: it ends in a local error. + // extends, which was never connected: the snapshot view lacks them. const auto child{ChildOf(template_block, *block, tip->nHeight + 2, CCbTx::Version::CLSIG_AND_BALANCE)}; chainman.ProcessNewBlock(child, /*force_processing=*/true, /*new_block=*/nullptr); { @@ -729,14 +952,34 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_missing_body_stalls, EvoStallTestSetup const CBlockIndex* child_index{chainman.m_blockman.LookupBlockIndex(child->GetHash())}; BOOST_REQUIRE(child_index); BlockValidationState mnhf_state; - BOOST_CHECK(!m_node.special_tx->m_mnhfman->ProcessBlock(*child, child_index, /*fJustCheck=*/true, mnhf_state)); - BOOST_CHECK(mnhf_state.IsError()); + BOOST_CHECK_THROW(m_node.special_tx->m_mnhfman->ProcessBlock(*child, child_index, /*fJustCheck=*/true, mnhf_state), + BlockDataUnavailableError); } { LOCK(::cs_main); tip->nStatus = tip_status; chainman.m_blockman.m_have_pruned = false; } + + // A lookup never rebuilds the EHF signals, even with the bodies back and + // inside a block-scoped transaction: those at the tip, never stored while + // V20 was inactive, stay unavailable to the snapshot view, and nothing is + // written. + const auto signals_key{std::make_pair(std::string{"mnhf_s2"}, tip->GetBlockHash())}; + { + // Opening an EvoDB drops every cached signal, as a restart would. + const CEvoDB unrelated{util::DbWrapperParams{.path = {}, .memory = true, .wipe = true}}; + } + { + LOCK(::cs_main); + { + auto tx{m_node.evodb->BeginTransaction(EvoDbIdentity::SNAPSHOT)}; + BOOST_CHECK_THROW(m_node.special_tx->m_mnhfman->GetSignalsStage(tip), BlockDataUnavailableError); + tx->Commit(); + } + BOOST_CHECK(m_node.evodb->CommitRootTransaction(EvoDbIdentity::SNAPSHOT)); + BOOST_CHECK(!m_node.evodb->Exists(signals_key)); + } } BOOST_FIXTURE_TEST_CASE(chainstatemanager_reconsider_block_candidates, SnapshotTestSetup) @@ -1102,6 +1345,199 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_mined_commitment_is_chain_aware, Snaps BOOST_CHECK(qblockman.ProcessBlock(*background_chainstate, block, snapshot_mined_block, state, /*fJustCheck=*/true, /*fBLSChecks=*/false)); } + + // Block templates, built before DIP3 is moved to genesis below. + const CBlock signal_template{CreateBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()), *snapshot_chainstate)}; + const CBlockIndex* snapshot_tip{WITH_LOCK(::cs_main, return snapshot_chainstate->m_chain.Tip())}; + + // Before DIP3 no quorum is mined, so while DIP3 activates above the base, + // the snapshot view's empty history at or below it is authoritative. + const auto platform_type{Params().GetConsensus().llmqTypePlatform}; + { + LOCK(::cs_main); + BOOST_CHECK(qblockman.GetMinedCommitmentsUntilBlock(platform_type, snapshot_tip, 1).empty()); + } + + // With DIP3 active at the base, a commitment only NORMAL has, for a quorum + // at or below the base, is history the snapshot view lacks: a miss there is + // unavailable data, not a quorum that was never mined. Above the base, a + // miss is authoritative. + ScopedDIP3FromGenesis dip3_active; + const CBlockIndex* earlier_base{ + WITH_LOCK(::cs_main, return background_chainstate->m_chain[quorum_base->nHeight - llmq_params.dkgInterval])}; + const uint256 normal_only_hash{earlier_base->GetBlockHash()}; + { + LOCK(::cs_main); + const CBlockIndex* normal_mined_block{ + background_chainstate->m_chain[earlier_base->nHeight + llmq_params.dkgMiningWindowStart]}; + auto tx = m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL); + m_node.evodb->Write(std::make_pair(std::string{"q_mc"}, std::make_pair(llmq_type, normal_only_hash)), + std::make_pair(llmq::CFinalCommitment{llmq_params, normal_only_hash}, + normal_mined_block->GetBlockHash())); + tx->Commit(); + } + { + LOCK(::cs_main); + const auto background_view{m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL)}; + BOOST_CHECK(qblockman.HasMinedCommitment(llmq_type, normal_only_hash, background_chainstate->m_chain)); + } + { + LOCK(::cs_main); + BOOST_CHECK_THROW(qblockman.HasMinedCommitment(llmq_type, normal_only_hash, snapshot_chainstate->m_chain), + BlockDataUnavailableError); + BOOST_CHECK_THROW(qman.GetQuorum(llmq_type, normal_only_hash, snapshot_chainstate->m_chain), + BlockDataUnavailableError); + BOOST_CHECK(!qblockman.HasMinedCommitment(llmq_type, snapshot_mined_block->GetBlockHash(), + snapshot_chainstate->m_chain)); + } + + // So a block whose EHF signal names that quorum stalls instead of failing. + ChainstateManager& chainman{*Assert(m_node.chainman)}; + Consensus::Params& consensus{const_cast(Params().GetConsensus())}; + struct V20HeightRestore { + Consensus::Params& params; + const int height; + ~V20HeightRestore() { params.V20Height = height; } + } v20_restore{consensus, std::exchange(consensus.V20Height, 1)}; + MNHFTxPayload signal; + signal.signal.versionBit = consensus.vDeployments[Consensus::DEPLOYMENT_V24].bit; + signal.signal.quorumHash = normal_only_hash; + CMutableTransaction signal_tx; + signal_tx.nVersion = CTransaction::SPECIAL_VERSION; + signal_tx.nType = TRANSACTION_MNHF_SIGNAL; + SetTxPayload(signal_tx, signal); + CBlock signal_block{MakeCbTxBlock(signal_template, snapshot_tip->nHeight + 1, CCbTx::Version::CLSIG_AND_BALANCE)}; + signal_block.vtx.push_back(MakeTransactionRef(std::move(signal_tx))); + signal_block.hashMerkleRoot = BlockMerkleRoot(signal_block); + while (!CheckProofOfWork(signal_block.GetHash(), signal_block.nBits, consensus)) + ++signal_block.nNonce; + const auto signal_block_ref{std::make_shared(signal_block)}; + chainman.ProcessNewBlock(signal_block_ref, /*force_processing=*/true, /*new_block=*/nullptr); + BlockValidationState state; + BOOST_CHECK(!snapshot_chainstate->ActivateBestChain(state, signal_block_ref)); + BOOST_CHECK(IsLocalEvoStateError(state)); + { + LOCK(::cs_main); + const CBlockIndex* index{chainman.m_blockman.LookupBlockIndex(signal_block.GetHash())}; + BOOST_REQUIRE(index); + BOOST_CHECK_EQUAL(index->nStatus & BLOCK_FAILED_MASK, 0U); + BOOST_CHECK_EQUAL(snapshot_chainstate->m_chain.Tip(), snapshot_tip); + } + + // A scan by height the snapshot view cannot satisfy from the commitments + // mined above the base is unknown, not short: a Platform quorum mined at or + // below the base, recorded only in NORMAL, is missing from its result. The + // view is isolated from NORMAL, so its answer cannot depend on that record; + // NORMAL resolving it shows the history the scan needs does exist. + { + LOCK(::cs_main); + const CBlockIndex* platform_mined_block{ + background_chainstate->m_chain[earlier_base->nHeight + llmq_params.dkgMiningWindowStart]}; + auto tx = m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL); + // The keys mirror DB_MINED_COMMITMENT and DB_MINED_COMMITMENT_BY_INVERSED_HEIGHT + // in llmq/blockprocessor.cpp. + m_node.evodb->Write(std::make_pair(std::string{"q_mc"}, std::make_pair(platform_type, normal_only_hash)), + std::make_pair(llmq::CFinalCommitment{Params().GetLLMQ(platform_type).value(), normal_only_hash}, + platform_mined_block->GetBlockHash())); + m_node.evodb->Write(std::make_tuple(std::string{"q_mcih"}, platform_type, + htobe32_internal(std::numeric_limits::max() - + platform_mined_block->nHeight)), + earlier_base->nHeight); + tx->Commit(); + } + { + LOCK(::cs_main); + const auto background_view{m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL)}; + BOOST_CHECK(qblockman.GetMinedCommitmentsUntilBlock(platform_type, background_chainstate->m_chain.Tip(), 1) == + std::vector{earlier_base}); + } + { + LOCK(::cs_main); + BOOST_CHECK_THROW(qblockman.GetMinedCommitmentsUntilBlock(platform_type, snapshot_tip, 1), + BlockDataUnavailableError); + BOOST_CHECK_THROW(qman.ScanQuorums(platform_type, snapshot_tip, 1, snapshot_chainstate->m_chain), + BlockDataUnavailableError); + } + + // So a block withdrawing from Platform under that quorum stalls instead of + // failing as signed by a quorum too old. + CMutableTransaction unlock_tx; + unlock_tx.nVersion = CTransaction::SPECIAL_VERSION; + unlock_tx.nType = TRANSACTION_ASSET_UNLOCK; + unlock_tx.vout.emplace_back(COIN, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); + SetTxPayload(unlock_tx, + CAssetUnlockPayload{CAssetUnlockPayload::INITIAL_VERSION, /*index=*/1, /*fee=*/1000, + static_cast(snapshot_tip->nHeight), normal_only_hash, CBLSSignature{}}); + CBlock unlock_block{MakeCbTxBlock(signal_template, snapshot_tip->nHeight + 1, CCbTx::Version::CLSIG_AND_BALANCE)}; + unlock_block.vtx.push_back(MakeTransactionRef(std::move(unlock_tx))); + unlock_block.hashMerkleRoot = BlockMerkleRoot(unlock_block); + while (!CheckProofOfWork(unlock_block.GetHash(), unlock_block.nBits, consensus)) + ++unlock_block.nNonce; + const auto unlock_block_ref{std::make_shared(unlock_block)}; + chainman.ProcessNewBlock(unlock_block_ref, /*force_processing=*/true, /*new_block=*/nullptr); + BOOST_CHECK(!snapshot_chainstate->ActivateBestChain(state, unlock_block_ref)); + BOOST_CHECK(IsLocalEvoStateError(state)); + { + LOCK(::cs_main); + const CBlockIndex* index{chainman.m_blockman.LookupBlockIndex(unlock_block.GetHash())}; + BOOST_REQUIRE(index); + BOOST_CHECK_EQUAL(index->nStatus & BLOCK_FAILED_MASK, 0U); + BOOST_CHECK_EQUAL(snapshot_chainstate->m_chain.Tip(), snapshot_tip); + } + + // The same holds for the rotating per-index scan, and a scan that the + // commitments mined above the base do satisfy is complete. + const auto rotating_type{Consensus::LLMQType::LLMQ_TEST_DIP0024}; + { + LOCK(::cs_main); + const auto background_view{m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL)}; + BOOST_CHECK(!qblockman.GetLastMinedCommitmentsByQuorumIndexUntilBlock(rotating_type, snapshot_tip, 0, 0)); + } + { + LOCK(::cs_main); + auto tx = m_node.evodb->BeginTransaction(EvoDbIdentity::SNAPSHOT); + // The keys mirror DB_MINED_COMMITMENT_BY_INVERSED_HEIGHT(_Q_INDEXED). + const uint32_t mined_key{htobe32_internal(std::numeric_limits::max() - snapshot_mined_block->nHeight)}; + m_node.evodb->Write(std::make_tuple(std::string{"q_mcih"}, platform_type, mined_key), quorum_base->nHeight); + m_node.evodb->Write(std::make_tuple(std::string{"q_mcihi"}, rotating_type, 0, mined_key), quorum_base->nHeight); + tx->Commit(); + } + { + LOCK(::cs_main); + BOOST_CHECK_THROW(qblockman.GetLastMinedCommitmentsByQuorumIndexUntilBlock(rotating_type, snapshot_tip, 0, 1), + BlockDataUnavailableError); + BOOST_CHECK(qblockman.GetLastMinedCommitmentsByQuorumIndexUntilBlock(rotating_type, snapshot_tip, 0, 0) == + quorum_base); + BOOST_CHECK(qblockman.GetMinedCommitmentsUntilBlock(platform_type, snapshot_tip, 1) == + std::vector{quorum_base}); + BOOST_CHECK_THROW(qblockman.GetMinedCommitmentsUntilBlock(platform_type, snapshot_tip, 2), + BlockDataUnavailableError); + + // Nothing can be mined below DIP3, so a short scan from there is complete. + const CBlockIndex* pre_dip3{snapshot_tip->GetAncestor(Params().GetConsensus().DIP0003Height - 1)}; + BOOST_REQUIRE(pre_dip3); + BOOST_CHECK(qblockman.GetMinedCommitmentsUntilBlock(platform_type, pre_dip3, 1).empty()); + BOOST_CHECK(!qblockman.GetLastMinedCommitmentsByQuorumIndexUntilBlock(rotating_type, pre_dip3, 0, 0)); + + // Neither can a type that was not enabled up to the base, so its short + // scan is complete too. + const auto unenabled_type{Consensus::LLMQType::LLMQ_TEST_V17}; + BOOST_REQUIRE(!chainman.IsQuorumTypeEnabled(unenabled_type, snapshot_tip)); + BOOST_CHECK(qblockman.GetMinedCommitmentsUntilBlock(unenabled_type, snapshot_tip, 1).empty()); + BOOST_CHECK(!qblockman.GetLastMinedCommitmentsByQuorumIndexUntilBlock(unenabled_type, snapshot_tip, 0, 0)); + + // A type retired before the base but enabled at the first block DIP3 + // lets mine may have history there, even with DIP3 from genesis. + const auto retired_type{Consensus::LLMQType::LLMQ_TEST_INSTANTSEND}; + BOOST_REQUIRE(!chainman.IsQuorumTypeEnabled(retired_type, snapshot_tip)); + BOOST_REQUIRE(chainman.IsQuorumTypeEnabled(retired_type, snapshot_tip->GetAncestor(0))); + BOOST_CHECK_THROW(qblockman.GetMinedCommitmentsUntilBlock(retired_type, snapshot_tip, 1), + BlockDataUnavailableError); + consensus.DIP0003Height = 0; + BOOST_CHECK_THROW(qblockman.GetMinedCommitmentsUntilBlock(retired_type, snapshot_tip, 1), + BlockDataUnavailableError); + } + SetMiscWarning(Untranslated("")); } BOOST_FIXTURE_TEST_CASE(chainstatemanager_evodb_snapshot_only_flush_restart, SnapshotTestSetup) @@ -1449,6 +1885,39 @@ BOOST_FIXTURE_TEST_CASE(chainstatemanager_snapshot_cleanup_recovers_invalid_rena WITH_LOCK(::cs_main, return restarted.ActiveChainstate().CoinsTip().GetBestBlock()))); } +//! At or below the base, the snapshot view holds only carried rotation +//! quarters. Reading an uncarried one as an input, to reconstruct or to +//! predict members, is unavailable data rather than fewer quarters or "not +//! available yet"; NORMAL keeps its legacy behavior. +BOOST_FIXTURE_TEST_CASE(chainstatemanager_uncarried_quarter_is_unavailable, SnapshotTestSetup) +{ + Chainstate* snapshot_chainstate{std::get<1>(this->SetupSnapshot())}; + ChainstateManager& chainman = *Assert(m_node.chainman); + LOCK(::cs_main); + const auto rotating{Consensus::LLMQType::LLMQ_TEST_DIP0024}; + const CBlockIndex* cycle_base{snapshot_chainstate->m_chain[96]}; + const CBlockIndex* next_work{snapshot_chainstate->m_chain[120 - llmq::WORK_DIFF_DEPTH]}; + const llmq::UtilParameters reconstruct{*m_node.dmnman, *m_node.llmq_ctx->qsnapman, chainman, cycle_base}; + const llmq::UtilParameters predict{*m_node.dmnman, *m_node.llmq_ctx->qsnapman, chainman, next_work}; + // Prediction needs V20's work-block modifier. + Consensus::Params& consensus{const_cast(Params().GetConsensus())}; + struct V20HeightRestore { + Consensus::Params& params; + const int height; + ~V20HeightRestore() { params.V20Height = height; } + } v20_restore{consensus, std::exchange(consensus.V20Height, 1)}; + { + BOOST_CHECK_THROW(llmq::utils::GetAllQuorumMembers(rotating, reconstruct), BlockDataUnavailableError); + BOOST_CHECK_THROW(llmq::utils::ComputeQuorumMembersFromWorkBlock(rotating, predict, next_work, 120), + BlockDataUnavailableError); + } + { + const auto background_view{m_node.evodb->BeginTransaction(EvoDbIdentity::NORMAL)}; + BOOST_CHECK_NO_THROW(llmq::utils::GetAllQuorumMembers(rotating, reconstruct)); + BOOST_CHECK(!llmq::utils::ComputeQuorumMembersFromWorkBlock(rotating, predict, next_work, 120)); + } +} + //! A rejection is persisted before the snapshot's coins directory is renamed. A //! crash in between must leave startup able to finish the invalidation and run //! on NORMAL alone, without a reindex. diff --git a/src/validation.cpp b/src/validation.cpp index 34c545feae04..35853f0c4a98 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -6186,9 +6186,19 @@ Chainstate& ChainstateManager::InitializeChainstate(CTxMemPool* mempool, m_ibd_chainstate = std::make_unique( mempool, m_blockman, *this, evoDb, special_tx, chainlocks, isman); m_active_chainstate = m_ibd_chainstate.get(); + m_versionbitscache.SetEvoDb(&evoDb); return *m_active_chainstate; } +std::shared_ptr EvoViewVersionBitsCache::ForCurrentView(EvoViewToken* view_out) const +{ + const CEvoDB* evodb{WITH_LOCK(m_mutex, return m_evodb)}; + const EvoViewToken view{evodb ? evodb->CurrentView() : EvoViewToken{}}; + if (view_out != nullptr) *view_out = view; + LOCK(m_mutex); + return m_parts.For(view); +} + const AssumeutxoData* ExpectedAssumeutxo( const int height, const CChainParams& chainparams) { @@ -6922,6 +6932,15 @@ Chainstate& ChainstateManager::ActiveChainstate() const return *m_active_chainstate; } +const CChain* ChainstateManager::EvoChain(::EvoDbIdentity identity) const +{ + AssertLockHeld(::cs_main); + for (const Chainstate* chainstate : {m_ibd_chainstate.get(), m_snapshot_chainstate.get()}) { + if (IsUsable(chainstate) && chainstate->EvoDbIdentity() == identity) return &chainstate->m_chain; + } + return nullptr; +} + bool ChainstateManager::IsSnapshotActive() const { LOCK(::cs_main); diff --git a/src/validation.h b/src/validation.h index cbeb6d0d1da0..e608875e729a 100644 --- a/src/validation.h +++ b/src/validation.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include // IWYU pragma: export @@ -854,6 +855,87 @@ enum class SnapshotCompletionResult { EVO_STATE_MISMATCH, }; +/** VersionBitsCache partitioned by Evo view. EHF signals that gate deployment + * states are Evo state, so a state computed under one view is never served to + * another. The calling thread's view also selects the EHF signals that + * SignalHeight reads, so the partition and its inputs always agree. */ +class EvoViewVersionBitsCache +{ +public: + //! Run `f` on the current view's partition, which it fills as it reads. + //! A default-identity switch can overtake a view resolved without a + //! transaction while `f` runs, so then `f` hands the partition a + //! KeepStates that drops what `f` added if that has happened by the time it + //! is done. Until then those states stay behind the partition's lock, so no + //! other reader sees them before. + template + auto InCurrentView(F&& f) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + EvoViewToken view; + const auto cache{ForCurrentView(&view)}; + // A transaction's view cannot change under it. + if (!view.ResolvedByDefault()) return f(*cache, VersionBitsCache::KeepStates{}); + return f(*cache, VersionBitsCache::KeepStates{[&view] { return !view.db->IsOvertaken(view); }}); + } + + //! Bind the EvoDB whose views key the partitions. + void SetEvoDb(const CEvoDB* evodb) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + LOCK(m_mutex); + m_evodb = evodb; + } + + //! The partition of this thread's current view, which is stored in + //! `view_out` if given. + std::shared_ptr ForCurrentView(EvoViewToken* view_out = nullptr) const + EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); + + BIP9Stats Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, + std::vector* signalling_blocks = nullptr) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + return InCurrentView([&](VersionBitsCache& cache, const VersionBitsCache::KeepStates& keep) { + return cache.Statistics(pindex, params, pos, signalling_blocks, keep); + }); + } + static uint32_t Mask(const Consensus::Params& params, Consensus::DeploymentPos pos) + { + return VersionBitsCache::Mask(params, pos); + } + ThresholdState State(const CBlockIndex* pindexPrev, const Consensus::Params& params, + Consensus::DeploymentPos pos) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + return InCurrentView([&](VersionBitsCache& cache, const VersionBitsCache::KeepStates& keep) { + return cache.State(pindexPrev, params, pos, keep); + }); + } + int StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, + Consensus::DeploymentPos pos) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + return InCurrentView([&](VersionBitsCache& cache, const VersionBitsCache::KeepStates& keep) { + return cache.StateSinceHeight(pindexPrev, params, pos, keep); + }); + } + int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) const + EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + return InCurrentView([&](VersionBitsCache& cache, const VersionBitsCache::KeepStates& keep) { + return cache.ComputeBlockVersion(pindexPrev, params, keep); + }); + } + void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) + { + LOCK(m_mutex); + m_parts.Clear(); + } + +private: + mutable Mutex m_mutex; + const CEvoDB* m_evodb GUARDED_BY(m_mutex){nullptr}; + // Shared, so a partition dropped by another thread outlives its users. + mutable EvoViewCache> m_parts GUARDED_BY(m_mutex){ + [] { return std::make_shared(); }}; +}; + /** * Provides an interface for creating and interacting with one or two * chainstates: an IBD chainstate generated by downloading blocks, and @@ -1137,6 +1219,10 @@ class ChainstateManager CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; } int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); } CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); } + //! The chain of the usable chainstate whose Evo state `identity` names, or + //! nullptr if none does. Evo indexes read under that identity, such as the + //! mined-commitment index, describe this chain. + const CChain* EvoChain(::EvoDbIdentity identity) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); node::BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { @@ -1150,9 +1236,10 @@ class ChainstateManager } /** - * Track versionbit status + * Track versionbit status. EHF-gated deployments depend on Evo state, so + * the cache is partitioned by the calling operation's Evo view. */ - mutable VersionBitsCache m_versionbitscache; + mutable EvoViewVersionBitsCache m_versionbitscache; //! @returns true if a snapshot-based chainstate is in use. Also implies //! that a background validation chainstate is also in use. @@ -1315,13 +1402,23 @@ class ChainstateManager template bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep) { - return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache); + // A buried deployment is decided by height alone, in every Evo view. + if constexpr (std::is_same_v) { + return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep); + } else { + assert(Consensus::ValidDeployment(dep)); + return ThresholdState::ACTIVE == chainman.m_versionbitscache.State(pindexPrev, chainman.GetConsensus(), dep); + } } template bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep) { - return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache); + if constexpr (std::is_same_v) { + return DeploymentActiveAt(index, chainman.GetConsensus(), dep); + } else { + return DeploymentActiveAfter(index.pprev, chainman, dep); + } } template diff --git a/src/versionbits.cpp b/src/versionbits.cpp index 3163dd40568c..6cebcd7f0aa2 100644 --- a/src/versionbits.cpp +++ b/src/versionbits.cpp @@ -6,6 +6,7 @@ #include #include +#include #include static int calculateStartHeight(const CBlockIndex* pindexPrev, ThresholdState state, const int nPeriod, const ThresholdConditionCache& cache) { @@ -277,22 +278,54 @@ class VersionBitsConditionChecker : public AbstractThresholdConditionChecker { } // namespace -ThresholdState VersionBitsCache::State(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) +template +std::invoke_result_t VersionBitsCache::Tentatively(const KeepStates& keep, F&& compute) +{ + AssertLockHeld(m_mutex); + if (!keep) return compute(); + std::array sizes; + for (unsigned int d = 0; d < Consensus::MAX_VERSION_BITS_DEPLOYMENTS; d++) { + sizes[d] = m_caches[d].size(); + } + // A computation only adds states. A deployment's states are dropped all + // together: a STARTED state needs those of the periods before it. + const auto drop_added = [&]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { + for (unsigned int d = 0; d < Consensus::MAX_VERSION_BITS_DEPLOYMENTS; d++) { + if (m_caches[d].size() != sizes[d]) m_caches[d].clear(); + } + }; + try { + auto result{compute()}; + if (!keep()) drop_added(); + return result; + } catch (...) { + drop_added(); + throw; + } +} + +ThresholdState VersionBitsCache::State(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, const KeepStates& keep) { LOCK(m_mutex); - return VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, m_caches[pos]); + return Tentatively(keep, [&]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { + return VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, m_caches[pos]); + }); } -BIP9Stats VersionBitsCache::Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, std::vector* signalling_blocks) +BIP9Stats VersionBitsCache::Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, std::vector* signalling_blocks, const KeepStates& keep) { LOCK(m_mutex); - return VersionBitsConditionChecker(pos).GetStateStatisticsFor(pindex, params, m_caches[pos], signalling_blocks); + return Tentatively(keep, [&]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { + return VersionBitsConditionChecker(pos).GetStateStatisticsFor(pindex, params, m_caches[pos], signalling_blocks); + }); } -int VersionBitsCache::StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) +int VersionBitsCache::StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, const KeepStates& keep) { LOCK(m_mutex); - return VersionBitsConditionChecker(pos).GetStateSinceHeightFor(pindexPrev, params, m_caches[pos]); + return Tentatively(keep, [&]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { + return VersionBitsConditionChecker(pos).GetStateSinceHeightFor(pindexPrev, params, m_caches[pos]); + }); } uint32_t VersionBitsCache::Mask(const Consensus::Params& params, Consensus::DeploymentPos pos) @@ -300,20 +333,22 @@ uint32_t VersionBitsCache::Mask(const Consensus::Params& params, Consensus::Depl return VersionBitsConditionChecker(pos).Mask(params); } -int32_t VersionBitsCache::ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) +int32_t VersionBitsCache::ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params, const KeepStates& keep) { LOCK(m_mutex); - int32_t nVersion = VERSIONBITS_TOP_BITS; - - for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) { - Consensus::DeploymentPos pos = static_cast(i); - ThresholdState state = VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, m_caches[pos]); - if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) { - nVersion |= Mask(params, pos); + return Tentatively(keep, [&]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { + int32_t nVersion = VERSIONBITS_TOP_BITS; + + for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) { + Consensus::DeploymentPos pos = static_cast(i); + ThresholdState state = VersionBitsConditionChecker(pos).GetStateFor(pindexPrev, params, m_caches[pos]); + if (state == ThresholdState::LOCKED_IN || state == ThresholdState::STARTED) { + nVersion |= Mask(params, pos); + } } - } - return nVersion; + return nVersion; + }); } void VersionBitsCache::Clear() diff --git a/src/versionbits.h b/src/versionbits.h index 8d4881d1dc92..2f47d5d434e4 100644 --- a/src/versionbits.h +++ b/src/versionbits.h @@ -10,7 +10,9 @@ #include #include +#include #include +#include #include /** What block version to use for new blocks (pre versionbits) */ @@ -88,24 +90,34 @@ class VersionBitsCache ThresholdConditionCache m_caches[Consensus::MAX_VERSION_BITS_DEPLOYMENTS] GUARDED_BY(m_mutex); public: + /** Decides, once a computation is done and with this cache still locked, + * whether the states it added may stay. If not, they are dropped before + * any other reader can see them, as they are when the computation throws. + * Without it, every state stays. */ + using KeepStates = std::function; + /** Get the numerical statistics for a given deployment for the signalling period that includes pindex. * If provided, signalling_blocks is set to true/false based on whether each block in the period signalled */ - BIP9Stats Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, std::vector* signalling_blocks = nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); + BIP9Stats Statistics(const CBlockIndex* pindex, const Consensus::Params& params, Consensus::DeploymentPos pos, std::vector* signalling_blocks = nullptr, const KeepStates& keep = {}) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); static uint32_t Mask(const Consensus::Params& params, Consensus::DeploymentPos pos); /** Get the BIP9 state for a given deployment for the block after pindexPrev. */ - ThresholdState State(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); + ThresholdState State(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, const KeepStates& keep = {}) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); /** Get the block height at which the BIP9 deployment switched into the state for the block after pindexPrev. */ - int StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); + int StateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, const KeepStates& keep = {}) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); /** Determine what nVersion a new block should use */ - int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); + int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params, const KeepStates& keep = {}) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex); + +private: + template + std::invoke_result_t Tentatively(const KeepStates& keep, F&& compute) EXCLUSIVE_LOCKS_REQUIRED(m_mutex); }; class AbstractEHFManager From 6ebc01cd488f4b5d666546c65c8e59c5dfedbae1 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 15 Oct 2026 01:29:04 -0500 Subject: [PATCH 02/62] fix(evo): bind non-active paths and dispatcher boundaries explicitly Evo accesses resolved their view from an open transaction or, failing that, the active chainstate. Work for the background chainstate outside a transaction, and work handed to another thread, silently used the active (snapshot) view instead. ForceSignalDBUpdate, for one, opened a NORMAL transaction at the active snapshot tip and flushed the NORMAL root. Every Chainstate method that reads Evo state (ActivateBestChain, ConnectTip, DisconnectTip, ReplayBlocks, LoadChainTip, RollforwardBlock, FlushStateToDisk, InvalidateBlock, EnforceBlock), TestBlockValidity, VerifyDB and the per-chainstate startup loops now bind that chainstate's view. ForceSignalDBUpdate takes the intended chainstate's view and uses its identity for the transaction and the root commit. Signals that view cannot rebuild (through RebuildSignals(), the startup-only rebuild of dashpay/dash#8098) are left unavailable when it is a snapshot view, so startup can still reach the promotion of a validated snapshot; NORMAL, which lacks history only when it was pruned, still fails startup, as does a body that cannot be read. ReplayBlocks runs that rebuild only for NORMAL, the one view a datadir from before v22 can have left in the old format. DMN repair binds NORMAL and takes its block range from NORMAL's chain: `evodb verify` and `evodb repair` default to it, resolve a height in it and refuse a block outside it, and the startup repair stops at its tip. Until promotion, NORMAL's records end at the background tip, even after background validation completes, so a range ending at the active snapshot tip would ask NORMAL to verify records it does not hold. Active-chain dispatchers bind the active chainstate's view per operation unless the thread is already bound, with a single view too, so a turn that a snapshot publication overtakes finishes in the view it started in. While a snapshot generation is live, the view is read under cs_main, together with the active tip where the turn needs one (ActiveEvoViewScope::Tip()), so a turn never pairs one chainstate's view with another's tip. With a single view there is nothing to pair, and a turn that needs no tip binds without waiting for cs_main. The dispatchers are: RPC execution, each peer's message-handler turn as two operations (receiving its queued GETDATA requests and its next message, then its sends, so a view change between them can reach the sends), the miner, mempool admission, Evo-reading interfaces calls, each node-scheduler task and each ChainLock, DKG and InstantSend work round. A failing work round, the LLMQ signing loops' and each DKG phase handler's included, is logged once per operation, view generation and reason, and its recovery once the operation has gone a minute without failing. A local Evo state error in a message handler drops that message, like any exception there, without punishing the peer; one from the peer's queued GETDATA requests ends receiving for that turn. Neither ends the message-handler thread, and the peer's sends (including its discouragement and ping timeout) still run. GETDATA requests leave the queue before they are served, so a failed lookup neither serves earlier requests again nor keeps the peer's later messages waiting; it is answered with NOTFOUND together with the requests found missing before it, and the requests after it are served on the next turn. The node scheduler and REST start before the block databases load, and a load retry replaces the Evo database, so they bind only to the one startup publishes once loading is final (and withdraws before destroying it, after they have stopped); until then their work runs unbound. RPC is held off by its warm-up until then. A chainstate load retry first lets the validation events the failed attempt queued run, since they are bound to the databases it then releases. Queued validation events and LLMQ worker-pool tasks capture the enqueuing thread's binding and reinstall it when they run; a task bound to a retired generation, or whose binding cannot be installed, is dropped, and what its enqueuer claimed for it is released. A local Evo state error in one subscriber to a queued event stays with that subscriber, and the others still receive the event; synchronous signals still pass it on to their caller. Either way the subscriber's registration count stays right, so it can still be unregistered. Every GUI- and wallet-facing interface operation that reads Evo state (the EVO provider operations, Evo, governance and LLMQ reads, isV24Active and listMNCollaterials) binds the active view and contains evo::LocalStateError at the interface boundary: it logs once per operation and generation, sets the misc warning, and reports failure through the operation's own channel. Operations without one now return std::optional (or, for GovernanceInfo, an optional fundingthreshold), and their Qt and wallet consumers keep their current data, show that the masternode state is unavailable, or refuse the action, instead of treating it as data. getPlatformQuorum runs Q's lookup in the bound view as well, and answers UNAVAILABLE when it cannot, or when a snapshot was published after it bound its view. While the masternode list is unavailable, the wallet keeps outputs it cannot classify out of automatic coin selection, CoinJoin's included, and classifies them again on the next block. A block builds its wallet batch only for that work or for a block it scans. An automatic outbound round reads the tip masternode list only when a connected masternode has to be skipped, so a node that lost its peers while the list is unavailable can still connect. A recovered signature whose quorum cannot be checked is dropped on its own, without blaming its peer, and the rest of its batch is still verified. During dual operation a quorum based at or below the snapshot base is in history the snapshot view does not have, and selecting it throws a local Evo state error. That error escaped BuildVerificationBatch, ended the work round, and dropped every lock FetchPendingLocks had already taken off the queue, so one such lock cost up to 31 others. Catch it per lock instead. The lock is left out of the batch and of the results: it cannot be verified in this run, and its peer is not to blame. The catch covers any local Evo state error from quorum selection, such as a rotating-quorum scan that fails before a signing quorum is chosen; a quorum below the snapshot base is the case that prompted it. GUI models poll the wrapped operations, and every failed poll set the misc warning again and notified the GUI. Raise it together with the log line, through the new WarnLocalEvoStateUnavailable(), once per operation and active Evo view. On a node without a snapshot it says that block data was pruned and suggests -reindex when block data is what is missing; for any other cause it names neither pruning nor a snapshot. getPlatformQuorum runs through WithActiveEvoView, so the typed scan error becomes UNAVAILABLE rather than INVALID, even for a quorum in the part of the window above the base. A quorum mined below the base is a block of the active chain below any later height, so it stays UNAVAILABLE once a window above the base has left it behind, too. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- src/chainlock/handler.cpp | 35 +- src/chainlock/signing.cpp | 3 + src/evo/deterministicmns.cpp | 11 +- src/evo/evodb.cpp | 78 +++ src/evo/evodb.h | 153 ++++ src/evo/mnhftx.cpp | 26 +- src/evo/mnhftx.h | 7 +- src/init.cpp | 297 ++++---- src/init.h | 17 + src/instantsend/net_instantsend.cpp | 25 +- src/interfaces/chain.h | 11 +- src/interfaces/node.h | 39 +- src/interfaces/providertx.h | 6 +- src/interfaces/wallet.h | 4 +- src/llmq/net_dkg.cpp | 27 +- src/llmq/net_quorum.cpp | 37 +- src/llmq/net_signing.cpp | 115 +-- src/llmq/quorumsman.h | 2 + src/llmq/signing.cpp | 35 +- src/llmq/signing.h | 4 + src/net.cpp | 59 +- src/net.h | 16 +- src/net_processing.cpp | 42 +- src/node/chainstate.cpp | 4 +- src/node/context.h | 5 + src/node/interfaces.cpp | 662 ++++++++++++------ src/node/miner.cpp | 1 + src/qt/bitcoingui.cpp | 4 +- src/qt/clientfeeds.cpp | 36 +- src/qt/masternodedialogs.cpp | 12 - src/qt/masternodedialogs.h | 8 +- src/qt/masternodelist.cpp | 37 +- src/qt/masternodelist.h | 4 + src/qt/masternodewidgets.cpp | 5 + src/qt/masternodewidgets.h | 3 + src/qt/masternodewizard.cpp | 81 ++- src/qt/proposallist.cpp | 15 +- src/qt/proposalmodel.cpp | 22 +- src/qt/proposalmodel.h | 21 +- src/qt/sharedmncreatedialog.cpp | 30 +- src/qt/sharedmncreatedialog.h | 2 +- src/qt/sharedmndialogs.cpp | 10 +- src/qt/sharedmndialogs.h | 4 +- src/qt/sharedmnwidgets.cpp | 7 +- src/qt/sharedmnwidgets.h | 2 +- src/qt/test/masternodewidgettests.cpp | 35 +- src/qt/test/sharedmnwalkthroughtests.cpp | 2 +- src/rest.cpp | 15 +- src/rpc/evo.cpp | 38 +- src/rpc/server.cpp | 5 + src/scheduler.cpp | 6 +- src/scheduler.h | 15 + src/test/denialofservice_tests.cpp | 35 + src/test/evo_db_tests.cpp | 162 +++++ src/test/interfaces_tests.cpp | 198 +++++- src/test/scheduler_tests.cpp | 28 + src/test/util/net.h | 3 + src/test/validation_chainstate_tests.cpp | 85 ++- .../validation_chainstatemanager_tests.cpp | 384 ++++++++++ src/test/validationinterface_tests.cpp | 71 ++ src/validation.cpp | 37 +- src/validation.h | 26 + src/validationinterface.cpp | 42 +- src/wallet/coinjoin.cpp | 6 +- src/wallet/interfaces.cpp | 2 +- src/wallet/rpc/spend.cpp | 6 +- src/wallet/spend.cpp | 3 +- src/wallet/test/wallet_tests.cpp | 97 +++ src/wallet/wallet.cpp | 52 +- src/wallet/wallet.h | 14 +- 70 files changed, 2730 insertions(+), 661 deletions(-) diff --git a/src/chainlock/handler.cpp b/src/chainlock/handler.cpp index cadce2a74dc8..8f431a795951 100644 --- a/src/chainlock/handler.cpp +++ b/src/chainlock/handler.cpp @@ -53,6 +53,9 @@ ChainlockHandler::ChainlockHandler(chainlock::Chainlocks& chainlocks, Chainstate std::make_unique(std::thread(util::TraceThread, "cl-schdlr", [&] { scheduler->serviceQueue(); }))}, seenChainLocks{SEEN_CHAINLOCKS_CUTOFF_SIZE, SEEN_CHAINLOCKS_MAX_SIZE} { + // Tasks are scheduled only from Start(), after this is set. + scheduler->SetTaskWrapper( + [this](const CScheduler::Function& task) { RunActiveEvoRound(m_chainman.EvoDb(), "cl-schdlr", task); }); } ChainlockHandler::~ChainlockHandler() @@ -174,12 +177,11 @@ MessageProcessingResult ChainlockHandler::ProcessNewChainLock(const NodeId from, if (!m_chainlocks.UpdateBestChainlock(hash, clsig, pindex)) return {}; if (pindex) { - scheduler->scheduleFromNow( - [&]() { - CheckActiveState(); - EnforceBestChainLock(); - }, - std::chrono::seconds{0}); + scheduler->scheduleFromNow(WithCapturedEvoView([&]() { + CheckActiveState(); + EnforceBestChainLock(); + }), + std::chrono::seconds{0}); LogPrint(BCLog::CHAINLOCKS, "ChainlockHandler::%s -- processed new CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from); @@ -201,14 +203,19 @@ void ChainlockHandler::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBloc // atomic[If tryLockChainTipScheduled is false, do (set it to true] and schedule signing). if (bool expected = false; tryLockChainTipScheduled.compare_exchange_strong(expected, true)) { - scheduler->scheduleFromNow( - [&]() { - CheckActiveState(); - EnforceBestChainLock(); - Cleanup(); - tryLockChainTipScheduled = false; - }, - std::chrono::seconds{0}); + const auto unschedule{[this] { tryLockChainTipScheduled = false; }}; + scheduler->scheduleFromNow(WithCapturedEvoView( + [&, unschedule]() { + const struct Unschedule { + decltype(unschedule) f; + ~Unschedule() { f(); } + } done{unschedule}; + CheckActiveState(); + EnforceBestChainLock(); + Cleanup(); + }, + unschedule), + std::chrono::seconds{0}); } } diff --git a/src/chainlock/signing.cpp b/src/chainlock/signing.cpp index ba1802ad452b..0e96d53e2111 100644 --- a/src/chainlock/signing.cpp +++ b/src/chainlock/signing.cpp @@ -36,6 +36,9 @@ ChainLockSigner::ChainLockSigner(const ChainstateManager& chainman, const chainl m_scheduler_thread{ std::make_unique(std::thread(util::TraceThread, "cls-schdlr", [&] { m_scheduler->serviceQueue(); }))} { + // Tasks are scheduled only from Start(), after this is set. + m_scheduler->SetTaskWrapper( + [this](const CScheduler::Function& task) { RunActiveEvoRound(m_chainman.EvoDb(), "cls-schdlr", task); }); } ChainLockSigner::~ChainLockSigner() { Stop(); } diff --git a/src/evo/deterministicmns.cpp b/src/evo/deterministicmns.cpp index 2193e1a32b8e..032cb576be1b 100644 --- a/src/evo/deterministicmns.cpp +++ b/src/evo/deterministicmns.cpp @@ -1288,6 +1288,8 @@ bool CDeterministicMNManager::MigrateLegacyDiffs(const CBlockIndex* const tip_in CDeterministicMNManager::RecalcDiffsResult CDeterministicMNManager::RecalculateAndRepairDiffs( const node::BlockManager& blockman, const CBlockIndex* start_index, const CBlockIndex* stop_index, BuildListFromBlockFunc build_list_func, bool repair) { + // Verification and repair are NORMAL-only lifecycle operations. + const EvoViewScope evo_view{m_evoDb.ViewFor(EvoDbIdentity::NORMAL)}; RecalcDiffsResult result; result.start_height = start_index->nHeight; result.stop_height = stop_index->nHeight; @@ -1396,11 +1398,18 @@ CDeterministicMNManager::RecalcDiffsResult CDeterministicMNManager::RecalculateA return result; } -bool CDeterministicMNManager::IsRepaired() const { return m_evoDb.Exists(DB_LIST_REPAIRED); } +bool CDeterministicMNManager::IsRepaired() const +{ + // Repair is a NORMAL-only lifecycle operation. + const EvoViewScope evo_view{m_evoDb.ViewFor(EvoDbIdentity::NORMAL)}; + return m_evoDb.Exists(DB_LIST_REPAIRED); +} void CDeterministicMNManager::CompleteRepair() { AssertLockHeld(::cs_main); + // Repair is a NORMAL-only lifecycle operation. + const EvoViewScope evo_view{m_evoDb.ViewFor(EvoDbIdentity::NORMAL)}; auto dbTx = m_evoDb.BeginTransaction(); m_evoDb.Write(DB_LIST_REPAIRED, 1); dbTx->Commit(); diff --git a/src/evo/evodb.cpp b/src/evo/evodb.cpp index b91d2cd03d43..1c43570c8652 100644 --- a/src/evo/evodb.cpp +++ b/src/evo/evodb.cpp @@ -8,10 +8,14 @@ #include #include #include +#include #include +#include +#include #include #include +#include CEvoDBScopedCommitter::CEvoDBScopedCommitter(CEvoDB& _evoDB, EvoDbIdentity identity) : evoDB{_evoDB}, @@ -113,6 +117,77 @@ const CEvoDB::TransactionContext& CEvoDB::GetContext(EvoDbIdentity identity) con return *transaction_contexts.at(identity); } +namespace { +//! How long an operation's rounds must go without failing before it counts as +//! recovered. One operation can stand for many tasks (every scheduler task is +//! "scheduler"), and one of them failing between the others' successes is not +//! a recovery. +constexpr std::chrono::seconds EVO_ROUND_RECOVERY_QUIET{60}; + +//! Causes logged per failing operation, beyond which the oldest are forgotten. +constexpr size_t MAX_LOGGED_EVO_ROUND_CAUSES{32}; + +struct FailingEvoRound { + //! The (view generation, reason) pairs logged, oldest first. + std::vector, std::string>> causes; + std::chrono::seconds last_failure; +}; +GlobalMutex g_evo_round_mutex; +std::map> g_failing_evo_rounds GUARDED_BY(g_evo_round_mutex); +std::atomic g_evo_rounds_failing{false}; +} // namespace + +void LogEvoRoundFailure(std::string_view what, std::optional generation, std::string_view reason) +{ + const auto now{GetTime()}; + LOCK(g_evo_round_mutex); + FailingEvoRound& failing{g_failing_evo_rounds[std::string{what}]}; + failing.last_failure = now; + const std::pair, std::string> cause{generation, reason}; + if (std::ranges::find(failing.causes, cause) != failing.causes.end()) return; + if (failing.causes.size() == MAX_LOGGED_EVO_ROUND_CAUSES) failing.causes.erase(failing.causes.begin()); + failing.causes.push_back(cause); + g_evo_rounds_failing = true; + LogPrintf("ERROR: %s: Evo state unavailable: %s. Repeats are not logged until the cause changes or %s recovers.\n", + what, reason, what); +} + +void LogEvoRoundRecovery(std::string_view what) +{ + if (!g_evo_rounds_failing.load(std::memory_order_relaxed)) return; + const auto now{GetTime()}; + LOCK(g_evo_round_mutex); + const auto it{g_failing_evo_rounds.find(what)}; + if (it == g_failing_evo_rounds.end() || now - it->second.last_failure < EVO_ROUND_RECOVERY_QUIET) return; + g_failing_evo_rounds.erase(it); + g_evo_rounds_failing = !g_failing_evo_rounds.empty(); + LogPrintf("%s: Evo state available again\n", what); +} + +bool CEvoDB::IsBound() const +{ + LOCK(cs); + return HoldsTransaction() || EvoViewScope::Innermost(*this) != nullptr; +} + +void CEvoDB::UpdateLiveGeneration() +{ + m_has_live_generation = m_snapshot_generation && (m_snapshot_generation->state == EvoGenerationState::PUBLISHED || + m_snapshot_generation->state == EvoGenerationState::PROMOTING); +} + +EvoViewToken CEvoDB::ActiveView() const +{ + LOCK(cs); + return MakeView(m_default_identity); +} + +bool CEvoDB::IsLive(const EvoViewToken& view) const +{ + LOCK(cs); + return IsLiveLocked(view); +} + bool CEvoDB::IsLiveLocked(const EvoViewToken& view) const { if (view.db != this) return false; @@ -284,6 +359,7 @@ void CEvoDB::BindSnapshotGeneration(std::optional record) transaction_contexts.erase(it); } m_snapshot_generation = std::move(record); + UpdateLiveGeneration(); SetDefaultIdentityLocked(m_snapshot_generation ? m_default_identity : EvoDbIdentity::NORMAL); } @@ -344,6 +420,7 @@ bool CEvoDB::PublishSnapshotGeneration(const std::optional& base_mn_lis if (base_mn_list_hash) batch.Write(EVODB_SNAPSHOT_MNLIST_HASH, *base_mn_list_hash); if (!db->WriteBatch(batch, /*fSync=*/true)) return false; m_snapshot_generation = record; + UpdateLiveGeneration(); return true; } @@ -561,6 +638,7 @@ bool CEvoDB::PrepareSnapshotPromotion(const uint256& snapshot_tip) batch.Write(GenerationRecordKey(record.generation), record); if (!db->WriteBatch(batch, /*fSync=*/true)) return false; m_snapshot_generation = record; + UpdateLiveGeneration(); return true; } diff --git a/src/evo/evodb.h b/src/evo/evodb.h index 4bafd962e96d..f7fbce474099 100644 --- a/src/evo/evodb.h +++ b/src/evo/evodb.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -20,6 +21,8 @@ #include #include #include +#include +#include #include #include @@ -412,6 +415,16 @@ class CEvoDB LOCK(cs); return GetCurrentIdentity() == m_default_identity; } + //! Whether this thread already binds its accesses to this CEvoDB, through + //! an open transaction or an EvoViewScope. + bool IsBound() const EXCLUSIVE_LOCKS_REQUIRED(!cs); + //! Whether a published snapshot generation is live, so that two views exist. + bool HasLiveGeneration() const { return m_has_live_generation.load(); } + //! The view of the active chainstate. + EvoViewToken ActiveView() const EXCLUSIVE_LOCKS_REQUIRED(!cs); + //! Whether `view` still names a view of this CEvoDB: NORMAL, or the snapshot + //! generation bound now, whether or not it is published yet. + bool IsLive(const EvoViewToken& view) const EXCLUSIVE_LOCKS_REQUIRED(!cs); CurTransaction& GetCurTransaction() EXCLUSIVE_LOCKS_REQUIRED(cs) { @@ -668,6 +681,7 @@ class CEvoDB } void BindSnapshotGeneration(std::optional record) EXCLUSIVE_LOCKS_REQUIRED(cs); + void UpdateLiveGeneration() EXCLUSIVE_LOCKS_REQUIRED(cs); //! Whether no transaction is open and every transaction tree is committed. bool TransactionsClean() const EXCLUSIVE_LOCKS_REQUIRED(cs); bool CollectGeneration(uint32_t generation, bool erase_record) EXCLUSIVE_LOCKS_REQUIRED(cs); @@ -677,6 +691,7 @@ class CEvoDB bool DiscardBoundGeneration() EXCLUSIVE_LOCKS_REQUIRED(cs); static inline std::atomic g_view_cache_epoch{0}; + std::atomic m_has_live_generation{false}; //! The live generation the SNAPSHOT identity reads and writes. std::optional m_snapshot_generation GUARDED_BY(cs); @@ -684,4 +699,142 @@ class CEvoDB size_t m_merge_batch_size GUARDED_BY(cs){10000}; }; +class CBlockIndex; + +/** Binds one active-chain dispatch turn (an RPC call, a P2P message handler + * turn, an interfaces call, a service work round) to the active chainstate's + * Evo view for its duration, unless the thread is already bound (a captured + * background token, an open transaction). It binds with a single view too, + * so a turn that a snapshot publication overtakes finishes in the view it + * started in. + * + * While a snapshot generation is live, the view is read under cs_main, where + * the active chainstate and its view change together; with a single view + * there is nothing to pair it with, so the turn does not wait for cs_main. + * `active_tip`, if given, is always read under cs_main with the view, so + * Tip() is the tip of the chainstate the bound view belongs to. Readers in + * the turn that need the active tip use Tip(), not a later look at the + * active chainstate. */ +class ActiveEvoViewScope +{ +public: + explicit ActiveEvoViewScope(const CEvoDB* evodb) + { + if (evodb == nullptr || evodb->IsBound()) return; + if (!evodb->HasLiveGeneration()) { + m_scope.emplace(evodb->ActiveView()); + return; + } + LOCK(::cs_main); + m_scope.emplace(evodb->ActiveView()); + } + + template + ActiveEvoViewScope(const CEvoDB* evodb, TipFn&& active_tip) + { + if (evodb == nullptr) return; + LOCK(::cs_main); + m_tip = active_tip(); + if (!evodb->IsBound()) m_scope.emplace(evodb->ActiveView()); + } + + //! The active tip read with the bound view, if the scope was given a way + //! to read it. + const CBlockIndex* Tip() const { return m_tip; } + +private: + const CBlockIndex* m_tip{nullptr}; + std::optional m_scope; +}; + +//! Log a failed round of `what` unless a failure with the same view generation +//! and reason was logged for it since it last recovered. +void LogEvoRoundFailure(std::string_view what, std::optional generation, std::string_view reason); +//! Log that rounds of `what` succeed again, once they have not failed for a +//! while after a logged failure. +void LogEvoRoundRecovery(std::string_view what); + +//! Run one round of active-chain service work bound to the active view, and +//! return whether it completed. A local Evo state error ends the round, never +//! the thread. +template +bool RunActiveEvoRound(const CEvoDB* evodb, std::string_view what, F&& round) +{ + std::optional generation; + try { + const ActiveEvoViewScope evo_view{evodb}; + if (const auto view{EvoViewScope::InnermostAny()}) generation = view->generation; + round(); + } catch (const evo::LocalStateError& e) { + LogEvoRoundFailure(what, generation, e.what()); + return false; + } + LogEvoRoundRecovery(what); + return true; +} + +/** The Evo view binding of a task handed to another thread: captured from the + * enqueuing thread's innermost scope and reinstalled when the task runs, so + * the executing thread's own binding never replaces it. A task whose + * snapshot generation was retired in between is dropped. */ +class EvoViewCapture +{ +public: + EvoViewCapture() : + m_view{EvoViewScope::InnermostAny()} + { + } + + enum class Outcome { + RAN, //!< the task ran to completion + FAILED, //!< the task started and ended in a local Evo state error + DROPPED, //!< the task never started + }; + + //! Run `task` under the captured binding. A task whose generation was + //! retired, or whose binding cannot be installed, is dropped. + template + Outcome Run(F&& task) const + { + std::optional scope; + if (m_view) { + if (!m_view->db->IsLive(*m_view)) { + LogPrint(BCLog::VALIDATION, "Dropping a task bound to retired snapshot generation %u\n", + m_view->generation); + return Outcome::DROPPED; + } + try { + scope.emplace(*m_view); + } catch (const evo::LocalStateError& e) { + LogPrintf("ERROR: dropping a queued task: %s\n", e.what()); + return Outcome::DROPPED; + } + } + try { + task(); + } catch (const evo::LocalStateError& e) { + LogPrintf("ERROR: Evo state unavailable to a queued task: %s\n", e.what()); + return Outcome::FAILED; + } + return Outcome::RAN; + } + +private: + std::optional m_view; +}; + +//! Wrap `task` so that it runs under the calling thread's current Evo view +//! binding wherever it is eventually executed. `on_drop` releases whatever +//! the enqueuer claimed for the task when it is dropped without starting; a +//! task that started releases its claims itself. +template +auto WithCapturedEvoView(F task, D on_drop = [] {}) +{ + return [task = std::move(task), on_drop = std::move(on_drop), evo_view = EvoViewCapture{}](auto&&... args) mutable { + if (evo_view.Run([&] { task(std::forward(args)...); }) == EvoViewCapture::Outcome::DROPPED) { + on_drop(); + } + }; +} + #endif // BITCOIN_EVO_EVODB_H diff --git a/src/evo/mnhftx.cpp b/src/evo/mnhftx.cpp index c6f3a62a359e..d37b525492d7 100644 --- a/src/evo/mnhftx.cpp +++ b/src/evo/mnhftx.cpp @@ -410,16 +410,34 @@ void CMNHFManager::AddToCache(const Signals& signals, const CBlockIndex* const p mnhfCache.For(view).insert(blockHash, signals); } -bool CMNHFManager::ForceSignalDBUpdate(const CBlockIndex* tip) +bool CMNHFManager::ForceSignalDBUpdate(const EvoViewToken& view, const CBlockIndex* tip) { + const EvoViewScope evo_view{view}; // force ehf signals db update - auto dbTx = m_evoDb.BeginTransaction(); + auto dbTx = m_evoDb.BeginTransaction(view.identity); - RebuildSignals(tip); + try { + RebuildSignals(tip); + } catch (const evo::LocalStateError& e) { + // History a snapshot view lacks must not keep startup from, say, + // promoting a validated snapshot, which is what makes it readable; + // until then, lookups report the signals it could not rebuild as + // unavailable. NORMAL lacks no history unless it was pruned, and no + // view can do without a body it has but cannot read. + if (view.identity == EvoDbIdentity::SNAPSHOT && !dynamic_cast(&e)) { + LogPrintf("CMNHFManager::%s -- skipping the EHF signal update: %s\n", __func__, e.what()); + return true; + } + const bool missing_data{dynamic_cast(&e) || + dynamic_cast(&e)}; + LogPrintf("CMNHFManager::%s -- cannot rebuild the EHF signals at block %s: %s%s\n", __func__, + tip->GetBlockHash().ToString(), e.what(), missing_data ? ". Restart with -reindex." : ""); + return false; + } dbTx->Commit(); // flush it to disk - if (!m_evoDb.CommitRootTransaction()) { + if (!m_evoDb.CommitRootTransaction(view.identity)) { LogPrintf("CMNHFManager::%s -- failed to commit to evoDB\n", __func__); return false; } diff --git a/src/evo/mnhftx.h b/src/evo/mnhftx.h index c883a21e1c83..408e522d04bf 100644 --- a/src/evo/mnhftx.h +++ b/src/evo/mnhftx.h @@ -141,7 +141,12 @@ class CMNHFManager : public AbstractEHFManager // from outside must check that it is valid first. Signals GetSignalsStage(const CBlockIndex* const pindexPrev) override EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); - bool ForceSignalDBUpdate(const CBlockIndex* tip) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache); + //! Recompute and persist the signals at `tip` under `view`, the view of + //! the chainstate whose tip it is. Signals a snapshot view lacks the + //! history for are left unavailable; failing to rebuild them for NORMAL, + //! or to read a block body, fails. + bool ForceSignalDBUpdate(const EvoViewToken& view, const CBlockIndex* tip) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_cache); /** * Recompute missing state from block data, walking back from pindex to the first block whose diff --git a/src/init.cpp b/src/init.cpp index b95c0e631b54..fdfbf064c51a 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -483,6 +483,7 @@ void PrepareShutdown(NodeContext& node) node.llmq_ctx.reset(); node.isman.reset(); node.dmnman.reset(); + node.evodb_for_dispatch = nullptr; node.evodb.reset(); } for (const auto& client : node.chain_clients) { @@ -1524,6 +1525,144 @@ bool AppInitInterfaces(NodeContext& node) return true; } +void ReleaseChainstateLoadAttempt(NodeContext& node) +{ + // Validation events a failed attempt queued carry Evo view bindings to the + // databases released below, so they run first. + SyncWithValidationInterfaceQueue(); + node.mempool.reset(); + node.special_tx.reset(); + node.llmq_ctx.reset(); + node.isman.reset(); + node.dmnman.reset(); + node.evodb.reset(); +} + +void RunSchedulerTask(const NodeContext& node, const std::function& task) +{ + RunActiveEvoRound(node.evodb_for_dispatch.load(), "scheduler", task); +} + +// The repair marker shares the EvoDB root transaction with the blocks connected during the +// import, so persist it with a full flush that writes the coins DB first. +static void CompleteEvoDbRepair(NodeContext& node) +{ + LOCK(::cs_main); + node.dmnman->CompleteRepair(); + for (Chainstate* chainstate : node.chainman->GetAll()) { + if (chainstate->CanFlushToDisk()) { + chainstate->ForceFlushStateToDisk(); + } + } +} + +void FinishImportedStartup(NodeContext& node, const ArgsManager& args, bool skip_evodb_repair_on_reindex) +{ + // The startup tail serves the active chain, like any other dispatch. + const ActiveEvoViewScope evo_view{node.evodb.get(), + [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return node.chainman->ActiveTip(); }}; + + { + const CBlockIndex* tip{evo_view.Tip()}; + const bool ibd = node.chainman->IsInitialBlockDownload(); + if (node.active_ctx) { + // On masternodes, defer the full broadcast until after + // nodeman->Init() so that GetProTxHash() is available + // for quorum connection setup and skShare derivation. + // Only kick CDSNotificationInterface here (cached block + // height for DS/MN payments/budgets). + node.ds_notification_interface->InitializeCurrentBlockTip(tip, ibd); + } else { + // Non-masternode nodes (including observer-only): broadcast + // to all subscribers now; no proTxHash dependency. + GetMainSignals().InitializeCurrentBlockTip(tip, ibd); + } + } + + // Seed InstantSend tip-height cache; NetInstantSend receives future + // updates via CValidationInterface but misses InitializeCurrentBlockTip. + // TODO: move cache updates from NetInstantSend to g_ds_notification due to specific of Tip's processing + node.isman->CacheTipHeight(WITH_LOCK(::cs_main, return node.chainman->ActiveChain().Tip())); + + if (skip_evodb_repair_on_reindex) { + LogPrintf("Skipping evodb repair during reindex\n"); + CompleteEvoDbRepair(node); // Mark as repaired since we're rebuilding fresh + } else if (node.dmnman->IsRepaired() && !args.GetBoolArg("-forceevodbrepair", false)) { + LogPrintf("Masternode list diffs are already repaired\n"); + } else { + const CBlockIndex* start_index; + const CBlockIndex* stop_index; + { + LOCK(cs_main); + const auto& consensus_params = Params().GetConsensus(); + const CChain& chain{node.chainman->NormalEvoChain()}; + start_index = chain[consensus_params.DIP0003Height]; + stop_index = chain.Tip(); + } + + if (start_index && stop_index && start_index->nHeight < stop_index->nHeight) { + LogPrintf("Verifying and repairing masternode list diffs...\n"); + const auto start{SteadyClock::now()}; + // Create a callback that wraps CSpecialTxProcessor::BuildNewListFromBlock + auto build_list_func = [&node](const CBlock& block, const CBlockIndex* const pindexPrev, + const CDeterministicMNList& prevList, const CCoinsViewCache& view, + bool debugLogs, BlockValidationState& state, + CDeterministicMNList& mnListRet) -> bool { + const bool is_v24_active{DeploymentActiveAfter(pindexPrev, *node.chainman, Consensus::DEPLOYMENT_V24)}; + return node.special_tx->RebuildListFromBlock(block, pindexPrev, is_v24_active, prevList, view, + debugLogs, state, mnListRet); + }; + auto result = node.dmnman->RecalculateAndRepairDiffs(node.chainman->m_blockman, start_index, stop_index, + build_list_func, true); + + if (!result.verification_errors.empty()) { + LogPrintf("WARNING: Verification errors:\n%s\n", Join(result.verification_errors, "\n")); + } + + if (!result.repair_errors.empty()) { + // Critical errors occurred - reindex required + LogPrintf("Failed to repair masternode list diffs. Database corruption detected. " + "Please restart with -reindex to rebuild the database.\n" + "Errors:\n%s\n", + Join(result.repair_errors, "\n")); + StartShutdown(); + return; + } + CompleteEvoDbRepair(node); + LogPrintf("Successfully repaired %d masternode list diffs, verified %d snapshots in %ds\n", + result.diffs_recalculated, result.snapshots_verified, + Ticks(SteadyClock::now() - start)); + } + } + + { + // Get all UTXOs for each MN collateral in one go so that we can fill coin cache early + // and reduce further locking overhead for cs_main in other parts of code including GUI + LogPrintf("Filling coin cache with masternode UTXOs...\n"); + LOCK(cs_main); + const auto start{SteadyClock::now()}; + const auto mnList{node.dmnman->GetListAtChainTip()}; + mnList.ForEachMN(/*onlyValid=*/false, [&](const auto& dmn) { + Coin coin; + GetUTXOCoin(node.chainman->ActiveChainstate(), dmn.collateralOutpoint, coin); + }); + LogPrintf("Filling coin cache with masternode UTXOs: done in %dms\n", + Ticks(SteadyClock::now() - start)); + } + + if (node.active_ctx) { + node.active_ctx->nodeman->Init(WITH_LOCK(::cs_main, return node.chainman->ActiveTip())); + // Now that nodeman->Init has set proTxHash, fan out the + // startup tip to all CValidationInterface subscribers. + // The earlier call only kicked CDSNotificationInterface + // directly because the full broadcast (NetQuorum, + // ActiveContext) depends on a valid proTxHash. + const CBlockIndex* tip = WITH_LOCK(::cs_main, return node.chainman->ActiveTip()); + const bool ibd = node.chainman->IsInitialBlockDownload(); + GetMainSignals().InitializeCurrentBlockTip(tip, ibd); + } +} + bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) { const ArgsManager& args = *Assert(node.args); @@ -1565,6 +1704,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) assert(!node.scheduler); node.scheduler = std::make_unique(); + // Each scheduled round serves the active chain unless the task carries + // its own Evo view binding. + node.scheduler->SetTaskWrapper([&node](const CScheduler::Function& task) { RunSchedulerTask(node, task); }); // Start the lightweight task scheduler thread node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { node.scheduler->serviceQueue(); }); @@ -2067,12 +2209,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) for (bool fLoaded = false; !fLoaded && !ShutdownRequested();) { // On a retry iteration the previous instances still hold the on-disk // database locks, so release them before opening the databases again. - node.mempool.reset(); - node.special_tx.reset(); - node.llmq_ctx.reset(); - node.isman.reset(); - node.dmnman.reset(); - node.evodb.reset(); + ReleaseChainstateLoadAttempt(node); auto catch_exceptions = [](auto&& f) { try { return f(); @@ -2184,6 +2321,9 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) } } + // No load retry replaces the Evo database from here on. + node.evodb_for_dispatch = node.evodb.get(); + // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. @@ -2516,134 +2656,35 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) chainman.m_thread_load = std::thread(&util::TraceThread, "initload", [=, &args, &chainman, &node] { // ImportBlocks can switch fReindex from true to false, fetch its original state here to use later bool skip_evodb_repair_on_reindex = fReindex || fReindexChainState; - // The repair marker shares the EvoDB root transaction with the blocks connected during the - // import, so persist it with a full flush that writes the coins DB first. - const auto complete_repair = [&] { - LOCK(::cs_main); - node.dmnman->CompleteRepair(); - for (Chainstate* chainstate : chainman.GetAll()) { - if (chainstate->CanFlushToDisk()) { - chainstate->ForceFlushStateToDisk(); - } - } - }; - // Import blocks - ImportBlocks(chainman, vImportFiles); - if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { - LogPrintf("Stopping after block import\n"); - if (skip_evodb_repair_on_reindex) complete_repair(); // Dash: the reindex rebuilt EvoDB - StartShutdown(); - return; - } - - // Start indexes initial sync - if (!StartIndexBackgroundSync(node)) { - bilingual_str err_str = _("Failed to start indexes, shutting down.."); - chainman.GetNotifications().fatalError(err_str.original, err_str); - return; - } - - // Load mempool from disk - if (auto* pool{chainman.ActiveChainstate().GetMempool()}) { - LoadMempool(*pool, ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{}, chainman.ActiveChainstate(), {}); - pool->SetLoadTried(!ShutdownRequested()); - } - - { - const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman.ActiveTip()); - const bool ibd = chainman.IsInitialBlockDownload(); - if (node.active_ctx) { - // On masternodes, defer the full broadcast until after - // nodeman->Init() so that GetProTxHash() is available - // for quorum connection setup and skShare derivation. - // Only kick CDSNotificationInterface here (cached block - // height for DS/MN payments/budgets). - node.ds_notification_interface->InitializeCurrentBlockTip(tip, ibd); - } else { - // Non-masternode nodes (including observer-only): broadcast - // to all subscribers now; no proTxHash dependency. - GetMainSignals().InitializeCurrentBlockTip(tip, ibd); - } - } - - // Seed InstantSend tip-height cache; NetInstantSend receives future - // updates via CValidationInterface but misses InitializeCurrentBlockTip. - // TODO: move cache updates from NetInstantSend to g_ds_notification due to specific of Tip's processing - node.isman->CacheTipHeight(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip())); - - if (skip_evodb_repair_on_reindex) { - LogPrintf("Skipping evodb repair during reindex\n"); - complete_repair(); // Mark as repaired since we're rebuilding fresh - } else if (node.dmnman->IsRepaired() && !args.GetBoolArg("-forceevodbrepair", false)) { - LogPrintf("Masternode list diffs are already repaired\n"); - } else { - const CBlockIndex* start_index; - const CBlockIndex* stop_index; + try { { - LOCK(cs_main); - const auto& consensus_params = Params().GetConsensus(); - start_index = chainman.ActiveChain()[consensus_params.DIP0003Height]; - stop_index = chainman.ActiveChain().Tip(); - } - - if (start_index && stop_index && start_index->nHeight < stop_index->nHeight) { - LogPrintf("Verifying and repairing masternode list diffs...\n"); - const auto start{SteadyClock::now()}; - // Create a callback that wraps CSpecialTxProcessor::BuildNewListFromBlock - auto build_list_func = - [&node, &chainman](const CBlock& block, const CBlockIndex* const pindexPrev, - const CDeterministicMNList& prevList, const CCoinsViewCache& view, bool debugLogs, - BlockValidationState& state, CDeterministicMNList& mnListRet) -> bool { - const bool is_v24_active{DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_V24)}; - return node.special_tx->RebuildListFromBlock(block, pindexPrev, is_v24_active, prevList, - view, debugLogs, state, mnListRet); - }; - auto result = node.dmnman->RecalculateAndRepairDiffs(chainman.m_blockman, start_index, stop_index, build_list_func, true); - - if (!result.verification_errors.empty()) { - LogPrintf("WARNING: Verification errors:\n%s\n", Join(result.verification_errors, "\n")); - } - - if (!result.repair_errors.empty()) { - // Critical errors occurred - reindex required - LogPrintf("Failed to repair masternode list diffs. Database corruption detected. " - "Please restart with -reindex to rebuild the database.\n" - "Errors:\n%s\n", - Join(result.repair_errors, "\n")); + const ActiveEvoViewScope evo_view{node.evodb.get()}; + // Import blocks + ImportBlocks(chainman, vImportFiles); + if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { + LogPrintf("Stopping after block import\n"); + if (skip_evodb_repair_on_reindex) CompleteEvoDbRepair(node); // Dash: the reindex rebuilt EvoDB StartShutdown(); return; } - complete_repair(); - LogPrintf("Successfully repaired %d masternode list diffs, verified %d snapshots in %ds\n", - result.diffs_recalculated, result.snapshots_verified, - Ticks(SteadyClock::now() - start)); - } - } - { - // Get all UTXOs for each MN collateral in one go so that we can fill coin cache early - // and reduce further locking overhead for cs_main in other parts of code including GUI - LogPrintf("Filling coin cache with masternode UTXOs...\n"); - LOCK(cs_main); - const auto start{SteadyClock::now()}; - const auto mnList{node.dmnman->GetListAtChainTip()}; - mnList.ForEachMN(/*onlyValid=*/false, [&](const auto& dmn) { - Coin coin; - GetUTXOCoin(chainman.ActiveChainstate(), dmn.collateralOutpoint, coin); - }); - LogPrintf("Filling coin cache with masternode UTXOs: done in %dms\n", Ticks(SteadyClock::now() - start)); - } + // Start indexes initial sync + if (!StartIndexBackgroundSync(node)) { + bilingual_str err_str = _("Failed to start indexes, shutting down.."); + chainman.GetNotifications().fatalError(err_str.original, err_str); + return; + } - if (node.active_ctx) { - node.active_ctx->nodeman->Init(WITH_LOCK(::cs_main, return chainman.ActiveTip())); - // Now that nodeman->Init has set proTxHash, fan out the - // startup tip to all CValidationInterface subscribers. - // The earlier call only kicked CDSNotificationInterface - // directly because the full broadcast (NetQuorum, - // ActiveContext) depends on a valid proTxHash. - const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman.ActiveTip()); - const bool ibd = chainman.IsInitialBlockDownload(); - GetMainSignals().InitializeCurrentBlockTip(tip, ibd); + // Load mempool from disk + if (auto* pool{chainman.ActiveChainstate().GetMempool()}) { + LoadMempool(*pool, ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{}, chainman.ActiveChainstate(), {}); + pool->SetLoadTried(!ShutdownRequested()); + } + } + FinishImportedStartup(node, args, skip_evodb_repair_on_reindex); + } catch (const evo::LocalStateError& e) { + LogPrintf("ERROR: Evo state unavailable during startup: %s\n", e.what()); + StartShutdown(); } }); #ifdef ENABLE_WALLET diff --git a/src/init.h b/src/init.h index eace57ae260d..44c01cd1a0b5 100644 --- a/src/init.h +++ b/src/init.h @@ -9,6 +9,7 @@ #include #include +#include //! Default value for -daemon option static constexpr bool DEFAULT_DAEMON = false; @@ -67,6 +68,22 @@ bool AppInitInterfaces(node::NodeContext& node); * @pre Parameters should be parsed and config file should be read, AppInitLockDataDirectory should have been called. */ bool AppInitMain(node::NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info = nullptr); +/** + * Startup work that follows the initial block import: announce the tip, + * warm caches and repair EvoDB. Runs on the loadblk thread, bound to the + * active chainstate's Evo view. + */ +void FinishImportedStartup(node::NodeContext& node, const ArgsManager& args, bool skip_evodb_repair_on_reindex); +/** + * Release the databases and managers a chainstate load attempt opened, once + * the validation events it queued have run. + */ +void ReleaseChainstateLoadAttempt(node::NodeContext& node); +/** + * Run a node scheduler task as a round of active-chain work, bound to the + * active chainstate's Evo view once startup has published the Evo database. + */ +void RunSchedulerTask(const node::NodeContext& node, const std::function& task); void PrepareShutdown(node::NodeContext& node); /** diff --git a/src/instantsend/net_instantsend.cpp b/src/instantsend/net_instantsend.cpp index 353cbdde321a..d69bdb846da4 100644 --- a/src/instantsend/net_instantsend.cpp +++ b/src/instantsend/net_instantsend.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -144,9 +145,18 @@ std::unique_ptr NetInstantSend::BuildVeri const int sign_height = next_cycle_height < active_chain.Height() ? next_cycle_height - 1 : -1; pindex_start = llmq::SelectQuorumForSigningStartBlock(active_chain, sign_height, signOffset); } - // For RegTest non-rotating quorum cycleHash has directly quorum hash - auto quorum = llmq_params.useRotation ? llmq::SelectQuorumForSigning(llmq_params, m_qman, id, pindex_start) - : m_qman.GetQuorum(llmq_params.type, islock->cycleHash); + llmq::CQuorumCPtr quorum; + try { + // For RegTest non-rotating quorum cycleHash has directly quorum hash + quorum = llmq_params.useRotation ? llmq::SelectQuorumForSigning(llmq_params, m_qman, id, pindex_start) + : m_qman.GetQuorum(llmq_params.type, islock->cycleHash); + } catch (const evo::LocalStateError& e) { + // Left unchecked, so only this lock is dropped, without blaming its peer: the rest of the batch stays + // verifiable. + LogPrint(BCLog::INSTANTSEND, "NetInstantSend::%s -- txid=%s, islock=%s: cannot select quorum: %s\n", + __func__, islock->txid.ToString(), hash.ToString(), e.what()); + continue; + } if (!quorum) { // Different cycle hashes can select different quorums within the same batch. @@ -452,8 +462,9 @@ void NetInstantSend::ProcessInstantSendLock(NodeId from, const uint256& hash, co void NetInstantSend::WorkThreadMain() { while (!workInterrupt) { - bool fMoreWork = [&]() -> bool { - if (!m_is_manager.IsInstantSendEnabled()) return false; + bool fMoreWork{false}; + RunActiveEvoRound(m_chainman.EvoDb(), "isman", [&] { + if (!m_is_manager.IsInstantSendEnabled()) return; auto [more_work, locks] = m_is_manager.FetchPendingLocks(); if (!locks.empty()) { @@ -462,8 +473,8 @@ void NetInstantSend::WorkThreadMain() if (m_signer) { m_signer->ProcessPendingRetryLockTxs(m_is_manager.PrepareTxToRetry()); } - return more_work; - }(); + fMoreWork = more_work; + }); if (!fMoreWork && !workInterrupt.sleep_for(WORK_THREAD_SLEEP_INTERVAL)) { return; diff --git a/src/interfaces/chain.h b/src/interfaces/chain.h index 16aa05365946..a141974e8bbc 100644 --- a/src/interfaces/chain.h +++ b/src/interfaces/chain.h @@ -193,8 +193,10 @@ class Chain //! Check if block is chainlocked. virtual bool hasChainLock(int height, const uint256& hash) = 0; - //! Return list of MN Collateral from outputs - virtual std::vector listMNCollaterials(const std::vector>& outputs) = 0; + //! Return list of MN Collateral from outputs, or nullopt when the + //! masternode list is not available. + virtual std::optional> listMNCollaterials( + const std::vector>& outputs) = 0; //! Return the loader that registers wallets with the node's CoinJoin //! client manager, or nullptr when the node runs without one. @@ -292,8 +294,9 @@ class Chain virtual bool isNonStandardSpecialTx(const CTransactionRef& tx, std::string& reason) = 0; //! Whether v24 hard fork rules apply to the next block, which is what - //! enables version 2 asset lock transactions by consensus. - virtual bool isV24Active() = 0; + //! enables version 2 asset lock transactions by consensus. Nullopt when + //! this node cannot evaluate the deployment yet. + virtual std::optional isV24Active() = 0; //! Check if any block has been pruned. virtual bool havePruned() = 0; diff --git a/src/interfaces/node.h b/src/interfaces/node.h index 7cece18be3bc..25c8d76bf117 100644 --- a/src/interfaces/node.h +++ b/src/interfaces/node.h @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -149,18 +150,22 @@ class EVO { public: virtual ~EVO() {} + //! The masternode list at the chain tip, or nulls when it is not available. virtual std::pair getListAtChainTip() = 0; - virtual ProviderTxCapabilities getProviderTxCapabilities() = 0; + //! The provider transaction rules, or nullopt when this node cannot evaluate them yet. + virtual std::optional getProviderTxCapabilities() = 0; //! Validate provider endpoints against a capability snapshot without changing node or wallet state or //! taking cs_main. Transaction creation validates them again against the then-active rules. virtual std::optional validateProviderNetInfo(const ProviderNetInfo& net_info, MnType type, uint16_t version, bool ipv4_optional, bool optional) = 0; //! The first endpoint a masternode at the chain tip already uses, which a - //! registration with a new collateral cannot reuse. Nothing is reported for - //! endpoints validateProviderNetInfo refuses. - virtual std::optional findProviderNetInfoInUse(const ProviderNetInfo& net_info, MnType type, - uint16_t version, bool ipv4_optional) = 0; + //! registration with a new collateral cannot reuse, or nullopt when none is. + //! Nothing is reported for endpoints validateProviderNetInfo refuses. An + //! error means the masternode list could not be read, so nothing was checked. + virtual ProviderTxResult> findProviderNetInfoInUse(const ProviderNetInfo& net_info, + MnType type, uint16_t version, + bool ipv4_optional) = 0; //! Successful registration with an existing collateral leaves that coin locked, //! including when the signed transaction is returned without submission. virtual ProviderTxResult registerMasternode(Wallet& wallet, @@ -202,13 +207,15 @@ class GOV int32_t m_no{0}; int32_t m_yes{0}; }; - virtual Votes getObjVotes(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) = 0; + //! Vote counts against the current masternode list, or nullopt when that list is not available. + virtual std::optional getObjVotes(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) = 0; struct UniqueVoters { uint16_t m_regular{0}; uint16_t m_evo{0}; }; - virtual UniqueVoters getObjUniqueVoters(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) = 0; - virtual std::vector getCurrentVotes(const uint256& hash) = 0; + virtual std::optional getObjUniqueVoters(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) = 0; + //! The current votes on an object, nullopt while the masternode list is unavailable. + virtual std::optional> getCurrentVotes(const uint256& hash) = 0; virtual bool existsObj(const uint256& hash) = 0; virtual bool isEnabled() = 0; virtual bool processVoteAndRelay(const CGovernanceVote& vote, std::string& error) = 0; @@ -218,7 +225,8 @@ class GOV int superblockmaturitywindow{0}; int lastsuperblock{0}; int nextsuperblock{0}; - int fundingthreshold{0}; + //! Absolute yes votes a proposal needs; nullopt when the masternode list is not available. + std::optional fundingthreshold; CAmount governancebudget{0}; int64_t targetSpacing{0}; int relayRequiredConfs{1}; @@ -230,7 +238,7 @@ class GOV std::unordered_set hashes; CAmount allocated{0}; }; - virtual FundableResult getFundableProposalHashes() = 0; + virtual std::optional getFundableProposalHashes() = 0; virtual std::optional createProposal(int32_t revision, int64_t created_time, const std::string& data_hex, std::string& error) = 0; virtual bool submitProposal(const uint256& parent, int32_t revision, int64_t created_time, const std::string& data_hex, @@ -254,7 +262,8 @@ class LLMQ CAmount m_limit{0}; CAmount m_locked{0}; }; - virtual CreditPoolCounts getCreditPoolCounts() = 0; + //! Nullopt when the credit pool at the tip is not available. + virtual std::optional getCreditPoolCounts() = 0; struct InstantSendCounts { size_t m_verified{0}; size_t m_unverified{0}; @@ -272,7 +281,8 @@ class LLMQ int32_t m_newest_height{0}; int32_t m_expiry_height{0}; }; - virtual std::vector getQuorumStats() = 0; + //! Nullopt when the quorums at the tip are not available. + virtual std::optional> getQuorumStats() = 0; enum class PlatformQuorumStatus { FOUND, INVALID, UNAVAILABLE }; struct PlatformQuorumResult { PlatformQuorumStatus status{PlatformQuorumStatus::UNAVAILABLE}; @@ -495,8 +505,9 @@ class Node //! Is loading blocks. virtual bool isLoadingBlocks() = 0; - //! Whether the v24 hard fork rules are active at the chain tip. - virtual bool isV24Active() = 0; + //! Whether the v24 hard fork rules are active at the chain tip; nullopt + //! when this node cannot evaluate the deployment yet. + virtual std::optional isV24Active() = 0; //! Set network active. virtual void setNetworkActive(bool active) = 0; diff --git a/src/interfaces/providertx.h b/src/interfaces/providertx.h index fca76dccef0a..147423a7871e 100644 --- a/src/interfaces/providertx.h +++ b/src/interfaces/providertx.h @@ -39,9 +39,9 @@ enum class ProviderTxErrorCode { struct ProviderTxError { ProviderTxErrorCode code{ProviderTxErrorCode::INTERNAL_ERROR}; - bilingual_str message; - std::string reject_reason; - std::optional transaction_error; + bilingual_str message{}; + std::string reject_reason{}; + std::optional transaction_error{}; }; template diff --git a/src/interfaces/wallet.h b/src/interfaces/wallet.h index 22c24f94aa2d..5af01fe584aa 100644 --- a/src/interfaces/wallet.h +++ b/src/interfaces/wallet.h @@ -265,8 +265,8 @@ class Wallet //! Lock all existing dust UTXOs that match the current threshold. virtual void lockExistingDustOutputs() = 0; - //! List protx coins. - virtual std::vector listProTxCoins() = 0; + //! List protx coins, or nullopt when the masternode list is not available. + virtual std::optional> listProTxCoins() = 0; //! Create transaction. virtual util::Result createTransaction(const std::vector& recipients, diff --git a/src/llmq/net_dkg.cpp b/src/llmq/net_dkg.cpp index e12dba4ade58..00c65fad154a 100644 --- a/src/llmq/net_dkg.cpp +++ b/src/llmq/net_dkg.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,7 @@ #include #include #include +#include #include namespace llmq { @@ -783,15 +785,24 @@ void NetDKG::Interrupt() void NetDKG::PhaseHandlerThread(ActiveDKGSessionHandler& handler) { + const std::string round_name{strprintf("dkg %s qi[%d]", handler.params.name, handler.QuorumIndex())}; while (!handler.IsStopRequested()) { - try { - LogPrint(BCLog::LLMQ_DKG, "NetDKG::%s -- %s qi[%d] - starting HandleDKGRound\n", __func__, - handler.params.name, handler.QuorumIndex()); - HandleDKGRound(handler); - } catch (AbortPhaseException& e) { - m_active->dkgdbgman.MarkAborted(handler.params.type, handler.QuorumIndex()); - LogPrint(BCLog::LLMQ_DKG, "NetDKG::%s -- %s qi[%d] - aborted current DKG session\n", __func__, - handler.params.name, handler.QuorumIndex()); + const bool completed{RunActiveEvoRound(m_chainman.EvoDb(), round_name, [&] { + try { + LogPrint(BCLog::LLMQ_DKG, "NetDKG::PhaseHandlerThread -- %s qi[%d] - starting HandleDKGRound\n", + handler.params.name, handler.QuorumIndex()); + HandleDKGRound(handler); + } catch (AbortPhaseException& e) { + m_active->dkgdbgman.MarkAborted(handler.params.type, handler.QuorumIndex()); + LogPrint(BCLog::LLMQ_DKG, "NetDKG::PhaseHandlerThread -- %s qi[%d] - aborted current DKG session\n", + handler.params.name, handler.QuorumIndex()); + } + })}; + if (!completed) { + // Retry after a second, unless asked to stop meanwhile. + for (int i{0}; i < 10 && !handler.IsStopRequested(); ++i) { + UninterruptibleSleep(std::chrono::milliseconds{100}); + } } } } diff --git a/src/llmq/net_quorum.cpp b/src/llmq/net_quorum.cpp index 1dc0768d67ce..4906b03af5b9 100644 --- a/src/llmq/net_quorum.cpp +++ b/src/llmq/net_quorum.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -644,10 +645,18 @@ void NetQuorum::StartVvecSyncThread(CQuorumCPtr pQuorum) const return; } - workerPool.push([pQuorum = std::move(pQuorum), this](int threadId) mutable { - DataRecoveryThread(std::move(pQuorum), CQuorumDataRequest::QUORUM_VERIFICATION_VECTOR, - /*protx_hash=*/uint256(), /*start_offset=*/0); - }); + const auto release{[pQuorum] { pQuorum->ReleaseRecovery(); }}; + workerPool.push(WithCapturedEvoView( + [pQuorum = std::move(pQuorum), release, this](int threadId) mutable { + try { + DataRecoveryThread(std::move(pQuorum), CQuorumDataRequest::QUORUM_VERIFICATION_VECTOR, + /*protx_hash=*/uint256(), /*start_offset=*/0); + } catch (const evo::LocalStateError&) { + release(); + throw; + } + }, + release)); } void NetQuorum::TryStartVvecSyncThread(gsl::not_null block_index, CQuorumCPtr pQuorum, @@ -678,10 +687,18 @@ void NetQuorum::StartSkShareRecoveryThread(gsl::not_null pIn return; } - workerPool.push([pQuorum = std::move(pQuorum), pIndex, nDataMaskIn, this](int threadId) mutable { - const size_t size_offset = GetQuorumRecoveryStartOffset(*pQuorum, pIndex); - DataRecoveryThread(std::move(pQuorum), nDataMaskIn, m_role->GetProTxHash(), size_offset); - }); + const auto release{[pQuorum] { pQuorum->ReleaseRecovery(); }}; + workerPool.push(WithCapturedEvoView( + [pQuorum = std::move(pQuorum), pIndex, nDataMaskIn, release, this](int threadId) mutable { + try { + const size_t size_offset = GetQuorumRecoveryStartOffset(*pQuorum, pIndex); + DataRecoveryThread(std::move(pQuorum), nDataMaskIn, m_role->GetProTxHash(), size_offset); + } catch (const evo::LocalStateError&) { + release(); + throw; + } + }, + release)); } size_t NetQuorum::GetQuorumRecoveryStartOffset(const CQuorum& quorum, @@ -724,7 +741,7 @@ void NetQuorum::StartCleanupOldQuorumDataThread(gsl::not_null +#include + #include #include #include @@ -284,12 +286,15 @@ bool NetSigning::ProcessPendingRecoveredSigs() void NetSigning::WorkThreadSigning() { while (!workInterrupt) { - bool fMoreWork = ProcessPendingRecoveredSigs(); + bool fMoreWork{false}; + RunActiveEvoRound(&m_sig_manager.EvoDb(), "recsig-signing", [&] { + fMoreWork = ProcessPendingRecoveredSigs(); - constexpr auto CLEANUP_INTERVAL{5s}; - if (cleanupThrottler.TryCleanup(CLEANUP_INTERVAL)) { - m_sig_manager.Cleanup(); - } + constexpr auto CLEANUP_INTERVAL{5s}; + if (cleanupThrottler.TryCleanup(CLEANUP_INTERVAL)) { + m_sig_manager.Cleanup(); + } + }); // TODO Wakeup when pending signing is needed? if (!fMoreWork && !workInterrupt.sleep_for(std::chrono::milliseconds(100))) { @@ -324,10 +329,12 @@ void NetSigning::WorkThreadCleaning() assert(m_shares_manager); while (!workInterrupt) { - RemoveDiscouragedNodeStates(); + RunActiveEvoRound(&m_sig_manager.EvoDb(), "sigshares-cleaning", [&] { + RemoveDiscouragedNodeStates(); - m_shares_manager->SendMessages(); - m_shares_manager->Cleanup(); + m_shares_manager->SendMessages(); + m_shares_manager->Cleanup(); + }); workInterrupt.sleep_for(std::chrono::milliseconds(100)); } @@ -338,52 +345,58 @@ void NetSigning::WorkThreadDispatcher() assert(m_shares_manager); while (!workInterrupt) { - // Dispatch all pending signs (individual tasks) - { - auto signs = m_shares_manager->DispatchPendingSigns(); - // Dispatch all signs to worker pool - for (auto& work : signs) { - if (workInterrupt) break; - - worker_pool.push([this, work = std::move(work)](int) mutable { - auto rs = m_shares_manager->SignAndProcessSingleShare(std::move(work)); - ProcessRecoveredSig(rs, true); - }); + // Tasks pushed below run under this round's binding. + RunActiveEvoRound(&m_sig_manager.EvoDb(), "sigshares-dispatch", [&] { + // Dispatch all pending signs (individual tasks) + { + auto signs = m_shares_manager->DispatchPendingSigns(); + // Dispatch all signs to worker pool + for (auto& work : signs) { + if (workInterrupt) break; + + worker_pool.push(WithCapturedEvoView([this, work = std::move(work)](int) mutable { + auto rs = m_shares_manager->SignAndProcessSingleShare(std::move(work)); + ProcessRecoveredSig(rs, true); + })); + } } - } - // Collect pending sig shares synchronously and dispatch each batch to a worker for parallel BLS verification. - // Batches awaiting verification are bounded so that under flood shares back up in the capped - // pending maps instead of migrating into the unbounded worker pool task queue. - // - // Each batch is bounded by actual share count (not unique-session count), so at most - // MAX_UNVERIFIED_BATCHES * MAX_SHARES_PER_BATCH shares can be sitting in / on the worker pool at once. - static constexpr int MAX_UNVERIFIED_BATCHES{4}; - static constexpr size_t MAX_SHARES_PER_BATCH{32}; - while (!workInterrupt && unverified_batches < MAX_UNVERIFIED_BATCHES) { - std::unordered_map> sigSharesByNodes; - std::unordered_map, CQuorumCPtr, StaticSaltedHasher> quorums; - - bool more_work = m_shares_manager->CollectPendingSigSharesToVerify(MAX_SHARES_PER_BATCH, sigSharesByNodes, quorums); - - if (sigSharesByNodes.empty()) { - break; + // Collect pending sig shares synchronously and dispatch each batch to a worker for parallel BLS + // verification. Batches awaiting verification are bounded so that under flood shares back up in the capped + // pending maps instead of migrating into the unbounded worker pool task queue. + // + // Each batch is bounded by actual share count (not unique-session count), so at most + // MAX_UNVERIFIED_BATCHES * MAX_SHARES_PER_BATCH shares can be sitting in / on the worker pool at once. + static constexpr int MAX_UNVERIFIED_BATCHES{4}; + static constexpr size_t MAX_SHARES_PER_BATCH{32}; + while (!workInterrupt && unverified_batches < MAX_UNVERIFIED_BATCHES) { + std::unordered_map> sigSharesByNodes; + std::unordered_map, CQuorumCPtr, StaticSaltedHasher> quorums; + + bool more_work = m_shares_manager->CollectPendingSigSharesToVerify(MAX_SHARES_PER_BATCH, + sigSharesByNodes, quorums); + + if (sigSharesByNodes.empty()) { + break; + } + + ++unverified_batches; + worker_pool.push(WithCapturedEvoView( + [this, sigSharesByNodes = std::move(sigSharesByNodes), quorums = std::move(quorums)](int) mutable { + // Ensures unverified_batches is decremented on every exit path, including exceptions. + struct UnverifiedBatchGuard { + std::atomic& count; + ~UnverifiedBatchGuard() { --count; } + } guard{unverified_batches}; + ProcessPendingSigShares(std::move(sigSharesByNodes), std::move(quorums)); + }, + [this] { --unverified_batches; })); + + if (!more_work) { + break; + } } - - ++unverified_batches; - worker_pool.push([this, sigSharesByNodes = std::move(sigSharesByNodes), quorums = std::move(quorums)](int) mutable { - // Ensures unverified_batches is decremented on every exit path, including exceptions. - struct UnverifiedBatchGuard { - std::atomic& count; - ~UnverifiedBatchGuard() { --count; } - } guard{unverified_batches}; - ProcessPendingSigShares(std::move(sigSharesByNodes), std::move(quorums)); - }); - - if (!more_work) { - break; - } - } + }); // Always sleep briefly between checks workInterrupt.sleep_for(std::chrono::milliseconds(10)); diff --git a/src/llmq/quorumsman.h b/src/llmq/quorumsman.h index 173143979af6..70bb955206b0 100644 --- a/src/llmq/quorumsman.h +++ b/src/llmq/quorumsman.h @@ -140,6 +140,8 @@ class CQuorumManager final //! The Evo view the calling operation reads. EvoViewToken CurrentView() const { return m_evoDb.CurrentView(); } + //! The EvoDB this manager reads, for callers that bind an Evo view. + const CEvoDB& EvoDb() const { return m_evoDb; } // all these methods will lock cs_main for a short period of time CQuorumCPtr GetQuorum(Consensus::LLMQType llmqType, const uint256& quorumHash) const diff --git a/src/llmq/signing.cpp b/src/llmq/signing.cpp index d4587e61e206..43c43c7eb955 100644 --- a/src/llmq/signing.cpp +++ b/src/llmq/signing.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -429,6 +430,8 @@ void CRecoveredSigsDb::CleanupOldVotes(int64_t maxAge) ////////////////// +const CEvoDB& CSigningManager::EvoDb() const { return qman.EvoDb(); } + CSigningManager::CSigningManager(const CQuorumManager& _qman, const util::DbWrapperParams& db_params, int64_t max_recsigs_age) : db{db_params}, @@ -587,21 +590,29 @@ bool CSigningManager::CollectPendingRecoveredSigsToVerify( auto llmqType = recSig->getLlmqType(); auto quorumKey = std::make_pair(recSig->getLlmqType(), recSig->getQuorumHash()); if (!ret_pubkeys.count(quorumKey)) { - auto quorum = qman.GetQuorum(llmqType, recSig->getQuorumHash()); - if (!quorum) { - LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not found, node=%d\n", __func__, - recSig->getQuorumHash().ToString(), nodeId); + try { + auto quorum = qman.GetQuorum(llmqType, recSig->getQuorumHash()); + if (!quorum) { + LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not found, node=%d\n", __func__, + recSig->getQuorumHash().ToString(), nodeId); + it = v.erase(it); + continue; + } + if (!IsQuorumActive(llmqType, qman, quorum->qc->quorumHash)) { + LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not active anymore, node=%d\n", + __func__, recSig->getQuorumHash().ToString(), nodeId); + it = v.erase(it); + continue; + } + + ret_pubkeys.emplace(quorumKey, quorum->qc->quorumPublicKey); + } catch (const evo::LocalStateError& e) { + // Only this signature is dropped, and its peer is not to blame. + LogPrint(BCLog::LLMQ, "CSigningManager::%s -- cannot check quorum %s: %s, node=%d\n", __func__, + recSig->getQuorumHash().ToString(), e.what(), nodeId); it = v.erase(it); continue; } - if (!IsQuorumActive(llmqType, qman, quorum->qc->quorumHash)) { - LogPrint(BCLog::LLMQ, "CSigningManager::%s -- quorum %s not active anymore, node=%d\n", __func__, - recSig->getQuorumHash().ToString(), nodeId); - it = v.erase(it); - continue; - } - - ret_pubkeys.emplace(quorumKey, quorum->qc->quorumPublicKey); } ++it; diff --git a/src/llmq/signing.h b/src/llmq/signing.h index cd40777edc0e..924dea5e3c0d 100644 --- a/src/llmq/signing.h +++ b/src/llmq/signing.h @@ -24,6 +24,7 @@ class Chainstate; class DataStream; class CDBBatch; class CDBWrapper; +class CEvoDB; class CInv; class CTransaction; struct RPCResult; @@ -204,6 +205,9 @@ class CSigningManager CSigningManager(const CSigningManager&) = delete; CSigningManager& operator=(const CSigningManager&) = delete; explicit CSigningManager(const CQuorumManager& _qman, const util::DbWrapperParams& db_params, int64_t max_recsigs_age); + + //! The EvoDB the quorum manager reads, for workers that bind an Evo view. + const CEvoDB& EvoDb() const; ~CSigningManager(); bool AlreadyHave(const CInv& inv) const EXCLUSIVE_LOCKS_REQUIRED(!cs_pending); diff --git a/src/net.cpp b/src/net.cpp index 6ae8aa234292..9992fb8446a2 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -43,6 +43,7 @@ #include #include +#include #include #include #include @@ -62,6 +63,7 @@ #include #include #include +#include #include #include @@ -2955,6 +2957,15 @@ bool CConnman::MaybePickPreferredNetwork(std::optional& network) return false; } +std::optional CConnman::ListForConnectedMasternodes(CDeterministicMNManager& dmnman, + const std::set& connected) +{ + if (connected.empty()) return CDeterministicMNList{}; + std::optional tip_list; + RunActiveEvoRound(&dmnman.EvoDb(), "opencon", [&] { tip_list = dmnman.GetListAtChainTip(); }); + return tip_list; +} + void CConnman::ThreadOpenConnections(const std::vector connect, CDeterministicMNManager& dmnman) { AssertLockNotHeld(m_unused_i2p_sessions_mutex); @@ -3190,7 +3201,11 @@ void CConnman::ThreadOpenConnections(const std::vector connect, CDe addrman.ResolveCollisions(); - auto mnList = dmnman.GetListAtChainTip(); + // Without the masternode list, connected masternodes cannot be + // skipped below; try again next round. + const auto tip_list{ListForConnectedMasternodes(dmnman, setConnectedMasternodes)}; + if (!tip_list) continue; + const auto& mnList{*tip_list}; const auto current_time{NodeClock::now()}; int nTries = 0; @@ -3467,7 +3482,10 @@ void CConnman::ThreadOpenMasternodeConnections(CDeterministicMNManager& dmnman, } }); - auto mnList = dmnman.GetListAtChainTip(); + std::optional tip_list; + RunActiveEvoRound(&dmnman.EvoDb(), "mncon", [&] { tip_list = dmnman.GetListAtChainTip(); }); + if (!tip_list) continue; + const auto& mnList{*tip_list}; if (interruptNet) return; @@ -3706,7 +3724,28 @@ void CConnman::OpenMasternodeConnection(const CAddress &addrConnect, bool use_v2 Mutex NetEventsInterface::g_msgproc_mutex; -void CConnman::ThreadMessageHandler() +bool CConnman::ServicePeer(const CEvoDB& evodb, CNode& node, bool send) +{ + bool more_work{false}; + try { + const ActiveEvoViewScope evo_view{&evodb}; + more_work = m_msgproc->ProcessMessages(&node, flagInterruptMsgProc); + } catch (const evo::LocalStateError& e) { + LogPrint(BCLog::NET, "peer=%d: Evo state unavailable: %s\n", node.GetId(), e.what()); + } + // Sends run even when receiving stopped early: they include the peer's + // discouragement and ping timeout. + if (!send || flagInterruptMsgProc) return more_work; + try { + const ActiveEvoViewScope evo_view{&evodb}; + m_msgproc->SendMessages(&node); + } catch (const evo::LocalStateError& e) { + LogPrint(BCLog::NET, "peer=%d: Evo state unavailable: %s\n", node.GetId(), e.what()); + } + return more_work; +} + +void CConnman::ThreadMessageHandler(const CEvoDB& evodb) { LOCK(NetEventsInterface::g_msgproc_mutex); @@ -3732,16 +3771,9 @@ void CConnman::ThreadMessageHandler() if (pnode->fDisconnect) continue; - // Receive messages - bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc); + const bool send{!fSkipSendMessagesForMasternodes || !pnode->m_masternode_connection}; + const bool fMoreNodeWork{ServicePeer(evodb, *pnode, send)}; fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend); - if (flagInterruptMsgProc) - return; - // Send messages - if (!fSkipSendMessagesForMasternodes || !pnode->m_masternode_connection) { - m_msgproc->SendMessages(pnode); - } - if (flagInterruptMsgProc) return; } @@ -4113,7 +4145,8 @@ bool CConnman::Start(CDeterministicMNManager& dmnman, CMasternodeMetaMan& mn_met } // Process messages - threadMessageHandler = std::thread(&util::TraceThread, "msghand", [this] { ThreadMessageHandler(); }); + threadMessageHandler = std::thread(&util::TraceThread, "msghand", + [this, &evodb = dmnman.EvoDb()] { ThreadMessageHandler(evodb); }); if (m_i2p_sam_session) { threadI2PAcceptIncoming = diff --git a/src/net.h b/src/net.h index d0319cfd4b34..c0b184f83b19 100644 --- a/src/net.h +++ b/src/net.h @@ -48,6 +48,7 @@ #include #include #include +#include #include #include #include @@ -60,6 +61,7 @@ class CChainParams; class CConnman; class CDeterministicMNList; class CDeterministicMNManager; +class CEvoDB; class CMasternodeMetaMan; class CMasternodeSync; class CNode; @@ -1617,10 +1619,22 @@ friend class CNode; void ProcessAddrFetch() EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_nodes_mutex, !m_unused_i2p_sessions_mutex, !mutexMsgProc); + /** The tip masternode list that identifies the masternodes in `connected` + * among outbound candidates: an empty list when there are none, nullopt + * when it cannot be read. */ + static std::optional ListForConnectedMasternodes(CDeterministicMNManager& dmnman, + const std::set& connected); void ThreadOpenConnections(const std::vector connect, CDeterministicMNManager& dmnman) EXCLUSIVE_LOCKS_REQUIRED(!m_addr_fetches_mutex, !m_added_nodes_mutex, !m_nodes_mutex, !m_reconnections_mutex, !m_unused_i2p_sessions_mutex, !mutexMsgProc); - void ThreadMessageHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc); + void ThreadMessageHandler(const CEvoDB& evodb) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc); + /** One message-handler turn for a peer: receive (its queued requests, + * orphans to reconsider, then its next message) and, if `send`, send. + * Both halves are bound to the active Evo view. A local Evo state error + * ends the half it occurs in, never the thread, and the sends still run + * after receiving stopped early. Returns whether the peer has more work. */ + bool ServicePeer(const CEvoDB& evodb, CNode& node, bool send) + EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex, !m_nodes_mutex, !mutexMsgProc); void ThreadI2PAcceptIncoming(CMasternodeSync& mn_sync) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc); void AcceptConnection(const ListenSocket& hListenSocket, CMasternodeSync& mn_sync) EXCLUSIVE_LOCKS_REQUIRED(!m_nodes_mutex, !mutexMsgProc); diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 1e253985afe0..6191d1782883 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -1129,6 +1129,11 @@ class PeerManagerImpl final : public PeerManager void ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic& interruptMsgProc) EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, NetEventsInterface::g_msgproc_mutex) LOCKS_EXCLUDED(::cs_main); + /** Serve the requests at the front of the peer's GETDATA queue, collecting + * the ones not found, or whose lookup threw, in vNotFound. */ + void ServeGetData(CNode& pfrom, Peer& peer, const std::atomic& interruptMsgProc, std::vector& vNotFound) + EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex, peer.m_getdata_requests_mutex, + NetEventsInterface::g_msgproc_mutex) LOCKS_EXCLUDED(::cs_main); /** Process a new block. Perform any post-processing housekeeping */ void ProcessBlock(CNode& from, const std::shared_ptr& pblock, bool force_processing); @@ -3010,14 +3015,14 @@ CTransactionRef PeerManagerImpl::FindTxForGetData(const Peer::TxRelay& tx_relay, return {}; } -void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic& interruptMsgProc) +void PeerManagerImpl::ServeGetData(CNode& pfrom, Peer& peer, const std::atomic& interruptMsgProc, + std::vector& vNotFound) { AssertLockNotHeld(cs_main); auto tx_relay = peer.GetTxRelay(); std::deque::iterator it = peer.m_getdata_requests.begin(); - std::vector vNotFound; // Process as many TX items from the front of the getdata queue as // possible, since they're common and it's efficient to batch process @@ -3030,12 +3035,14 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic if (pfrom.fPauseSend) break; - const CInv &inv = *it; + const CInv inv{*it}; if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK) { break; } - ++it; + // Dequeued before it is served: a lookup that throws leaves neither + // this request nor the ones served before it queued. + it = peer.m_getdata_requests.erase(it); if (tx_relay == nullptr && NetMessageViolatesBlocksOnly(inv.GetCommand())) { // Note that if we receive a getdata for non-block messages @@ -3044,6 +3051,8 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic continue; } + // Not found until it is served, including when a lookup throws. + vNotFound.push_back(inv); bool push = false; if (inv.IsGenTxMsg()) { CTransactionRef tx = FindTxForGetData(*tx_relay, inv.hash); @@ -3121,23 +3130,36 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic } } - if (!push) { - vNotFound.push_back(inv); + if (push) { + vNotFound.pop_back(); } } // Only process one BLOCK item per call, since they're uncommon and can be // expensive to process. if (it != peer.m_getdata_requests.end() && !pfrom.fPauseSend) { - const CInv &inv = *it++; + const CInv inv{*it}; + it = peer.m_getdata_requests.erase(it); if (inv.IsGenBlkMsg()) { ProcessGetBlockData(pfrom, peer, inv); } // else: If the first item on the queue is an unknown type, we erase it // and continue processing the queue on the next call. } +} - peer.m_getdata_requests.erase(peer.m_getdata_requests.begin(), it); +void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic& interruptMsgProc) +{ + std::vector vNotFound; + // A lookup this node's Evo state cannot answer ends the batch. The + // requests found missing before it, and the one that failed, have left the + // queue, so they are still answered: this node cannot serve them. + std::exception_ptr local_error; + try { + ServeGetData(pfrom, peer, interruptMsgProc, vNotFound); + } catch (const evo::LocalStateError&) { + local_error = std::current_exception(); + } if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't @@ -3156,6 +3178,7 @@ void PeerManagerImpl::ProcessGetData(CNode& pfrom, Peer& peer, const std::atomic // assume we have them and request the parents from us. MakeAndPushMessage(pfrom, NetMsgType::NOTFOUND, vNotFound); } + if (local_error) std::rethrow_exception(local_error); } void PeerManagerImpl::SendBlockTransactions(CNode& pfrom, Peer& peer, const CBlock& block, const BlockTransactionsRequest& req) { @@ -6027,6 +6050,9 @@ bool PeerManagerImpl::ProcessMessages(CNode* pfrom, std::atomic& interrupt if (m_orphanage.HaveTxToReconsider(peer->m_id)) fMoreWork = true; } catch (const std::exception& e) { LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name()); + } catch (const evo::LocalStateError& e) { + // This node's Evo state, not the peer's message: drop the message only. + LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' (%s) caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size, e.what(), typeid(e).name()); } catch (...) { LogPrint(BCLog::NET, "%s(%s, %u bytes): Unknown exception caught\n", __func__, SanitizeString(msg.m_type), msg.m_message_size); } diff --git a/src/node/chainstate.cpp b/src/node/chainstate.cpp index 42fc24fba26a..4ada12d31859 100644 --- a/src/node/chainstate.cpp +++ b/src/node/chainstate.cpp @@ -287,6 +287,7 @@ static ChainstateLoadResult CompleteChainstateInitialization(ChainstateManager& // block tree into BlockIndex()! for (Chainstate* chainstate : chainman.GetAll()) { + const EvoViewScope evo_view{chainstate->EvoView()}; LogPrintf("Initializing chainstate %s\n", chainstate->ToString()); chainstate->InitCoinsDB( @@ -337,7 +338,7 @@ static ChainstateLoadResult CompleteChainstateInitialization(ChainstateManager& } } - if (!special_tx.m_mnhfman->ForceSignalDBUpdate(chainman.ActiveTip())) { + if (!special_tx.m_mnhfman->ForceSignalDBUpdate(chainman.ActiveChainstate().EvoView(), chainman.ActiveTip())) { return {ChainstateLoadStatus::FAILURE, _("Error upgrading evo database for EHF")}; } @@ -488,6 +489,7 @@ ChainstateLoadResult VerifyLoadedChainstate(ChainstateManager& chainman, const C LOCK(cs_main); for (Chainstate* chainstate : chainman.GetAll()) { + const EvoViewScope evo_view{chainstate->EvoView()}; if (!is_coinsview_empty(chainstate)) { const CBlockIndex* tip = chainstate->m_chain.Tip(); if (tip && tip->nTime > GetTime() + MAX_FUTURE_BLOCK_TIME) { diff --git a/src/node/context.h b/src/node/context.h index ee9db1292479..88b0184a61e4 100644 --- a/src/node/context.h +++ b/src/node/context.h @@ -112,6 +112,11 @@ struct NodeContext { std::unique_ptr cj_walletman; std::unique_ptr dstxman; std::unique_ptr evodb; + //! The Evo database for dispatchers that start before the block databases + //! load (the scheduler, REST) to bind to. Startup publishes it once loading, + //! retries included, has finished and withdraws it before destroying it, + //! after those dispatchers have stopped. Until then their work runs unbound. + std::atomic evodb_for_dispatch{nullptr}; std::unique_ptr special_tx; std::unique_ptr dmnman; std::unique_ptr isman; diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp index 251c2d4b6a0e..c13f8dad7218 100644 --- a/src/node/interfaces.cpp +++ b/src/node/interfaces.cpp @@ -17,7 +17,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -95,6 +97,9 @@ #include #include #include +#include +#include +#include #include #include @@ -140,6 +145,52 @@ namespace node { // All members of the classes in this namespace are intentionally public, as the // classes themselves are private. namespace { +bilingual_str EvoStateUnavailableMessage() +{ + return _("Masternode state is not available yet. See debug.log for details."); +} + +ProviderTxError UnavailableProviderTxError() +{ + return {.code = interfaces::ProviderTxErrorCode::INTERNAL_ERROR, .message = EvoStateUnavailableMessage()}; +} + +//! Set the misc warning and log `e`, once per operation and active Evo view: +//! GUI models poll these operations, and each warning notifies the GUI. +void ReportEvoStateUnavailable(const CEvoDB* evodb, std::string_view operation, const evo::LocalStateError& e) +{ + static Mutex mutex; + static std::set> reported; + const EvoViewToken view{evodb ? evodb->ActiveView() : EvoViewToken{}}; + if (WITH_LOCK(mutex, return reported.emplace(operation, view.db, view.identity, view.generation).second)) { + // Without a snapshot, only pruning removes the block data Evo state is + // derived from. + const auto reason{evodb && evodb->HasLiveGeneration() ? EvoStateUnavailableReason::SNAPSHOT + : dynamic_cast(&e) ? EvoStateUnavailableReason::PRUNED + : EvoStateUnavailableReason::OTHER}; + WarnLocalEvoStateUnavailable(strprintf("%s could not read it", operation), reason); + uiInterface.NotifyAlertChanged(); + LogPrintf("ERROR: %s: Evo state unavailable: %s\n", operation, e.what()); + } +} + +/** Run a GUI-facing operation that reads Evo state on the active chainstate's + * view. When this node cannot provide that state, the operation reports it + * and returns `on_unavailable()`: the error must not reach Qt, and callers + * must not mistake it for data. */ +template +std::invoke_result_t WithActiveEvoView(const CEvoDB* evodb, std::string_view operation, Fn&& fn, + OnUnavailable&& on_unavailable) +{ + try { + const ActiveEvoViewScope evo_view{evodb}; + return fn(); + } catch (const evo::LocalStateError& e) { + ReportEvoStateUnavailable(evodb, operation, e); + return on_unavailable(); + } +} + class MnEntryImpl : public MnEntry { private: @@ -273,83 +324,128 @@ class EVOImpl : public EVO public: std::pair getListAtChainTip() override { - const auto *tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()); - if (tip && context().dmnman) { - MnListImpl mnList = context().dmnman->GetListForBlock(tip); - if (!mnList.getBlockHash().IsNull()) { - mnList.setContext(m_context); - return {std::make_shared(mnList), tip}; - } - } - return {nullptr, nullptr}; + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::pair { + const auto* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()); + if (tip && context().dmnman) { + MnListImpl mnList = context().dmnman->GetListForBlock(tip); + if (!mnList.getBlockHash().IsNull()) { + mnList.setContext(m_context); + return {std::make_shared(mnList), tip}; + } + } + return {nullptr, nullptr}; + }, + [] { return std::pair{nullptr, nullptr}; }); + } + std::optional getProviderTxCapabilities() override + { + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { return evo::provider::GetCapabilities(context()); }, + [] { return std::nullopt; }); } - ProviderTxCapabilities getProviderTxCapabilities() override { return evo::provider::GetCapabilities(context()); } std::optional validateProviderNetInfo(const ProviderNetInfo& net_info, MnType type, uint16_t version, bool ipv4_optional, bool optional) override { return evo::provider::ValidateNetInfo(net_info, type, version, ipv4_optional, optional); } - std::optional findProviderNetInfoInUse(const ProviderNetInfo& net_info, MnType type, uint16_t version, - bool ipv4_optional) override + ProviderTxResult> findProviderNetInfoInUse(const ProviderNetInfo& net_info, MnType type, + uint16_t version, bool ipv4_optional) override { - return evo::provider::FindNetInfoInUse(context(), net_info, type, version, ipv4_optional); + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> ProviderTxResult> { + if (!context().dmnman) return UnavailableProviderTxError(); + return evo::provider::FindNetInfoInUse(context(), net_info, type, version, ipv4_optional); + }, + UnavailableProviderTxError); } ProviderTxResult registerMasternode(Wallet& wallet, const ProviderRegistrationRequest& request) override { - return evo::provider::Register(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::Register(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult prepareMasternodeRegistration( Wallet& wallet, const ProviderRegistrationRequest& request) override { - return evo::provider::PrepareRegistration(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, + [&] { return evo::provider::PrepareRegistration(context(), wallet, request); }, UnavailableProviderTxError); } ProviderTxResult submitMasternodeRegistration( Wallet& wallet, const CTransactionRef& tx, const std::vector& collateral_signature) override { - return evo::provider::SubmitRegistration(context(), wallet, tx, collateral_signature); + return WithActiveEvoView( + context().evodb.get(), __func__, + [&] { return evo::provider::SubmitRegistration(context(), wallet, tx, collateral_signature); }, + UnavailableProviderTxError); } ProviderTxResult updateMasternodeService(Wallet& wallet, const ProviderUpdateServiceRequest& request) override { - return evo::provider::UpdateService(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::UpdateService(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult updateMasternodeRegistrar(Wallet& wallet, const ProviderUpdateRegistrarRequest& request) override { - return evo::provider::UpdateRegistrar(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::UpdateRegistrar(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult revokeMasternode(Wallet& wallet, const ProviderRevokeRequest& request) override { - return evo::provider::Revoke(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::Revoke(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult prepareSharedRegistration(const SharedRegistrationRequest& request) override { - return evo::provider::PrepareSharedRegistration(context(), request); + return WithActiveEvoView( + context().evodb.get(), __func__, + [&] { return evo::provider::PrepareSharedRegistration(context(), request); }, UnavailableProviderTxError); } ProviderTxResult signShared(Wallet& wallet, const SharedSignRequest& request) override { - return evo::provider::SignShared(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::SignShared(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult combineShared(Wallet& wallet, const SharedCombineRequest& request) override { - return evo::provider::CombineShared(context(), &wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::CombineShared(context(), &wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult dissolveShared(Wallet& wallet, const SharedDissolveRequest& request) override { - return evo::provider::DissolveShared(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::DissolveShared(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult prepareSharedDissolution(const SharedDissolvePrepareRequest& request) override { - return evo::provider::PrepareSharedDissolution(context(), request); + return WithActiveEvoView( + context().evodb.get(), __func__, + [&] { return evo::provider::PrepareSharedDissolution(context(), request); }, UnavailableProviderTxError); } ProviderTxResult updateShare(Wallet& wallet, const SharedUpdateShareRequest& request) override { - return evo::provider::UpdateShare(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, [&] { return evo::provider::UpdateShare(context(), wallet, request); }, + UnavailableProviderTxError); } ProviderTxResult prepareSharedRegistrarUpdate( Wallet& wallet, const SharedRegistrarUpdatePrepareRequest& request) override { - return evo::provider::PrepareSharedRegistrarUpdate(context(), wallet, request); + return WithActiveEvoView( + context().evodb.get(), __func__, + [&] { return evo::provider::PrepareSharedRegistrarUpdate(context(), wallet, request); }, + UnavailableProviderTxError); } void setContext(NodeContext* context) override { @@ -373,43 +469,58 @@ class GOVImpl : public GOV context().govman->GetAllNewerThan(objs, nMoreThanTime, include_postponed); } } - Votes getObjVotes(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) override - { - Votes ret; - if (context().govman != nullptr && context().dmnman != nullptr) { - const auto& tip_mn_list{context().dmnman->GetListAtChainTip()}; - if (auto govobj{context().govman->FindGovernanceObject(obj.GetHash())}) { - ret.m_abs = govobj->GetAbstainCount(tip_mn_list, vote_signal); - ret.m_no = govobj->GetNoCount(tip_mn_list, vote_signal); - ret.m_yes = govobj->GetYesCount(tip_mn_list, vote_signal); - } else { - ret.m_abs = obj.GetAbstainCount(tip_mn_list, vote_signal); - ret.m_no = obj.GetNoCount(tip_mn_list, vote_signal); - ret.m_yes = obj.GetYesCount(tip_mn_list, vote_signal); - } - } - return ret; - } - UniqueVoters getObjUniqueVoters(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) override - { - if (context().govman != nullptr && context().dmnman != nullptr) { - const auto& tip_mn_list{context().dmnman->GetListAtChainTip()}; - if (auto govobj{context().govman->FindGovernanceObject(obj.GetHash())}) { - const auto count = govobj->GetUniqueVoterCount(tip_mn_list, vote_signal); - return {.m_regular = count.m_regular, .m_evo = count.m_evo}; - } else { - const auto count = obj.GetUniqueVoterCount(tip_mn_list, vote_signal); - return {.m_regular = count.m_regular, .m_evo = count.m_evo}; - } - } - return {0, 0}; + std::optional getObjVotes(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) override + { + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { + Votes ret; + if (context().govman != nullptr && context().dmnman != nullptr) { + const auto& tip_mn_list{context().dmnman->GetListAtChainTip()}; + if (auto govobj{context().govman->FindGovernanceObject(obj.GetHash())}) { + ret.m_abs = govobj->GetAbstainCount(tip_mn_list, vote_signal); + ret.m_no = govobj->GetNoCount(tip_mn_list, vote_signal); + ret.m_yes = govobj->GetYesCount(tip_mn_list, vote_signal); + } else { + ret.m_abs = obj.GetAbstainCount(tip_mn_list, vote_signal); + ret.m_no = obj.GetNoCount(tip_mn_list, vote_signal); + ret.m_yes = obj.GetYesCount(tip_mn_list, vote_signal); + } + } + return ret; + }, + [] { return std::nullopt; }); + } + std::optional getObjUniqueVoters(const CGovernanceObject& obj, vote_signal_enum_t vote_signal) override + { + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { + if (context().govman != nullptr && context().dmnman != nullptr) { + const auto& tip_mn_list{context().dmnman->GetListAtChainTip()}; + if (auto govobj{context().govman->FindGovernanceObject(obj.GetHash())}) { + const auto count = govobj->GetUniqueVoterCount(tip_mn_list, vote_signal); + return UniqueVoters{.m_regular = count.m_regular, .m_evo = count.m_evo}; + } else { + const auto count = obj.GetUniqueVoterCount(tip_mn_list, vote_signal); + return UniqueVoters{.m_regular = count.m_regular, .m_evo = count.m_evo}; + } + } + return UniqueVoters{}; + }, + [] { return std::nullopt; }); } - std::vector getCurrentVotes(const uint256& hash) override + std::optional> getCurrentVotes(const uint256& hash) override { - if (context().govman != nullptr) { - return context().govman->GetCurrentVotes(hash, COutPoint{}); - } - return {}; + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional> { + if (context().govman != nullptr) { + return context().govman->GetCurrentVotes(hash, COutPoint{}); + } + return std::vector{}; + }, + [] { return std::nullopt; }); } bool existsObj(const uint256& hash) override { @@ -427,28 +538,41 @@ class GOVImpl : public GOV } bool processVoteAndRelay(const CGovernanceVote& vote, std::string& error) override { - if (context().govman != nullptr) { - CGovernanceException exception; - bool result = context().govman->ProcessVoteAndRelay(vote, exception); - if (!result) { - error = exception.GetMessage(); - } - return result; - } - error = "Governance manager not available"; - return false; + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> bool { + if (context().govman != nullptr) { + CGovernanceException exception; + bool result = context().govman->ProcessVoteAndRelay(vote, exception); + if (!result) { + error = exception.GetMessage(); + } + return result; + } + error = "Governance manager not available"; + return false; + }, + [&] { + error = EvoStateUnavailableMessage().original; + return false; + }); } GovernanceInfo getGovernanceInfo() override { GovernanceInfo info; if (context().chainman) { const Consensus::Params& consensusParams = context().chainman->GetConsensus(); + if (context().dmnman) { + info.fundingthreshold = WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { + return static_cast(context().dmnman->GetListAtChainTip().GetCounts().m_valid_weighted / 10); + }, + [] { return std::nullopt; }); + } LOCK(::cs_main); CSuperblock::GetNearestSuperblocksHeights(context().chainman->ActiveHeight(), info.lastsuperblock, info.nextsuperblock); info.governancebudget = CSuperblock::GetPaymentsLimit(info.nextsuperblock); - if (context().dmnman) { - info.fundingthreshold = static_cast(context().dmnman->GetListAtChainTip().GetCounts().m_valid_weighted / 10); - } info.superblockcycle = consensusParams.nSuperblockCycle; info.superblockmaturitywindow = consensusParams.nSuperblockMaturityWindow; info.targetSpacing = consensusParams.nPowTargetSpacing; @@ -473,38 +597,43 @@ class GOVImpl : public GOV } return std::nullopt; } - FundableResult getFundableProposalHashes() override - { - FundableResult result; - if (context().govman != nullptr && context().chainman != nullptr && context().dmnman != nullptr) { - const auto tip_mn_list{context().dmnman->GetListAtChainTip()}; - if (const auto proposals{context().govman->GetApprovedProposals(tip_mn_list)}; !proposals.empty()) { - int32_t last_sb{0}, next_sb{0}; - CAmount budget{0}; - { - LOCK(::cs_main); - CSuperblock::GetNearestSuperblocksHeights(context().chainman->ActiveHeight(), last_sb, next_sb); - budget = CSuperblock::GetPaymentsLimit(next_sb); - } - for (const auto& proposal : proposals) { - UniValue json = proposal->GetJSONObject(); - CAmount payment_amount{0}; - try { - payment_amount = ParsePaymentAmount(json["payment_amount"].getValStr()); - } catch (...) { - continue; - } - if (result.allocated + payment_amount > budget) { - // Budget is saturated, cannot fulfill proposal - continue; + std::optional getFundableProposalHashes() override + { + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { + FundableResult result; + if (context().govman != nullptr && context().chainman != nullptr && context().dmnman != nullptr) { + const auto tip_mn_list{context().dmnman->GetListAtChainTip()}; + if (const auto proposals{context().govman->GetApprovedProposals(tip_mn_list)}; !proposals.empty()) { + int32_t last_sb{0}, next_sb{0}; + CAmount budget{0}; + { + LOCK(::cs_main); + CSuperblock::GetNearestSuperblocksHeights(context().chainman->ActiveHeight(), last_sb, next_sb); + budget = CSuperblock::GetPaymentsLimit(next_sb); + } + for (const auto& proposal : proposals) { + UniValue json = proposal->GetJSONObject(); + CAmount payment_amount{0}; + try { + payment_amount = ParsePaymentAmount(json["payment_amount"].getValStr()); + } catch (...) { + continue; + } + if (result.allocated + payment_amount > budget) { + // Budget is saturated, cannot fulfill proposal + continue; + } + result.allocated += payment_amount; + result.hashes.insert(proposal->GetHash()); + } + return result; } - result.allocated += payment_amount; - result.hashes.insert(proposal->GetHash()); } return result; - } - } - return result; + }, + [] { return std::nullopt; }); } std::optional createProposal(int32_t revision, int64_t created_time, const std::string& data_hex, std::string& error) override @@ -517,33 +646,44 @@ class GOVImpl : public GOV error = "This node is still building its governance collateral index, so it can't submit proposals yet"; return std::nullopt; } - CGovernanceObject govobj(uint256{}, revision, created_time, uint256{}, data_hex); - if (govobj.GetObjectType() != GovernanceObject::PROPOSAL) { - error = "Invalid object type, only proposals can be validated"; - return std::nullopt; - } - std::string strValidationError; - if (!governance::ValidateProposal(data_hex, strValidationError)) { - error = "Invalid proposal data: " + strValidationError; - return std::nullopt; - } - const ChainstateManager& chainman = *Assert(context().chainman); - { - LOCK(::cs_main); - std::string strError; - if (!govobj.IsValidLocally(Assert(context().dmnman)->GetListAtChainTip(), chainman, /*collateral=*/nullptr, - strError, false)) { - error = "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError; + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { + CGovernanceObject govobj(uint256{}, revision, created_time, uint256{}, data_hex); + if (govobj.GetObjectType() != GovernanceObject::PROPOSAL) { + error = "Invalid object type, only proposals can be validated"; + return std::nullopt; + } + std::string strValidationError; + if (!governance::ValidateProposal(data_hex, strValidationError)) { + error = "Invalid proposal data: " + strValidationError; + return std::nullopt; + } + const ChainstateManager& chainman = *Assert(context().chainman); + { + LOCK(::cs_main); + std::string strError; + if (!govobj.IsValidLocally(Assert(context().dmnman)->GetListAtChainTip(), chainman, + /*collateral=*/nullptr, strError, false)) { + error = "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError; + return std::nullopt; + } + } + return govobj; + }, + [&] { + error = EvoStateUnavailableMessage().original; return std::nullopt; - } - } - return govobj; + }); } bool submitProposal(const uint256& parent, int32_t revision, int64_t created_time, const std::string& data_hex, const uint256& fee_txid, std::string& out_object_hash, std::string& error) override { - if (!context().govman || !context().dmnman || !context().chainman) { error = "Governance not available"; return false; } + if (!context().govman || !context().dmnman || !context().chainman) { + error = "Governance not available"; + return false; + } if (!context().govman->IsValid() || !context().gov_collateral_index) { error = "Governance is disabled on this node, so it can't submit proposals"; return false; @@ -552,35 +692,55 @@ class GOVImpl : public GOV error = "This node is still building its governance collateral index, so it can't submit proposals yet"; return false; } - if(!Assert(context().mn_sync)->IsBlockchainSynced()) { error = "Client not synced"; return false; } - const auto mnList = Assert(context().dmnman)->GetListAtChainTip(); - CGovernanceObject govobj(parent, revision, created_time, fee_txid, data_hex); - if (govobj.GetObjectType() == GovernanceObject::TRIGGER) { error = "Submission of triggers is not available"; return false; } - if (govobj.GetObjectType() == GovernanceObject::PROPOSAL) { - std::string strValidationError; - if (!governance::ValidateProposal(data_hex, strValidationError)) { error = "Invalid proposal data: " + strValidationError; return false; } - } - const CTxMemPool& mempool = *Assert(context().mempool); - bool fMissingConfirmations{false}; - { - LOCK2(cs_main, mempool.cs); - std::string strError; - if (!govobj.IsValidLocally(mnList, *Assert(context().chainman), context().gov_collateral_index.get(), - strError, fMissingConfirmations, true) && - !fMissingConfirmations) { - error = "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError; + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> bool { + if (!Assert(context().mn_sync)->IsBlockchainSynced()) { + error = "Client not synced"; + return false; + } + const auto mnList = Assert(context().dmnman)->GetListAtChainTip(); + CGovernanceObject govobj(parent, revision, created_time, fee_txid, data_hex); + if (govobj.GetObjectType() == GovernanceObject::TRIGGER) { + error = "Submission of triggers is not available"; + return false; + } + if (govobj.GetObjectType() == GovernanceObject::PROPOSAL) { + std::string strValidationError; + if (!governance::ValidateProposal(data_hex, strValidationError)) { + error = "Invalid proposal data: " + strValidationError; + return false; + } + } + const CTxMemPool& mempool = *Assert(context().mempool); + bool fMissingConfirmations{false}; + { + LOCK2(cs_main, mempool.cs); + std::string strError; + if (!govobj.IsValidLocally(mnList, *Assert(context().chainman), context().gov_collateral_index.get(), + strError, fMissingConfirmations, true) && + !fMissingConfirmations) { + error = "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError; + return false; + } + } + if (!Assert(context().govman)->MasternodeRateCheck(govobj)) { + error = "Object creation rate limit exceeded"; + return false; + } + if (fMissingConfirmations) { + context().govman->AddPostponedObject(govobj); + context().govman->RelayObject(govobj); + } else { + context().govman->AddGovernanceObject(govobj, ""); + } + out_object_hash = govobj.GetHash().ToString(); + return true; + }, + [&] { + error = EvoStateUnavailableMessage().original; return false; - } - } - if (!Assert(context().govman)->MasternodeRateCheck(govobj)) { error = "Object creation rate limit exceeded"; return false; } - if (fMissingConfirmations) { - context().govman->AddPostponedObject(govobj); - context().govman->RelayObject(govobj); - } else { - context().govman->AddGovernanceObject(govobj, ""); - } - out_object_hash = govobj.GetHash().ToString(); - return true; + }); } void setContext(NodeContext* context) override { @@ -597,22 +757,27 @@ class LLMQImpl : public LLMQ NodeContext& context() { return *Assert(m_context); } public: - CreditPoolCounts getCreditPoolCounts() override - { - CreditPoolCounts ret{}; - if (!context().chainman || !context().special_tx) { - return ret; - } - const auto* pindex{WITH_LOCK(::cs_main, return context().chainman->ActiveChain().Tip())}; - if (!pindex || !pindex->pprev) { - return ret; - } - auto& cpoolman{*context().special_tx->m_cpoolman}; - const auto pool{cpoolman.GetCreditPool(pindex)}; - ret.m_locked = pool.locked; - ret.m_limit = pool.currentLimit; - ret.m_diff = pool.locked - cpoolman.GetCreditPool(pindex->pprev).locked; - return ret; + std::optional getCreditPoolCounts() override + { + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional { + CreditPoolCounts ret{}; + if (!context().chainman || !context().special_tx) { + return ret; + } + const auto* pindex{WITH_LOCK(::cs_main, return context().chainman->ActiveChain().Tip())}; + if (!pindex || !pindex->pprev) { + return ret; + } + auto& cpoolman{*context().special_tx->m_cpoolman}; + const auto pool{cpoolman.GetCreditPool(pindex)}; + ret.m_locked = pool.locked; + ret.m_limit = pool.currentLimit; + ret.m_diff = pool.locked - cpoolman.GetCreditPool(pindex->pprev).locked; + return ret; + }, + [] { return std::nullopt; }); } ChainLockInfo getBestChainLock() override { @@ -652,48 +817,67 @@ class LLMQImpl : public LLMQ return entry.GetTx().IsPlatformTransfer(); })); } - std::vector getQuorumStats() override + std::optional> getQuorumStats() override { - std::vector stats{}; - if (!context().llmq_ctx || !context().llmq_ctx->qman || !context().chainman) { - return stats; - } - const auto* pindex{WITH_LOCK(::cs_main, return context().chainman->ActiveChain().Tip())}; - if (!pindex) { - return stats; - } - for (const auto& type : llmq::GetEnabledQuorumTypes(*context().chainman, pindex)) { - const auto llmq_params{Params().GetLLMQ(type)}; - if (!llmq_params.has_value()) { - continue; - } - const auto quorums{context().llmq_ctx->qman->ScanQuorums(type, pindex, llmq_params->signingActiveQuorumCount)}; - double health{0.0}; - for (const auto& q : quorums) { - size_t numMembers = q->members.size(); - size_t numValidMembers = q->qc->CountValidMembers(); - health += (numMembers > 0) ? (double(numValidMembers) / double(numMembers)) : 0.0; - } - health = quorums.empty() ? 0.0 : (health / quorums.size()); - const int32_t newest_height{(!quorums.empty() && quorums[0]->m_quorum_base_block_index) - ? quorums[0]->m_quorum_base_block_index->nHeight : 0}; - const int32_t expiry_height{(newest_height > 0) - ? newest_height + llmq_params->signingActiveQuorumCount * llmq_params->dkgInterval - : 0}; - stats.emplace_back(QuorumInfo{ - .m_name = std::string(llmq_params->name), - .m_count = quorums.size(), - .m_health = health, - .m_rotates = llmq_params->useRotation, - .m_data_retention_blocks = llmq_params->max_store_depth(), - .m_newest_height = newest_height, - .m_expiry_height = expiry_height, - }); - } - return stats; + return WithActiveEvoView( + context().evodb.get(), __func__, + [&]() -> std::optional> { + std::vector stats{}; + if (!context().llmq_ctx || !context().llmq_ctx->qman || !context().chainman) { + return stats; + } + const auto* pindex{WITH_LOCK(::cs_main, return context().chainman->ActiveChain().Tip())}; + if (!pindex) { + return stats; + } + for (const auto& type : llmq::GetEnabledQuorumTypes(*context().chainman, pindex)) { + const auto llmq_params{Params().GetLLMQ(type)}; + if (!llmq_params.has_value()) { + continue; + } + const auto quorums{ + context().llmq_ctx->qman->ScanQuorums(type, pindex, llmq_params->signingActiveQuorumCount)}; + double health{0.0}; + for (const auto& q : quorums) { + size_t numMembers = q->members.size(); + size_t numValidMembers = q->qc->CountValidMembers(); + health += (numMembers > 0) ? (double(numValidMembers) / double(numMembers)) : 0.0; + } + health = quorums.empty() ? 0.0 : (health / quorums.size()); + const int32_t newest_height{(!quorums.empty() && quorums[0]->m_quorum_base_block_index) + ? quorums[0]->m_quorum_base_block_index->nHeight + : 0}; + const int32_t expiry_height{ + (newest_height > 0) ? newest_height + llmq_params->signingActiveQuorumCount * llmq_params->dkgInterval + : 0}; + stats.emplace_back(QuorumInfo{ + .m_name = std::string(llmq_params->name), + .m_count = quorums.size(), + .m_health = health, + .m_rotates = llmq_params->useRotation, + .m_data_retention_blocks = llmq_params->max_store_depth(), + .m_newest_height = newest_height, + .m_expiry_height = expiry_height, + }); + } + return stats; + }, + [] { return std::nullopt; }); } PlatformQuorumResult getPlatformQuorum(uint8_t llmq_type, const uint256& quorum_hash, uint32_t core_chain_locked_height) override + { + // Unbound, or unable to read its own Evo state, this node cannot tell. + return WithActiveEvoView( + context().evodb.get(), __func__, + [&] { return LookupPlatformQuorum(llmq_type, quorum_hash, core_chain_locked_height); }, + [] { return PlatformQuorumResult{}; }); + } + +private: + //! getPlatformQuorum in the Evo view the calling thread is bound to. + PlatformQuorumResult LookupPlatformQuorum(uint8_t llmq_type, const uint256& quorum_hash, + uint32_t core_chain_locked_height) { PlatformQuorumResult invalid{PlatformQuorumStatus::INVALID, {}}; const auto type{static_cast(llmq_type)}; @@ -705,7 +889,8 @@ class LLMQImpl : public LLMQ return invalid; } const int signed_height{static_cast(core_chain_locked_height)}; - if (!context().llmq_ctx || !context().llmq_ctx->quorum_block_processor || !context().chainman) { + if (!context().llmq_ctx || !context().llmq_ctx->quorum_block_processor || !context().chainman || + !context().evodb) { return {}; } // Only a ChainLock whose block is known can lock part of the active chain; the best height may @@ -718,6 +903,11 @@ class LLMQImpl : public LLMQ } LOCK(::cs_main); + // Only the active chain of the bound view can answer: a snapshot + // published since answers the next call. + if (context().evodb->ActiveView() != context().evodb->CurrentView()) { + return {}; + } const CChain& active{context().chainman->ActiveChain()}; const CBlockIndex* tip{active.Tip()}; if (!tip || signed_height > tip->nHeight) { @@ -755,6 +945,8 @@ class LLMQImpl : public LLMQ } return {PlatformQuorumStatus::FOUND, qc.quorumPublicKey.ToByteVector()}; } + +public: std::vector getInstantSendLock(const uint256& txid) override { if (!context().isman) { @@ -1169,10 +1361,15 @@ class NodeImpl : public Node return m_context->active_ctx != nullptr; } bool isLoadingBlocks() override { return chainman().m_blockman.LoadingBlocks(); } - bool isV24Active() override + std::optional isV24Active() override { - LOCK(::cs_main); - return DeploymentActiveAfter(chainman().ActiveChain().Tip(), chainman(), Consensus::DEPLOYMENT_V24); + return WithActiveEvoView( + m_context->evodb.get(), __func__, + [&]() -> std::optional { + LOCK(::cs_main); + return DeploymentActiveAfter(chainman().ActiveChain().Tip(), chainman(), Consensus::DEPLOYMENT_V24); + }, + [] { return std::nullopt; }); } void setNetworkActive(bool active) override { @@ -1509,21 +1706,27 @@ class ChainImpl : public Chain if (m_node.chainlocks == nullptr) return false; return m_node.chainlocks->HasChainLock(height, hash); } - std::vector listMNCollaterials(const std::vector>& outputs) override + std::optional> listMNCollaterials( + const std::vector>& outputs) override { - const CBlockIndex *tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()); - CDeterministicMNList mnList{}; - if (tip != nullptr && m_node.dmnman != nullptr) { - mnList = m_node.dmnman->GetListForBlock(tip); - } - std::vector listRet; - for (const auto& [tx, index]: outputs) { - COutPoint nextOut{tx->GetHash(), index}; - if (CDeterministicMNManager::IsProTxWithCollateral(tx, index) || mnList.HasMNByCollateral(nextOut)) { - listRet.emplace_back(nextOut); - } - } - return listRet; + return WithActiveEvoView( + m_node.evodb.get(), __func__, + [&]() -> std::optional> { + const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()); + CDeterministicMNList mnList{}; + if (tip != nullptr && m_node.dmnman != nullptr) { + mnList = m_node.dmnman->GetListForBlock(tip); + } + std::vector listRet; + for (const auto& [tx, index] : outputs) { + COutPoint nextOut{tx->GetHash(), index}; + if (CDeterministicMNManager::IsProTxWithCollateral(tx, index) || mnList.HasMNByCollateral(nextOut)) { + listRet.emplace_back(nextOut); + } + } + return listRet; + }, + [] { return std::nullopt; }); } interfaces::CoinJoin::Loader* coinJoinLoader() override { return m_node.coinjoin_loader.get(); } bool findBlock(const uint256& hash, const FoundBlock& block) override @@ -1671,10 +1874,15 @@ class ChainImpl : public Chain if (!m_node.mempool || !m_node.mempool->m_require_standard) return false; return !IsStandardSpecialTx(*tx, reason); } - bool isV24Active() override + std::optional isV24Active() override { - LOCK(::cs_main); - return DeploymentActiveAfter(chainman().ActiveChain().Tip(), chainman(), Consensus::DEPLOYMENT_V24); + return WithActiveEvoView( + m_node.evodb.get(), __func__, + [&]() -> std::optional { + LOCK(::cs_main); + return DeploymentActiveAfter(chainman().ActiveChain().Tip(), chainman(), Consensus::DEPLOYMENT_V24); + }, + [] { return std::nullopt; }); } bool havePruned() override { diff --git a/src/node/miner.cpp b/src/node/miner.cpp index dbcdba66480b..f94e2306731f 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -211,6 +211,7 @@ void BlockAssembler::FillBlockPayments(CMutableTransaction& txNew, const CBlockI std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn) { + const EvoViewScope evo_view{m_chainstate.EvoView()}; const auto time_start{SteadyClock::now()}; resetBlock(); diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index ef42f759101e..e7552ae64641 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -1952,7 +1952,9 @@ void BitcoinGUI::updateGovernanceCycleIcon() ? tr("~%1 (%2 blocks) left for superblock").arg(remaining_str).arg(remaining_blocks) : tr("~%1 (%2 blocks) left for voting").arg(voting_str).arg(voting_remaining))}; const auto tooltip2{[&]() { - const auto allocated_budget{m_node.gov().getFundableProposalHashes().allocated}; + const auto fundable{m_node.gov().getFundableProposalHashes()}; + if (!fundable) return tr("Budget commitment is not available yet"); + const auto allocated_budget{fundable->allocated}; const auto budget_pct{gov_info.governancebudget > 0 ? static_cast(static_cast(allocated_budget) / static_cast(gov_info.governancebudget) * 100.0) : 0}; diff --git a/src/qt/clientfeeds.cpp b/src/qt/clientfeeds.cpp index ce2e118640b6..e9924bb90db5 100644 --- a/src/qt/clientfeeds.cpp +++ b/src/qt/clientfeeds.cpp @@ -91,8 +91,13 @@ void CreditPoolFeed::fetch() return; } + // Unavailable counts keep the current data until a later fetch. + const auto counts{m_client_model.node().llmq().getCreditPoolCounts()}; + if (!counts) { + return; + } auto ret = std::make_shared(); - ret->m_counts = m_client_model.node().llmq().getCreditPoolCounts(); + ret->m_counts = *counts; ret->m_pending_unlocks = m_client_model.node().llmq().getPendingAssetUnlocks(); setData(std::move(ret)); @@ -132,8 +137,12 @@ void QuorumFeed::fetch() return; } + auto quorums{m_client_model.node().llmq().getQuorumStats()}; + if (!quorums) { + return; + } auto ret = std::make_shared(); - ret->m_quorums = m_client_model.node().llmq().getQuorumStats(); + ret->m_quorums = std::move(*quorums); setData(std::move(ret)); } @@ -220,22 +229,31 @@ void ProposalFeed::fetch() const auto nMinQuorum = static_cast(Params().GetConsensus().nGovernanceMinQuorum); ret->m_abs_vote_req = static_cast(std::max(nMinQuorum, data_mn->m_counts.m_valid_weighted / 10)); ret->m_gov_info = m_client_model.node().gov().getGovernanceInfo(); + auto fundable{m_client_model.node().gov().getFundableProposalHashes()}; + // Proposals are judged against the masternode list; without it, keep the + // current data until a later fetch. + if (!ret->m_gov_info.fundingthreshold || !fundable) { + return; + } std::vector govObjList; m_client_model.getAllGovernanceObjects(govObjList); for (const auto& govObj : govObjList) { if (govObj.GetObjectType() != GovernanceObject::PROPOSAL) { continue; // Skip triggers. } - ret->m_proposals.emplace_back(std::make_shared(m_client_model, govObj, ret->m_gov_info, ret->m_gov_info.requiredConfs, - /*is_broadcast=*/true)); + auto proposal{std::make_shared(m_client_model, govObj, ret->m_gov_info, ret->m_gov_info.requiredConfs, + /*is_broadcast=*/true)}; const auto voters = m_client_model.node().gov().getObjUniqueVoters(govObj, VOTE_SIGNAL_FUNDING); - ret->m_max_regular_voters = std::max(ret->m_max_regular_voters, voters.m_regular); - ret->m_max_evo_voters = std::max(ret->m_max_evo_voters, voters.m_evo); + if (!proposal->hasVotes() || !voters) { + return; + } + ret->m_proposals.emplace_back(std::move(proposal)); + ret->m_max_regular_voters = std::max(ret->m_max_regular_voters, voters->m_regular); + ret->m_max_evo_voters = std::max(ret->m_max_evo_voters, voters->m_evo); } - auto fundable{m_client_model.node().gov().getFundableProposalHashes()}; - ret->m_fundable_hashes = std::move(fundable.hashes); - ret->m_allocated = fundable.allocated; + ret->m_fundable_hashes = std::move(fundable->hashes); + ret->m_allocated = fundable->allocated; setData(std::move(ret)); } diff --git a/src/qt/masternodedialogs.cpp b/src/qt/masternodedialogs.cpp index 880d94127115..d044dc3411b5 100644 --- a/src/qt/masternodedialogs.cpp +++ b/src/qt/masternodedialogs.cpp @@ -340,12 +340,6 @@ void MasternodeActionDialog::finishSubmission(MasternodeOperationRunner::Submiss accept(); } -UpdateServiceDialog::UpdateServiceDialog(interfaces::Node& node, WalletModel* wallet_model, - const MasternodeEntry& entry, QWidget* parent) : - UpdateServiceDialog(node, wallet_model, entry, node.evo().getProviderTxCapabilities(), parent) -{ -} - UpdateServiceDialog::UpdateServiceDialog(interfaces::Node& node, WalletModel* wallet_model, const MasternodeEntry& entry, interfaces::ProviderTxCapabilities capabilities, QWidget* parent) : MasternodeActionDialog(node, wallet_model, entry, parent), @@ -521,12 +515,6 @@ void UpdateServiceDialog::submit() }); } -UpdateRegistrarDialog::UpdateRegistrarDialog(interfaces::Node& node, WalletModel* wallet_model, - const MasternodeEntry& entry, QWidget* parent) : - UpdateRegistrarDialog(node, wallet_model, entry, node.evo().getProviderTxCapabilities(), parent) -{ -} - UpdateRegistrarDialog::UpdateRegistrarDialog(interfaces::Node& node, WalletModel* wallet_model, const MasternodeEntry& entry, interfaces::ProviderTxCapabilities capabilities, QWidget* parent) : diff --git a/src/qt/masternodedialogs.h b/src/qt/masternodedialogs.h index a997cbb1e43b..4ee5d17bbdbf 100644 --- a/src/qt/masternodedialogs.h +++ b/src/qt/masternodedialogs.h @@ -137,15 +137,13 @@ class UpdateServiceDialog : public MasternodeActionDialog public: UpdateServiceDialog(interfaces::Node& node, WalletModel* wallet_model, const MasternodeEntry& entry, - QWidget* parent = nullptr); + interfaces::ProviderTxCapabilities capabilities, QWidget* parent = nullptr); protected: void validate() override; void submit() override; private: - UpdateServiceDialog(interfaces::Node& node, WalletModel* wallet_model, const MasternodeEntry& entry, - interfaces::ProviderTxCapabilities capabilities, QWidget* parent); std::optional buildNetInfo(QString& error) const; std::optional buildRequest(const CBLSSecretKey& operator_key, QString& error) const; @@ -173,15 +171,13 @@ class UpdateRegistrarDialog : public MasternodeActionDialog public: UpdateRegistrarDialog(interfaces::Node& node, WalletModel* wallet_model, const MasternodeEntry& entry, - QWidget* parent = nullptr); + interfaces::ProviderTxCapabilities capabilities, QWidget* parent = nullptr); protected: void validate() override; void submit() override; private: - UpdateRegistrarDialog(interfaces::Node& node, WalletModel* wallet_model, const MasternodeEntry& entry, - interfaces::ProviderTxCapabilities capabilities, QWidget* parent); std::optional buildRequest(QString& error) const; bool operatorChanged() const; bool votingChanged() const; diff --git a/src/qt/masternodelist.cpp b/src/qt/masternodelist.cpp index 312f4597de82..b649c779263e 100644 --- a/src/qt/masternodelist.cpp +++ b/src/qt/masternodelist.cpp @@ -254,8 +254,12 @@ void MasternodeList::updateRegistrationAvailability() } // isV24Active() takes cs_main and this runs on every block; activation is - // monotonic, so ask only until it is - if (!m_v24_active && clientModel != nullptr) m_v24_active = clientModel->node().isV24Active(); + // monotonic, so ask only until it is. An unknown state asks again later. + std::optional v24_state{m_v24_active}; + if (!m_v24_active && clientModel != nullptr) { + v24_state = clientModel->node().isV24Active(); + m_v24_active = v24_state.value_or(false); + } const bool v24_active{clientModel != nullptr && m_v24_active}; const bool can_shared{can_register && v24_active}; ui->btnSharedMasternode->setEnabled(can_shared); @@ -265,6 +269,8 @@ void MasternodeList::updateRegistrationAvailability() ui->btnSharedMasternode->setToolTip(tr("Managing shared masternodes requires a wallet with private keys.")); } else if (clientModel == nullptr) { ui->btnSharedMasternode->setToolTip(tr("Shared masternode management is unavailable until the node is ready.")); + } else if (!v24_state) { + ui->btnSharedMasternode->setToolTip(MasternodeWidgetUtil::masternodeStateUnavailableText()); } else if (!v24_active) { ui->btnSharedMasternode->setToolTip(tr("Shared masternodes require the v24 hard fork, which is not active on this network yet.")); } else { @@ -478,10 +484,22 @@ const MasternodeEntry* MasternodeList::selectedEntryForDialog() return entry != nullptr && clientModel != nullptr && walletModel != nullptr ? entry : nullptr; } +std::optional MasternodeList::providerTxCapabilities() +{ + auto capabilities{clientModel->node().evo().getProviderTxCapabilities()}; + if (!capabilities) { + QMessageBox::warning(this, tr("Masternode state unavailable"), + MasternodeWidgetUtil::masternodeStateUnavailableText()); + } + return capabilities; +} + void MasternodeList::onUpdateService() { if (const auto* entry{selectedEntryForDialog()}) { - UpdateServiceDialog dialog(clientModel->node(), walletModel, *entry, this); + const auto capabilities{providerTxCapabilities()}; + if (!capabilities) return; + UpdateServiceDialog dialog(clientModel->node(), walletModel, *entry, *capabilities, this); dialog.exec(); } } @@ -490,7 +508,9 @@ void MasternodeList::onUpdateRegistrar() { if (const auto* entry{selectedEntryForDialog()}; entry != nullptr && walletModel->wallet().isSpendable(PKHash(entry->keyIdOwnerRaw()))) { - UpdateRegistrarDialog dialog(clientModel->node(), walletModel, *entry, this); + const auto capabilities{providerTxCapabilities()}; + if (!capabilities) return; + UpdateRegistrarDialog dialog(clientModel->node(), walletModel, *entry, *capabilities, this); dialog.exec(); } } @@ -574,10 +594,11 @@ void MasternodeList::updateMasternodeList() return; } - std::set setOutpts; - for (const auto& outpt : walletModel->wallet().listProTxCoins()) { - setOutpts.emplace(outpt); - } + // Without the wallet's collaterals ownership cannot be told; keep the + // current list until a later update. + const auto protx_coins{walletModel->wallet().listProTxCoins()}; + if (!protx_coins) return; + const std::set setOutpts{protx_coins->begin(), protx_coins->end()}; QSet owned_mns; QHash my_share_counts; diff --git a/src/qt/masternodelist.h b/src/qt/masternodelist.h index 332aafcbb5d6..994c682670a5 100644 --- a/src/qt/masternodelist.h +++ b/src/qt/masternodelist.h @@ -5,6 +5,7 @@ #ifndef BITCOIN_QT_MASTERNODELIST_H #define BITCOIN_QT_MASTERNODELIST_H +#include #include #include @@ -17,6 +18,7 @@ #include #include +#include #include class ClientModel; @@ -142,6 +144,8 @@ class MasternodeList : public QWidget const MasternodeEntry* GetSelectedEntry(); const MasternodeEntry* selectedEntryForDialog(); + //! The provider transaction rules, or nullopt after telling the user they are not available yet + std::optional providerTxCapabilities(); Q_SIGNALS: void doubleClicked(const QModelIndex&); diff --git a/src/qt/masternodewidgets.cpp b/src/qt/masternodewidgets.cpp index d1fdc1d6b395..82cf13a64c1e 100644 --- a/src/qt/masternodewidgets.cpp +++ b/src/qt/masternodewidgets.cpp @@ -56,6 +56,11 @@ bool isP2PKHorP2SHAddress(const QString& address) return std::holds_alternative(dest) || std::holds_alternative(dest); } +QString masternodeStateUnavailableText() +{ + return QObject::tr("Masternode state is not available on this node yet. Try again later."); +} + QLabel* makeTitle(const QString& text, QWidget* parent, double point_size) { auto* label{new QLabel(text, parent)}; diff --git a/src/qt/masternodewidgets.h b/src/qt/masternodewidgets.h index 2d527ad6d8a7..6818061ff2e3 100644 --- a/src/qt/masternodewidgets.h +++ b/src/qt/masternodewidgets.h @@ -44,6 +44,9 @@ bool isP2PKHorP2SHAddress(const QString& address); //! translated reason in `error` QString freshAddress(WalletModel* wallet_model, QString& error); +//! Shown when the node cannot evaluate its masternode state yet +QString masternodeStateUnavailableText(); + //! Spacing tokens (px) keeping one vertical rhythm across the dialogs' pages constexpr int GROUP_SPACING{16}; //!< between top-level groups of a page constexpr int TITLE_SPACING{8}; //!< between a group's title and its body diff --git a/src/qt/masternodewizard.cpp b/src/qt/masternodewizard.cpp index 1ab89e3c07d7..c08fc8b691e6 100644 --- a/src/qt/masternodewizard.cpp +++ b/src/qt/masternodewizard.cpp @@ -63,10 +63,21 @@ using MasternodeWidgetUtil::makePageLayout; using MasternodeWidgetUtil::makePageTitle; using MasternodeWidgetUtil::makeValue; -std::set RegisteredCollaterals(interfaces::Wallet& wallet) +//! Whether the provider transaction rules still have `version`. Rules this +//! node cannot evaluate yet count as changed. +bool CurrentProviderVersionIs(interfaces::Node& node, uint16_t version) +{ + const auto capabilities{node.evo().getProviderTxCapabilities()}; + return capabilities && capabilities->version == version; +} + +//! The wallet's coins registered as masternode collateral, or nullopt when the +//! masternode list is not available +std::optional> RegisteredCollaterals(interfaces::Wallet& wallet) { const auto registered{wallet.listProTxCoins()}; - return {registered.begin(), registered.end()}; + if (!registered) return std::nullopt; + return std::set{registered->begin(), registered->end()}; } //! Formats collateral amounts, which are whole coins in every display unit, so @@ -686,7 +697,8 @@ bool RegisterMasternodeWizard::isEvo() const bool RegisterMasternodeWizard::usesExtendedAddresses() const { - return m_node.evo().getProviderTxCapabilities().extended_addresses; + const auto capabilities{m_node.evo().getProviderTxCapabilities()}; + return capabilities && capabilities->extended_addresses; } bool RegisterMasternodeWizard::isExternalCollateral() const @@ -846,10 +858,13 @@ void RegisterMasternodeWizard::enterPage(Page page) } break; case PagePlatform: { + // Without the rules, no version is recorded and validating the page + // reports them unavailable. const auto capabilities{m_node.evo().getProviderTxCapabilities()}; - const bool v3{capabilities.extended_addresses}; - m_platform_provider_version = capabilities.version; - m_platform_ipv4_optional = capabilities.ipv4_optional; + if (!capabilities) showError(MasternodeWidgetUtil::masternodeStateUnavailableText()); + const bool v3{capabilities && capabilities->extended_addresses}; + m_platform_provider_version = capabilities ? capabilities->version : 0; + m_platform_ipv4_optional = capabilities && capabilities->ipv4_optional; m_platform_extended_addresses = v3; m_platform_addr_box->setVisible(v3); m_platform_port_box->setVisible(!v3); @@ -919,7 +934,9 @@ bool RegisterMasternodeWizard::validatePage(Page page, QString& err) break; case PageService: { const QStringList list{MasternodeWidgetUtil::tokenizeEndpointList(m_service_edit->text())}; - if (list.isEmpty() && isEvo() && !usesExtendedAddresses()) { + if (list.isEmpty() && isEvo() && !m_node.evo().getProviderTxCapabilities()) { + err = MasternodeWidgetUtil::masternodeStateUnavailableText(); + } else if (list.isEmpty() && isEvo() && !usesExtendedAddresses()) { err = tr("EvoNodes need at least one service address to carry the Platform ports before v24 " "activation."); } else if (!isEvo()) { @@ -927,9 +944,12 @@ bool RegisterMasternodeWizard::validatePage(Page page, QString& err) } else if (!list.isEmpty()) { interfaces::ProviderNetInfo core_only; for (const QString& entry : list) core_only.core_p2p.push_back(entry.toStdString()); - const auto capabilities{m_node.evo().getProviderTxCapabilities()}; - if (const auto error{m_node.evo().validateProviderNetInfo( - core_only, MnType::Regular, capabilities.version, capabilities.ipv4_optional, /*optional=*/true)}) { + if (const auto capabilities{m_node.evo().getProviderTxCapabilities()}; !capabilities) { + err = MasternodeWidgetUtil::masternodeStateUnavailableText(); + } else if (const auto error{m_node.evo().validateProviderNetInfo(core_only, MnType::Regular, + capabilities->version, + capabilities->ipv4_optional, + /*optional=*/true)}) { err = QString::fromStdString(error->message.translated); } } @@ -1049,14 +1069,21 @@ interfaces::ProviderNetInfo RegisterMasternodeWizard::providerNetInfo() const bool RegisterMasternodeWizard::validateProviderNetInfo(bool optional, QString& err) const { // The Platform page pins the rules it was entered with, so typing there doesn't wait for cs_main - const interfaces::ProviderTxCapabilities pinned{.version = m_platform_provider_version, - .extended_addresses = m_platform_extended_addresses, - .ipv4_optional = m_platform_ipv4_optional}; - const auto capabilities{isEvo() && m_platform_provider_version != 0 ? pinned - : m_node.evo().getProviderTxCapabilities()}; + std::optional capabilities; + if (isEvo() && m_platform_provider_version != 0) { + capabilities = interfaces::ProviderTxCapabilities{.version = m_platform_provider_version, + .extended_addresses = m_platform_extended_addresses, + .ipv4_optional = m_platform_ipv4_optional}; + } else { + capabilities = m_node.evo().getProviderTxCapabilities(); + } + if (!capabilities) { + err = MasternodeWidgetUtil::masternodeStateUnavailableText(); + return false; + } const MnType type{isEvo() ? MnType::Evo : MnType::Regular}; - if (const auto error{m_node.evo().validateProviderNetInfo(providerNetInfo(), type, capabilities.version, - capabilities.ipv4_optional, optional)}) { + if (const auto error{m_node.evo().validateProviderNetInfo(providerNetInfo(), type, capabilities->version, + capabilities->ipv4_optional, optional)}) { err = QString::fromStdString(error->message.translated); return false; } @@ -1186,7 +1213,14 @@ void RegisterMasternodeWizard::refreshCollateralCandidates() m_col_utxo_none->setVisible(true); return; } - refreshCollateralCandidates(RegisteredCollaterals(m_walletModel->wallet())); + const auto registered{RegisteredCollaterals(m_walletModel->wallet())}; + if (!registered) { + // Keep the current candidates: a registered collateral cannot be told + // from a free one yet. + showError(MasternodeWidgetUtil::masternodeStateUnavailableText()); + return; + } + refreshCollateralCandidates(*registered); } void RegisterMasternodeWizard::refreshCollateralCandidates(const std::set& registered_collaterals) @@ -1391,7 +1425,12 @@ std::optional RegisterMasternodeWizard: const COutPoint outpoint{hash, static_cast( m_col_utxo_combo->itemData(m_col_utxo_combo->currentIndex(), VOUT_ROLE).toInt())}; - if (RegisteredCollaterals(m_walletModel->wallet()).count(outpoint) != 0) { + const auto registered{RegisteredCollaterals(m_walletModel->wallet())}; + if (!registered) { + error = MasternodeWidgetUtil::masternodeStateUnavailableText(); + return std::nullopt; + } + if (registered->count(outpoint) != 0) { error = tr("The selected collateral output is already used by another masternode."); return std::nullopt; } @@ -1498,7 +1537,7 @@ void RegisterMasternodeWizard::startRegistration(bool skip_confirmation) goToPage(PageSecret); return; } - if (isEvo() && m_node.evo().getProviderTxCapabilities().version != m_platform_provider_version) { + if (isEvo() && !CurrentProviderVersionIs(m_node, m_platform_provider_version)) { goToPage(PagePlatform); showError(tr("The network's provider-transaction rules changed while this wizard was open. Review the " "Platform services page again before registering.")); @@ -1541,7 +1580,7 @@ void RegisterMasternodeWizard::startRegistration(bool skip_confirmation) void RegisterMasternodeWizard::startSubmit(bool skip_confirmation) { if (m_walletModel == nullptr || !m_runner || !m_prepared_tx) return; - if (isEvo() && m_node.evo().getProviderTxCapabilities().version != m_platform_provider_version) { + if (isEvo() && !CurrentProviderVersionIs(m_node, m_platform_provider_version)) { showError(tr("The network's provider-transaction rules changed while the collateral signature was being " "collected. Discard this prepared registration and review the Platform services page again.")); return; diff --git a/src/qt/proposallist.cpp b/src/qt/proposallist.cpp index 9b5f9e0c363e..1daf3e90c62c 100644 --- a/src/qt/proposallist.cpp +++ b/src/qt/proposallist.cpp @@ -258,16 +258,23 @@ void ProposalList::updateProposalList() // Include unrelayed wallet proposals (0 confs, not yet broadcast) for (const auto& obj : getWalletProposals(/*pending=*/true)) { CGovernanceObject govObj(obj.hashParent, obj.revision, obj.time, obj.collateralHash, obj.GetDataAsHexString()); - ret.m_proposals.emplace_back(std::make_shared(*clientModel, govObj, ret.m_gov_info, queryCollateralDepth(obj.collateralHash), - /*is_broadcast=*/false)); + auto proposal{std::make_shared(*clientModel, govObj, ret.m_gov_info, + queryCollateralDepth(obj.collateralHash), + /*is_broadcast=*/false)}; + // Without vote counts keep the current list until a later update. + if (!proposal->hasVotes()) return; + ret.m_proposals.emplace_back(std::move(proposal)); } } else if (m_proposal_source == ProposalSource::Local) { // Discard network proposals and only include wallet proposals ret.m_proposals.clear(); for (const auto& obj : getWalletProposals(/*pending=*/std::nullopt)) { CGovernanceObject govObj(obj.hashParent, obj.revision, obj.time, obj.collateralHash, obj.GetDataAsHexString()); - ret.m_proposals.emplace_back(std::make_shared(*clientModel, govObj, ret.m_gov_info, queryCollateralDepth(obj.collateralHash), - /*is_broadcast=*/clientModel->node().gov().existsObj(obj.GetHash()))); + auto proposal{ + std::make_shared(*clientModel, govObj, ret.m_gov_info, queryCollateralDepth(obj.collateralHash), + /*is_broadcast=*/clientModel->node().gov().existsObj(obj.GetHash()))}; + if (!proposal->hasVotes()) return; + ret.m_proposals.emplace_back(std::move(proposal)); } } diff --git a/src/qt/proposalmodel.cpp b/src/qt/proposalmodel.cpp index 43dd3147182b..1d1b562182ca 100644 --- a/src/qt/proposalmodel.cpp +++ b/src/qt/proposalmodel.cpp @@ -46,8 +46,7 @@ QString formatProposalAmount(const BitcoinUnit& unit, const CAmount& amount) } // anonymous namespace Proposal::Proposal(ClientModel& client_model, const CGovernanceObject& govObj, - const interfaces::GOV::GovernanceInfo& govInfo, int collateral_confs, - bool is_broadcast) : + const interfaces::GOV::GovernanceInfo& govInfo, int collateral_confs, bool is_broadcast) : m_is_broadcast{is_broadcast}, m_block_height{client_model.getNumBlocks()}, m_collateral_confs{collateral_confs}, @@ -57,7 +56,8 @@ Proposal::Proposal(ClientModel& client_model, const CGovernanceObject& govObj, m_hash_object{QString::fromStdString(govObj.GetHash().ToString())}, m_hash_parent{QString::fromStdString(govObj.Object().hashParent.ToString())}, m_json{QString::fromStdString(govObj.GetInnerJson().write(2))}, - m_objHash{govObj.GetHash()} + m_objHash{govObj.GetHash()}, + m_votes{client_model.node().gov().getObjVotes(govObj, VOTE_SIGNAL_FUNDING)} { UniValue prop_data; if (!prop_data.read(govObj.GetDataAsPlainString())) { @@ -65,11 +65,16 @@ Proposal::Proposal(ClientModel& client_model, const CGovernanceObject& govObj, } m_funded_height = client_model.node().gov().getProposalFundedHeight(govObj.GetHash()); - m_votes = client_model.node().gov().getObjVotes(govObj, VOTE_SIGNAL_FUNDING); - for (const auto& vote : client_model.node().gov().getCurrentVotes(govObj.GetHash())) { - if (vote.GetSignal() == VOTE_SIGNAL_FUNDING) { - m_current_votes.emplace(vote.GetMasternodeOutpoint(), vote); + // Without the masternode list the votes are unknown, not absent: the + // proposal then reports no votes, and its feed keeps its current data. + if (const auto current_votes{client_model.node().gov().getCurrentVotes(govObj.GetHash())}) { + for (const auto& vote : *current_votes) { + if (vote.GetSignal() == VOTE_SIGNAL_FUNDING) { + m_current_votes.emplace(vote.GetMasternodeOutpoint(), vote); + } } + } else { + m_votes.reset(); } if (const UniValue& titleValue = prop_data.find_value("name"); titleValue.isStr()) { @@ -182,7 +187,8 @@ ProposalStatus Proposal::status(bool is_fundable) const if (m_block_height % m_gov_info.superblockcycle >= m_gov_info.superblockcycle - m_gov_info.superblockmaturitywindow) { return is_fundable ? ProposalStatus::Passing : ProposalStatus::Failing; } - if (getAbsoluteYesCount() < m_gov_info.fundingthreshold) { + // Only proposals judged against a known masternode list are listed. + if (Assume(m_gov_info.fundingthreshold) && getAbsoluteYesCount() < *m_gov_info.fundingthreshold) { return ProposalStatus::Voting; } return is_fundable ? ProposalStatus::Passing : ProposalStatus::Unfunded; diff --git a/src/qt/proposalmodel.h b/src/qt/proposalmodel.h index 0a7a8c832765..4b6f1424b1f1 100644 --- a/src/qt/proposalmodel.h +++ b/src/qt/proposalmodel.h @@ -9,6 +9,7 @@ #include #include #include +#include #include @@ -47,7 +48,6 @@ class Proposal int m_block_height{0}; int m_collateral_confs{0}; interfaces::GOV::GovernanceInfo m_gov_info; - interfaces::GOV::Votes m_votes; std::map m_current_votes; QDateTime m_date_collateral{}; QDateTime m_endDate{}; @@ -61,6 +61,14 @@ class Proposal QString m_url{}; std::optional m_funded_height{}; uint256 m_objHash{}; + //! Nullopt when the masternode list to count votes against is not available + std::optional m_votes; + + interfaces::GOV::Votes votes() const + { + Assume(m_votes.has_value()); + return m_votes.value_or(interfaces::GOV::Votes{}); + } public: explicit Proposal(ClientModel& client_model, const CGovernanceObject& _govObj, @@ -76,10 +84,13 @@ class Proposal int paymentsRemaining() const; int paymentsRequested() const; int requiredConfs() const; - int32_t getAbsoluteYesCount() const { return m_votes.m_yes - m_votes.m_no; } - int32_t getAbstainCount() const { return m_votes.m_abs; } - int32_t getNoCount() const { return m_votes.m_no; } - int32_t getYesCount() const { return m_votes.m_yes; } + //! Whether the vote counts are known. Only proposals with known counts are + //! listed, so the counts below are read only for those. + bool hasVotes() const { return m_votes.has_value(); } + int32_t getAbsoluteYesCount() const { return votes().m_yes - votes().m_no; } + int32_t getAbstainCount() const { return votes().m_abs; } + int32_t getNoCount() const { return votes().m_no; } + int32_t getYesCount() const { return votes().m_yes; } ProposalStatus status(bool is_fundable) const; QDateTime collateralDate() const { return m_date_collateral; } QDateTime endDate() const { return m_endDate; } diff --git a/src/qt/sharedmncreatedialog.cpp b/src/qt/sharedmncreatedialog.cpp index a45870140e99..14ece3fceb52 100644 --- a/src/qt/sharedmncreatedialog.cpp +++ b/src/qt/sharedmncreatedialog.cpp @@ -185,7 +185,8 @@ QString ShareName(const MnShareSession& session, int index) } //! Why the network would refuse these service addresses because a registered -//! masternode already uses one of them (empty = none is in use) +//! masternode already uses one of them, or that this cannot be checked yet +//! (empty = none is in use) QString ServiceInUseProblem(interfaces::Node& node, const QString& services) { interfaces::ProviderNetInfo net_info; @@ -193,12 +194,15 @@ QString ServiceInUseProblem(interfaces::Node& node, const QString& services) net_info.core_p2p.push_back(entry.toStdString()); } const auto capabilities{node.evo().getProviderTxCapabilities()}; - const auto in_use{node.evo().findProviderNetInfoInUse(net_info, MnType::Regular, capabilities.version, - capabilities.ipv4_optional)}; - if (!in_use) return {}; + if (!capabilities) return MasternodeWidgetUtil::masternodeStateUnavailableText(); + const auto result{node.evo().findProviderNetInfoInUse(net_info, MnType::Regular, capabilities->version, + capabilities->ipv4_optional)}; + const auto* in_use{std::get_if>(&result)}; + if (!in_use) return MasternodeWidgetUtil::masternodeStateUnavailableText(); + if (!*in_use) return {}; return SharedMnCreateDialog::tr("%1 is already the service address of a registered masternode. Every service " "address must be unique on the network.") - .arg(QString::fromStdString(*in_use)); + .arg(QString::fromStdString(**in_use)); } } // anonymous namespace @@ -1271,8 +1275,8 @@ void SharedMnCreateDialog::enterPage(Page page) QString gate; if (m_wallet_model == nullptr) { gate = tr("No wallet is available."); - } else if (!m_v24_active) { - gate = SharedMnV24InactiveMessage(); + } else if (!m_v24_active.value_or(false)) { + gate = SharedMnV24InactiveMessage(m_v24_active); } else if (!canSign()) { gate = tr("This wallet cannot sign. You can view, but not take part."); } @@ -1380,9 +1384,11 @@ bool SharedMnCreateDialog::validatePage(Page page, QString& err) for (const QString& entry : MasternodeWidgetUtil::tokenizeEndpointList(m_service_edit->text())) { net_info.core_p2p.push_back(entry.toStdString()); } - const auto capabilities{m_node.evo().getProviderTxCapabilities()}; - if (const auto error{m_node.evo().validateProviderNetInfo(net_info, MnType::Regular, capabilities.version, - capabilities.ipv4_optional, /*optional=*/true)}) { + if (const auto capabilities{m_node.evo().getProviderTxCapabilities()}; !capabilities) { + err = MasternodeWidgetUtil::masternodeStateUnavailableText(); + } else if (const auto error{m_node.evo().validateProviderNetInfo(net_info, MnType::Regular, capabilities->version, + capabilities->ipv4_optional, + /*optional=*/true)}) { err = QString::fromStdString(error->message.translated); } else { err = ServiceInUseProblem(m_node, m_service_edit->text()); @@ -2353,8 +2359,8 @@ void SharedMnCreateDialog::pushSessionToWidgets() void SharedMnCreateDialog::startSession() { - if (!m_v24_active) { - showError(SharedMnV24InactiveMessage()); + if (!m_v24_active.value_or(false)) { + showError(SharedMnV24InactiveMessage(m_v24_active)); return; } if (m_wallet_model == nullptr) { diff --git a/src/qt/sharedmncreatedialog.h b/src/qt/sharedmncreatedialog.h index 808ad1088c84..95797b38e8a8 100644 --- a/src/qt/sharedmncreatedialog.h +++ b/src/qt/sharedmncreatedialog.h @@ -397,7 +397,7 @@ private Q_SLOTS: interfaces::Node& m_node; WalletModel* const m_wallet_model; - const bool m_v24_active; + const std::optional m_v24_active; MnShareSession m_session; //! Null without a wallet, when nothing can be prepared or signed here MasternodeOperationRunner* const m_runner; diff --git a/src/qt/sharedmndialogs.cpp b/src/qt/sharedmndialogs.cpp index c2a76e742732..b75c29ad8ae5 100644 --- a/src/qt/sharedmndialogs.cpp +++ b/src/qt/sharedmndialogs.cpp @@ -404,8 +404,8 @@ void UpdateShareDialog::validate() if (!m_is_shared) { showError(tr("This masternode is not shared and has no share table.")); - } else if (!m_v24_active) { - showError(SharedMnV24InactiveMessage()); + } else if (!m_v24_active.value_or(false)) { + showError(SharedMnV24InactiveMessage(m_v24_active)); } else if (m_share_combo->count() == 0) { showError(NoShareKeysMessage()); } else if (!m_reward_edit->text().trimmed().isEmpty() && !problem.isEmpty()) { @@ -416,7 +416,7 @@ void UpdateShareDialog::validate() clearError(); } - setOkValid(m_v24_active && m_is_shared && has_share && problem.isEmpty() && + setOkValid(m_v24_active.value_or(false) && m_is_shared && has_share && problem.isEmpty() && !m_fee_source->selectedAddress().isEmpty()); } @@ -892,9 +892,9 @@ bool SharedMnDialog::gateButton(QPushButton* button) const button->setToolTip(tr("This wallet is watch-only and cannot sign.")); return false; } - if (!m_v24_active) { + if (!m_v24_active.value_or(false)) { button->setEnabled(false); - button->setToolTip(SharedMnV24InactiveMessage()); + button->setToolTip(SharedMnV24InactiveMessage(m_v24_active)); return false; } return true; diff --git a/src/qt/sharedmndialogs.h b/src/qt/sharedmndialogs.h index 8ef926ffb1d5..8c56df5bf51a 100644 --- a/src/qt/sharedmndialogs.h +++ b/src/qt/sharedmndialogs.h @@ -63,7 +63,7 @@ class UpdateShareDialog : public MasternodeActionDialog //! Fill the reward field with a fresh address of this wallet void useNewAddress(); - const bool m_v24_active; + const std::optional m_v24_active; const QString m_voting_address; const std::vector m_shares; @@ -242,7 +242,7 @@ class SharedMnDialog : public QDialog const CAmount m_early_penalty; const uint32_t m_early_period_blocks; const int m_registered_height; - const bool m_v24_active; + const std::optional m_v24_active; //! Null without a wallet, in which case every action button is gated off MasternodeOperationRunner* const m_runner; diff --git a/src/qt/sharedmnwidgets.cpp b/src/qt/sharedmnwidgets.cpp index 8a344028b407..1abac3c089f6 100644 --- a/src/qt/sharedmnwidgets.cpp +++ b/src/qt/sharedmnwidgets.cpp @@ -89,8 +89,13 @@ bool SharedMnWalletOwnsShare(const WalletModel* wallet_model, const interfaces:: return wallet_model != nullptr && wallet_model->wallet().isSpendable(PKHash(share.keyIDOwner)); } -QString SharedMnV24InactiveMessage() +QString SharedMnV24InactiveMessage(std::optional v24_active) { + if (!v24_active) { + return QCoreApplication::translate("SharedMnDialog", + "This node cannot tell yet whether the v24 upgrade is active. Try again " + "later."); + } return QCoreApplication::translate("SharedMnDialog", "Shared masternodes need the v24 upgrade, which is not active on this network " "yet."); diff --git a/src/qt/sharedmnwidgets.h b/src/qt/sharedmnwidgets.h index c2b7b981c1ee..248bc379edc0 100644 --- a/src/qt/sharedmnwidgets.h +++ b/src/qt/sharedmnwidgets.h @@ -47,7 +47,7 @@ BitcoinUnits::Unit SharedMnDisplayUnit(const WalletModel* wallet_model); bool SharedMnWalletOwnsShare(const WalletModel* wallet_model, const interfaces::MnShare& share); //! The one wording for the v24 activation gate -QString SharedMnV24InactiveMessage(); +QString SharedMnV24InactiveMessage(std::optional v24_active); //! Broadcast a fully signed transaction under the same fee cap "sendrawtransaction" //! applies. Returns why it was rejected, ready to show to the user, or an empty diff --git a/src/qt/test/masternodewidgettests.cpp b/src/qt/test/masternodewidgettests.cpp index caa2eb64d79c..2c4b5d28e2bb 100644 --- a/src/qt/test/masternodewidgettests.cpp +++ b/src/qt/test/masternodewidgettests.cpp @@ -11,13 +11,16 @@ #include #include #include +#include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -27,7 +30,6 @@ #include #include #include -#include #include #include