diff --git a/doc/design/assumeutxo.md b/doc/design/assumeutxo.md index 5c6ee36a6fad..a261df61d5c8 100644 --- a/doc/design/assumeutxo.md +++ b/doc/design/assumeutxo.md @@ -1,20 +1,50 @@ # assumeutxo Assumeutxo is a feature that allows fast bootstrapping of a validating dashd -instance with a very similar security model to assumevalid. +instance. ## Loading a snapshot There is currently no canonical source for snapshots, but any downloaded snapshot will be checked against a hash that's been hardcoded in source code. -Once you've obtained the snapshot, you can use the RPC command `loadtxoutset` -(yet to be merged) to load it. +Dash Core accepts one snapshot per network: + +| network | base height | base block hash | snapshot file size | snapshot file sha256 | +| ------- | ----------- | --------------- | ------------------ | -------------------- | +| mainnet | 2579482 | `000000000000001cfbe4751211d7e753bab093e5d63de1fa947cf20714a0e727` | 289606403 bytes | `bf65a65ef575989e58df25f5781187a6b4dec25e0211b329fb2413b203dc952f` | +| testnet | 1599687 | `0000006e4b85a1f38f3224ead2865de8e7f29d98229b58b00a1b1bedab624872` | 64126131 bytes | `651e5b29b8c9ff9b50606cbd95c515e7877fb0004432bfa9d4bdce228fc99786` | + +The snapshot file is deterministic: `dumptxoutset` writes the same bytes at the same +base block on every node, so a file can be checked with `sha256sum` before loading it. +Loading checks the file again, independently of where it came from: the coins against +the pinned UTXO set hash and the Dash evo section (masternode list, quorums, credit +pool and hard-fork signals) against the pinned evo hash. + +Once you've obtained the snapshot, start the node and wait until its headers have +passed the base block (`getblockchaininfo` reports `headers` at or above the base +height), then load it with the RPC command `loadtxoutset`, for example + +``` +dash-cli loadtxoutset /path/to/utxo-2579482.dat +``` + +The node then syncs to the network tip from the base block, and validates the chain +up to the base block in the background. `getchainstates` shows both chainstates and +whether the snapshot has been validated yet. Once background validation has reached +the base block and a restart has promoted the snapshot chainstate, the node is +indistinguishable from one that synced from genesis. + +A masternode does not load snapshots, and a node does not start with +`-masternodeblsprivkey` while it has a snapshot chainstate, validated or not, +until a restart has promoted it. ### Pruning -A pruned node can load a snapshot. To save space, it's possible to delete the -snapshot file as soon as `loadtxoutset` finishes. +A pruned node cannot load a snapshot, and a node does not start with `-prune` +while it has a snapshot chainstate, validated or not, until a restart has +promoted it. It's possible to delete the snapshot file as soon as +`loadtxoutset` finishes. The minimum `-prune` setting is 550 MiB, but this functionality ignores that minimum and uses at least 1100 MiB. @@ -25,10 +55,17 @@ downloaded snapshot). ### Indexes -Indexes work but don't take advantage of this feature. They always start building +A node with `-addressindex`, `-spentindex` or `-timestampindex` cannot load a +snapshot, and does not start with them while it has a snapshot chainstate. + +Other indexes work but don't take advantage of this feature. They always start building from the genesis block. Once the background validation reaches the snapshot block, indexes will continue to build all the way to the tip. +Governance waits until background validation has completed and the governance +collateral index has caught up: until then the node neither processes nor relays +governance objects, and `gobject prepare` and `gobject submit` refuse. + For indexes that support pruning, note that no pruning will take place between the snapshot and the tip, until the background sync has completed - after which everything is pruned. Depending on how old the snapshot is, this may temporarily @@ -40,6 +77,13 @@ The RPC command `dumptxoutset` can be used to generate a snapshot. This can be u to create a snapshot on one node that you wish to load on another node. It can also be used to verify the hardcoded snapshot hash in the source code. +`dumptxoutset` writes the snapshot at the node's current tip, and only a snapshot whose +base is pinned can be loaded. To produce the pinned mainnet or testnet file, use a copy +of a synced datadir, disconnect it from the network (`setnetworkactive false`), call +`invalidateblock` on the block after the base, and run `dumptxoutset` there. Its +`txoutset_hash`, `evo.hash` and `nchaintx` fields are the values pinned in +`src/kernel/chainparams.cpp`. + The utility script `./contrib/devtools/utxo_snapshot.sh` may be of use. @@ -51,18 +95,12 @@ The utility script ## Design notes -- A new block index `nStatus` flag is introduced, `BLOCK_ASSUMED_VALID`, to mark block - index entries that are required to be assumed-valid by a chainstate created - from a UTXO snapshot. This flag is used as a way to modify certain - CheckBlockIndex() logic to account for index entries that are pending validation by a - chainstate running asynchronously in the background. - - The concept of UTXO snapshots is treated as an implementation detail that lives behind the ChainstateManager interface. The external presentation of the changes required to facilitate the use of UTXO snapshots is the understanding that there are - now certain regions of the chain that can be temporarily assumed to be valid (using - the nStatus flag mentioned above). In certain cases, e.g. wallet rescanning, this is - very similar to dealing with a pruned chain. + now certain regions of the chain that can be temporarily assumed to be valid. + In certain cases, e.g. wallet rescanning, this is very similar to dealing with + a pruned chain. Logic outside ChainstateManager should try not to know about snapshots, instead preferring to work in terms of more general states like assumed-valid. diff --git a/doc/release-notes-8078.md b/doc/release-notes-8078.md new file mode 100644 index 000000000000..52a10ab47ded --- /dev/null +++ b/doc/release-notes-8078.md @@ -0,0 +1,9 @@ +Other changes +------------- + +- While a loaded AssumeUTXO snapshot has not been validated in the + background, an InstantSend lock that conflicts with a block on the snapshot + chain no longer invalidates that block. The block is kept and the lock is + discarded: it is not applied, announced, relayed or served. Once background + validation completes, such a lock invalidates the conflicting blocks as + before. (#8078) diff --git a/doc/release-notes-8270.md b/doc/release-notes-8270.md new file mode 100644 index 000000000000..04d82457f714 --- /dev/null +++ b/doc/release-notes-8270.md @@ -0,0 +1,7 @@ +Updated RPCs +------------ + +- RPC handlers that let a local Evo-state exception reach the RPC dispatcher + now return `RPC_INTERNAL_ERROR` (-32603) instead of `RPC_MISC_ERROR` (-1). + RPCs that handle the failure as a validation result, such as `submitblock` + and the package RPCs, report it through their own error paths. (#8270) diff --git a/doc/release-notes-8271.md b/doc/release-notes-8271.md new file mode 100644 index 000000000000..b2d773073d6c --- /dev/null +++ b/doc/release-notes-8271.md @@ -0,0 +1,19 @@ +Updated RPCs +------------ + +- On a pruned node, `quorum info`, `quorum memberof` and `quorum selectquorum` + fail with `RPC_INTERNAL_ERROR` for a quorum whose members this node cannot + compute because the block that fixes them was pruned. They used to work with + members computed from a substitute value, which could be wrong. (#8271) + +Other changes +------------- + +- A pruned node no longer substitutes the block hash for the quorum score + modifier of a pruned work block. It keeps such a quorum's public key, from + its mined commitment, without members, so it still verifies signatures + by that quorum (for example on masternode hard-fork signals) and never + stalls on them. `quorum listextended` and the GUI then compute its health + over its commitment's member slots. Its members are computed again once the + pruned block is downloaded again, for example with `getblockfrompeer`. + (#8271) diff --git a/doc/release-notes-8276.md b/doc/release-notes-8276.md new file mode 100644 index 000000000000..2c90c01ec856 --- /dev/null +++ b/doc/release-notes-8276.md @@ -0,0 +1,11 @@ +Updated RPCs +------------ + +- `loadtxoutset`, `getchainstates` and `dumptxoutset` are no longer hidden, and + `loadtxoutset` and `getchainstates` now work on mainnet and testnet as well as + regtest. `loadtxoutset` loads an AssumeUTXO snapshot so that the node is usable at + the network tip within minutes, while it validates the chain up to the snapshot in + the background. Mainnet accepts the snapshot at height 2579482 and testnet the one + at height 1599687. Pruned nodes, masternodes and nodes with `-addressindex`, + `-spentindex` or `-timestampindex` refuse to load a snapshot. See + `doc/design/assumeutxo.md`. (#8276) diff --git a/doc/zmq.md b/doc/zmq.md index 2f7afc1d1bd6..caa178978da9 100644 --- a/doc/zmq.md +++ b/doc/zmq.md @@ -142,11 +142,11 @@ Where the 8-byte uints correspond to the mempool sequence number. | hashtx | <32-byte transaction hash in Little Endian> | -`rawblock`: Notifies when the chain tip is updated. Messages are ZMQ multipart messages with three parts. The first part is the topic (`rawblock`), the second part is the serialized block, and the last part is a sequence number (representing the message count to detect lost messages). +`rawblock`: Notifies when the chain tip is updated. When assumeutxo is in use, this notification will not be issued for historical blocks connected to the background validation chainstate. Messages are ZMQ multipart messages with three parts. The first part is the topic (`rawblock`), the second part is the serialized block, and the last part is a sequence number (representing the message count to detect lost messages). | rawblock | | -`hashblock`: Notifies when the chain tip is updated. Messages are ZMQ multipart messages with three parts. The first part is the topic (`hashblock`), the second part is the 32-byte block hash, and the last part is a sequence number (representing the message count to detect lost messages). +`hashblock`: Notifies when the chain tip is updated. When assumeutxo is in use, this notification will not be issued for historical blocks connected to the background validation chainstate. Messages are ZMQ multipart messages with three parts. The first part is the topic (`hashblock`), the second part is the 32-byte block hash, and the last part is a sequence number (representing the message count to detect lost messages). | hashblock | <32-byte block hash in Little Endian> | diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 44755f47f12a..0fa2d82b3be3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -327,6 +327,7 @@ add_library(bitcoin_node STATIC EXCLUDE_FROM_ALL evo/simplifiedmns.cpp evo/smldiff.cpp evo/snapshot.cpp + evo/snapshot_chain.cpp evo/specialtx.cpp evo/specialtx_filter.cpp evo/specialtxman.cpp diff --git a/src/bench/wallet_create_tx.cpp b/src/bench/wallet_create_tx.cpp index 82165cbbe9c0..36591771f908 100644 --- a/src/bench/wallet_create_tx.cpp +++ b/src/bench/wallet_create_tx.cpp @@ -70,7 +70,7 @@ void generateFakeBlock(const CChainParams& params, // notify wallet const auto& pindex = WITH_LOCK(::cs_main, return context.chainman->ActiveChain().Tip()); - wallet.blockConnected(kernel::MakeBlockInfo(pindex, &block)); + wallet.blockConnected(ChainstateRole::NORMAL, kernel::MakeBlockInfo(pindex, &block)); } struct PreSelectInputs { diff --git a/src/chain.h b/src/chain.h index 7b82ea1c8762..2017a18918ca 100644 --- a/src/chain.h +++ b/src/chain.h @@ -91,16 +91,20 @@ enum BlockStatus : uint32_t { /** * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, - * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all - * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. + * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. + * + * If a block's validity is at least VALID_TRANSACTIONS, CBlockIndex::nTx will be set. If a block and all previous + * blocks back to the genesis block or an assumeutxo snapshot block are at least VALID_TRANSACTIONS, + * CBlockIndex::nChainTx will be set. */ BLOCK_VALID_TRANSACTIONS = 3, //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30. - //! Implies all parents are either at least VALID_CHAIN, or are ASSUMED_VALID + //! Implies all previous blocks back to the genesis block or an assumeutxo snapshot block are at least VALID_CHAIN. BLOCK_VALID_CHAIN = 4, - //! Scripts & signatures ok. Implies all parents are either at least VALID_SCRIPTS, or are ASSUMED_VALID. + //! Scripts & signatures ok. Implies all previous blocks back to the genesis block or an assumeutxo snapshot block + //! are at least VALID_SCRIPTS. BLOCK_VALID_SCRIPTS = 5, //! All validity bits. @@ -117,21 +121,8 @@ enum BlockStatus : uint32_t { BLOCK_CONFLICT_CHAINLOCK = 128, //!< conflicts with chainlock system - /** - * If ASSUMED_VALID is set, it means that this block has not been validated - * and has validity status less than VALID_SCRIPTS. Also that it may have - * descendant blocks with VALID_SCRIPTS set, because they can be validated - * based on an assumeutxo snapshot. - * - * When an assumeutxo snapshot is loaded, the ASSUMED_VALID flag is added to - * unvalidated blocks at the snapshot height and below. Then, as the background - * validation progresses, and these blocks are validated, the ASSUMED_VALID - * flags are removed. See `doc/design/assumeutxo.md` for details. - * - * This flag is only used to implement checks in CheckBlockIndex() and - * should not be used elsewhere. - */ - BLOCK_ASSUMED_VALID = 256, + BLOCK_STATUS_RESERVED = 256, //!< Unused flag that was previously set on assumeutxo snapshot blocks and their + //!< ancestors before they were validated, and unset when they were validated. }; /** The block chain is a tree shaped structure starting with the @@ -166,21 +157,16 @@ class CBlockIndex //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block arith_uint256 nChainWork{}; - //! Number of transactions in this block. + //! Number of transactions in this block. This will be nonzero if the block + //! reached the VALID_TRANSACTIONS level, and zero otherwise. //! Note: in a potential headers-first mode, this number cannot be relied upon - //! Note: this value is faked during UTXO snapshot load to ensure that - //! LoadBlockIndex() will load index entries for blocks that we lack data for. - //! @sa ActivateSnapshot unsigned int nTx{0}; //! (memory only) Number of transactions in the chain up to and including this block. - //! This value will be non-zero only if and only if transactions for this block and all its parents are available. + //! This value will be non-zero if this block and all previous blocks back + //! to the genesis block or an assumeutxo snapshot block have reached the + //! VALID_TRANSACTIONS level. //! Change to 64-bit type before 2024 (assuming worst case of 60 byte transactions). - //! - //! Note: this value is faked during use of a UTXO snapshot because we don't - //! have the underlying block data available during snapshot load. - //! @sa AssumeutxoData - //! @sa ActivateSnapshot unsigned int nChainTx{0}; //! Verification status of this block. See enum BlockStatus @@ -255,13 +241,16 @@ class CBlockIndex } /** - * Check whether this block's and all previous blocks' transactions have been - * downloaded (and stored to disk) at some point. + * Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot block have + * reached VALID_TRANSACTIONS and had transactions downloaded (and stored to disk) at some point. * * Does not imply the transactions are consensus-valid (ConnectTip might fail) * Does not imply the transactions are still stored on disk. (IsBlockPruned might return true) + * + * Note that this will be true for the snapshot base block, if one is loaded, since its nChainTx value will have + * been set manually based on the related AssumeutxoData entry. */ - bool HaveTxsDownloaded() const { return nChainTx != 0; } + bool HaveNumChainTxs() const { return nChainTx != 0; } NodeSeconds Time() const { @@ -307,14 +296,6 @@ class CBlockIndex return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } - //! @returns true if the block is assumed-valid; this means it is queued to be - //! validated by a background chainstate. - bool IsAssumedValid() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) - { - AssertLockHeld(::cs_main); - return nStatus & BLOCK_ASSUMED_VALID; - } - //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) @@ -324,12 +305,6 @@ class CBlockIndex if (nStatus & BLOCK_FAILED_MASK) return false; if ((nStatus & BLOCK_VALID_MASK) < nUpTo) { - // If this block had been marked assumed-valid and we're raising - // its validity to a certain point, there is no longer an assumption. - if (nStatus & BLOCK_ASSUMED_VALID && nUpTo >= BLOCK_VALID_SCRIPTS) { - nStatus &= ~BLOCK_ASSUMED_VALID; - } - nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo; return true; } diff --git a/src/chainlock/handler.cpp b/src/chainlock/handler.cpp index cadce2a74dc8..61fa165a71b2 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() @@ -203,10 +206,14 @@ void ChainlockHandler::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBloc if (bool expected = false; tryLockChainTipScheduled.compare_exchange_strong(expected, true)) { scheduler->scheduleFromNow( [&]() { + // A failed round must still let the next tip schedule one. + const struct Unschedule { + ChainlockHandler& handler; + ~Unschedule() { handler.tryLockChainTipScheduled = false; } + } done{*this}; CheckActiveState(); EnforceBestChainLock(); Cleanup(); - tryLockChainTipScheduled = false; }, std::chrono::seconds{0}); } @@ -242,8 +249,12 @@ void ChainlockHandler::AcceptedBlockHeader(const CBlockIndex* pindexNew) m_chainlocks.AcceptedBlockHeader(pindexNew); } -void ChainlockHandler::BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) +void ChainlockHandler::BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindex) { + // Only the active chainstate's blocks concern this subscriber. + if (role == ChainstateRole::BACKGROUND) { + return; + } if (!m_mn_sync.IsBlockchainSynced()) { return; } @@ -300,7 +311,7 @@ void ChainlockHandler::EnforceBestChainLock() LogPrint(BCLog::CHAINLOCKS, "ChainlockHandler::%s -- enforcing block %s via CLSIG (%s)\n", __func__, currentBestChainLockBlockIndex->GetBlockHash().ToString(), clsig.ToString()); m_chainman.ActiveChainstate().EnforceBlock(dummy_state, currentBestChainLockBlockIndex); - + if (dummy_state.IsError()) return; if (/*activateNeeded =*/WITH_LOCK(::cs_main, return m_chainman.ActiveTip()->GetAncestor( currentBestChainLockBlockIndex->nHeight)) != diff --git a/src/chainlock/handler.h b/src/chainlock/handler.h index 76dca1672a95..fa1c3b0fca2f 100644 --- a/src/chainlock/handler.h +++ b/src/chainlock/handler.h @@ -104,7 +104,7 @@ class ChainlockHandler final : public CValidationInterface void TransactionAddedToMempool(const CTransactionRef& tx, int64_t nAcceptTime, uint64_t mempool_sequence) override EXCLUSIVE_LOCKS_REQUIRED(!cs); - void BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) override + void BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindex) override EXCLUSIVE_LOCKS_REQUIRED(!cs); private: diff --git a/src/chainlock/signing.cpp b/src/chainlock/signing.cpp index ba1802ad452b..fa6580c483e2 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(); } @@ -185,8 +188,12 @@ void ChainLockSigner::BlockDisconnected(const std::shared_ptr& blo } -void ChainLockSigner::BlockConnected(const std::shared_ptr& block, const CBlockIndex* pindex) +void ChainLockSigner::BlockConnected(ChainstateRole role, const std::shared_ptr& block, const CBlockIndex* pindex) { + // Only the active chainstate's blocks concern this subscriber. + if (role == ChainstateRole::BACKGROUND) { + return; + } if (!m_mn_sync.IsBlockchainSynced()) { return; } diff --git a/src/chainlock/signing.h b/src/chainlock/signing.h index b077026fe303..1dafed891ef1 100644 --- a/src/chainlock/signing.h +++ b/src/chainlock/signing.h @@ -72,7 +72,7 @@ class ChainLockSigner final : public llmq::CRecoveredSigsListener, public CValid void UnregisterRecoveryInterface(); // implements validation interface: - void BlockConnected(const std::shared_ptr& block, const CBlockIndex* pindex) override + void BlockConnected(ChainstateRole role, const std::shared_ptr& block, const CBlockIndex* pindex) override EXCLUSIVE_LOCKS_REQUIRED(!cs_signer); void BlockDisconnected(const std::shared_ptr& block, const CBlockIndex* pindex) override EXCLUSIVE_LOCKS_REQUIRED(!cs_signer); diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 3617491289e1..a671cbf5369c 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -204,6 +204,32 @@ static void ReadRegTestLLMQInstantSendDIP0024Args(const ArgsManager& args, CChai options.llmq_dip0024_instantsend = args.GetArg("-llmqtestinstantsenddip0024", ""); } +static void ReadRegTestAssumeutxoArgs(const ArgsManager& args, CChainParams::RegTestOptions& options) +{ + for (const std::string& arg : args.GetArgs("-assumeutxodata")) { + const std::vector fields{SplitString(arg, ':')}; + const auto valid_hash = [](const std::string& value) { + return value.size() == uint256::size() * 2 && IsHex(value) && !uint256S(value).IsNull(); + }; + int32_t height; + uint32_t n_chain_tx; + if (fields.size() != 5 || !ParseInt32(fields[0], &height) || height <= 0 || !valid_hash(fields[1]) || + !valid_hash(fields[2]) || !ParseUInt32(fields[3], &n_chain_tx) || n_chain_tx == 0 || + !valid_hash(fields[4])) { + throw std::runtime_error(strprintf( + "Invalid value (%s) for -assumeutxodata=::::", + arg)); + } + options.assumeutxo_data.push_back(AssumeutxoData{ + .height = height, + .hash_serialized = AssumeutxoHash{uint256S(fields[1])}, + .evo_hash = EvoSnapshotHash{uint256S(fields[2])}, + .nChainTx = n_chain_tx, + .blockhash = uint256S(fields[4]), + }); + } +} + void ReadRegTestArgs(const ArgsManager& args, CChainParams::RegTestOptions& options) { if (auto value = args.GetBoolArg("-fastprune")) options.fastprune = *value; @@ -215,6 +241,7 @@ void ReadRegTestArgs(const ArgsManager& args, CChainParams::RegTestOptions& opti ReadRegTestLLMQTestArgs(args, options, Consensus::LLMQType::LLMQ_TEST_INSTANTSEND); ReadRegTestLLMQTestArgs(args, options, Consensus::LLMQType::LLMQ_TEST_PLATFORM); ReadRegTestLLMQInstantSendDIP0024Args(args, options); + ReadRegTestAssumeutxoArgs(args, options); } static void ReadDevNetSubsidyAndDiffArgs(const ArgsManager& args, CChainParams::DevNetOptions& options) @@ -335,6 +362,7 @@ void SetupChainParamsOptions(ArgsManager& argsman) { SetupChainParamsBaseOptions(argsman); + argsman.AddArg("-assumeutxodata=::::", "Add an exact AssumeUTXO snapshot authorization (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-budgetparams=::", "Override masternode, budget and superblock start heights (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-dip3params=:", "Override DIP3 activation and enforcement heights (regtest-only)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CHAINPARAMS); argsman.AddArg("-highsubsidyblocks=", "The number of blocks with a higher than normal subsidy to mine at the start of a chain. Block after that height will have fixed subsidy base. (default: 0, devnet-only)", ArgsManager::ALLOW_ANY, OptionsCategory::CHAINPARAMS); diff --git a/src/coins.h b/src/coins.h index 5b5b7ad0d255..7aa36e5b4e46 100644 --- a/src/coins.h +++ b/src/coins.h @@ -236,6 +236,8 @@ class CCoinsViewCursor virtual bool Valid() const = 0; virtual void Next() = 0; + //! Whether a read failed: the cursor may then have skipped records. + virtual bool HasError() const = 0; //! Get best block at the time this cursor was created const uint256 &GetBestBlock() const { return hashBlock; } diff --git a/src/dbwrapper.cpp b/src/dbwrapper.cpp index b1cd8017f9d2..ee1fd5377765 100644 --- a/src/dbwrapper.cpp +++ b/src/dbwrapper.cpp @@ -217,6 +217,16 @@ struct LevelDBContext { //! the database itself leveldb::DB* pdb; + + //! Also frees what a constructor that threw had allocated. + ~LevelDBContext() + { + delete pdb; + delete options.filter_policy; + delete options.info_log; + delete options.block_cache; + delete penv; + } }; CDBWrapper::CDBWrapper(const DBParams& params) @@ -275,19 +285,7 @@ CDBWrapper::CDBWrapper(const DBParams& params) LogPrintf("Using obfuscation key for %s: %s\n", fs::PathToString(params.path), HexStr(obfuscate_key)); } -CDBWrapper::~CDBWrapper() -{ - delete DBContext().pdb; - DBContext().pdb = nullptr; - delete DBContext().options.filter_policy; - DBContext().options.filter_policy = nullptr; - delete DBContext().options.info_log; - DBContext().options.info_log = nullptr; - delete DBContext().options.block_cache; - DBContext().options.block_cache = nullptr; - delete DBContext().penv; - DBContext().options.env = nullptr; -} +CDBWrapper::~CDBWrapper() = default; bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync) { diff --git a/src/dbwrapper.h b/src/dbwrapper.h index 205c5e065dfc..4213abc6cd52 100644 --- a/src/dbwrapper.h +++ b/src/dbwrapper.h @@ -425,6 +425,8 @@ class CDBTransactionIterator return transactionIt != transaction.writes.end() || parentIt->Valid(); } + bool HasError() const { return parentIt->HasError(); } + void Next() { if (transactionIt == transaction.writes.end() && !parentIt->Valid()) { return; diff --git a/src/dsnotificationinterface.cpp b/src/dsnotificationinterface.cpp index 2db2dc7e91e6..644fa3df36d4 100644 --- a/src/dsnotificationinterface.cpp +++ b/src/dsnotificationinterface.cpp @@ -34,6 +34,11 @@ void CDSNotificationInterface::InitializeCurrentBlockTip(const CBlockIndex* tip, UpdatedBlockTip(tip, nullptr, ibd); } +void CDSNotificationInterface::InitializeSnapshotTip(const CBlockIndex* tip, bool ibd) +{ + UpdatedBlockTip(tip, nullptr, ibd); +} + void CDSNotificationInterface::AcceptedBlockHeader(const CBlockIndex *pindexNew) { m_mn_sync.AcceptedBlockHeader(pindexNew); @@ -77,8 +82,12 @@ void CDSNotificationInterface::TransactionAddedToMempool(const CTransactionRef& m_dstxman.TransactionAddedToMempool(ptx); } -void CDSNotificationInterface::BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) +void CDSNotificationInterface::BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindex) { + // Only the active chainstate's blocks concern this subscriber. + if (role == ChainstateRole::BACKGROUND) { + return; + } m_dstxman.BlockConnected(pblock, pindex); } diff --git a/src/dsnotificationinterface.h b/src/dsnotificationinterface.h index bb4a42792cde..97c9ad52c49f 100644 --- a/src/dsnotificationinterface.h +++ b/src/dsnotificationinterface.h @@ -27,6 +27,8 @@ class CDSNotificationInterface : public CValidationInterface // CValidationInterface void InitializeCurrentBlockTip(const CBlockIndex* tip, bool ibd) override; + void InitializeSnapshotTip(const CBlockIndex* tip, bool ibd) override; + protected: // CValidationInterface void AcceptedBlockHeader(const CBlockIndex *pindexNew) override; @@ -34,7 +36,7 @@ class CDSNotificationInterface : public CValidationInterface void SynchronousUpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; void TransactionAddedToMempool(const CTransactionRef& tx, int64_t nAcceptTime, uint64_t mempool_sequence) override; - void BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) override; + void BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindex) override; void BlockDisconnected(const std::shared_ptr& pblock, const CBlockIndex* pindexDisconnected) override; void NotifyMasternodeListChanged(bool undo, const CDeterministicMNList& oldMNList, const CDeterministicMNListDiff& diff) override; void NotifyChainLock(const CBlockIndex* pindex, const std::shared_ptr& clsig) override; diff --git a/src/evo/cbtx.cpp b/src/evo/cbtx.cpp index e0fbbb91056d..0a88654abbb0 100644 --- a/src/evo/cbtx.cpp +++ b/src/evo/cbtx.cpp @@ -4,6 +4,8 @@ #include +#include +#include #include #include #include @@ -193,7 +195,35 @@ std::string CCbTx::ToString() const creditPoolBalance / COIN, creditPoolBalance % COIN, merkleRootAssetUnlocks.ToString()); } -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex) +std::optional DecodeCbTxPayload(const CTransaction& tx) +{ + if (!tx.IsCoinBase() || tx.nType != TRANSACTION_COINBASE) return std::nullopt; + DataStream ds{tx.vExtraPayload}; + CCbTx cbtx; + try { + ds >> cbtx.nVersion >> cbtx.nHeight >> cbtx.merkleRootMNList; + if (cbtx.nVersion >= CCbTx::Version::MERKLE_ROOT_QUORUMS) { + ds >> cbtx.merkleRootQuorums; + if (cbtx.nVersion >= CCbTx::Version::CLSIG_AND_BALANCE) { + ds >> COMPACTSIZE(cbtx.bestCLHeightDiff); + // Decoded eagerly: bytes valid in neither scheme reject the payload. + CBLSSignature signature; + ds >> signature; + cbtx.bestCLSignature.Set(signature); + ds >> cbtx.creditPoolBalance; + if (cbtx.nVersion >= CCbTx::Version::MERKLE_ROOT_ASSETUNLOCKS) ds >> cbtx.merkleRootAssetUnlocks; + } + } + } catch (const std::exception&) { + return std::nullopt; + } + if (!ds.empty()) return std::nullopt; + return cbtx; +} + +std::optional> GetNonNullCoinbaseChainlock(const EvoViewToken& view, + const node::BlockManager& blockman, + const CBlockIndex* pindex) { if (pindex == nullptr) { return std::nullopt; @@ -205,22 +235,38 @@ std::optional> GetNonNullCoinbaseChainlock(co } CBlock block; - if (!blockman.ReadBlockFromDisk(block, *pindex)) { + if (!ReadBlockInView(view, blockman, *pindex, block)) return std::nullopt; + return GetNonNullCoinbaseChainlock(block, *pindex); +} + +std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, const CBlockIndex& index) +{ + if (block.vtx.empty()) return std::nullopt; + const auto payload{DecodeCbTxPayload(*block.vtx[0])}; + if (!payload || payload->nVersion < CCbTx::Version::CLSIG_AND_BALANCE || payload->nHeight != index.nHeight || + !payload->bestCLSignature.Get().IsValid() || payload->bestCLHeightDiff >= static_cast(index.nHeight)) { return std::nullopt; } - - return GetNonNullCoinbaseChainlock(block, pindex->nHeight); + return std::make_pair(payload->bestCLSignature.Get(), payload->bestCLHeightDiff); } -std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, int32_t height) +bool ReadBlockInView(const EvoViewToken& view, const node::BlockManager& blockman, const CBlockIndex& index, + CBlock& block) { - if (block.vtx.empty() || !block.vtx[0]->IsCoinBase() || block.vtx[0]->nType != TRANSACTION_COINBASE) { - return std::nullopt; + const auto [have_data, block_pos]{WITH_LOCK(::cs_main, return std::make_pair( + (index.nStatus & BLOCK_HAVE_DATA) != 0, index.GetBlockPos()))}; + if (!have_data) { + // A snapshot view lacks the bodies at or below its base, where a block + // this node does not have cannot be told from one whose data does not + // matter. + if (view.AtOrBelowSnapshotBase(index.nHeight)) { + throw BlockDataUnavailableError(strprintf("block %s at or below the snapshot base is not available", + index.GetBlockHash().ToString())); + } + return false; } - const auto payload = GetTxPayload(*block.vtx[0]); - if (!payload || payload->nVersion < CCbTx::Version::CLSIG_AND_BALANCE || payload->nHeight != height || - !payload->bestCLSignature.Get().IsValid() || payload->bestCLHeightDiff >= static_cast(height)) { - return std::nullopt; + if (blockman.ReadBlockFromDisk(block, block_pos) != index.GetBlockHash()) { + throw BlockDataReadError(strprintf("block %s cannot be read", index.GetBlockHash().ToString())); } - return std::make_pair(payload->bestCLSignature.Get(), payload->bestCLHeightDiff); + return true; } diff --git a/src/evo/cbtx.h b/src/evo/cbtx.h index 09201841ef8c..e94a01733c09 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,24 @@ 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); -std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, int32_t height); +/** Decode a coinbase's CbTx payload strictly: the ChainLock signature + * eagerly, and nothing may follow the payload. */ +std::optional DecodeCbTxPayload(const CTransaction& tx); +/** The non-null ChainLock in the coinbase of `pindex`'s block. A block this + * node has but cannot read raises BlockDataReadError; one it lacks reads as + * none, except at or below the base in a snapshot `view`, where it raises + * BlockDataUnavailableError. */ +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 + * this node does not have it, raises BlockDataUnavailableError instead when the + * view is a snapshot view at or below its base, and BlockDataReadError when the + * body is stored but cannot be read. */ +bool ReadBlockInView(const EvoViewToken& view, const node::BlockManager& blockman, const CBlockIndex& index, + CBlock& block); +/** The non-null ChainLock in `block`'s coinbase, decoded strictly, where + * `index` is the block's own index. */ +std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, const CBlockIndex& index); #endif // BITCOIN_EVO_CBTX_H diff --git a/src/evo/creditpool.cpp b/src/evo/creditpool.cpp index d4fac2c010f7..50af5236378b 100644 --- a/src/evo/creditpool.cpp +++ b/src/evo/creditpool.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -28,6 +29,9 @@ static const std::string DB_CREDITPOOL_SNAPSHOT = "cpm_S"; +// Window entries carried by an assumeutxo snapshot, for blocks at or below its +// base. Written only into a snapshot generation. +static const std::string DB_CREDITPOOL_HISTORY = "cpm_H"; static bool GetDataFromUnlockTx(const CTransaction& tx, CAmount& toUnlock, uint64_t& index, TxValidationState& state) { @@ -66,6 +70,12 @@ static Uint256LruHashMap& BlockDataCache() EXCLUSIVE_LOC return cache; } +void CCreditPoolManager::ClearBlockDataCacheForTesting() +{ + LOCK(::cache_mutex); + BlockDataCache().clear(); +} + // it throws exception if anything went wrong static std::optional ReadCreditData(const CBlock& block, int height) { @@ -157,8 +167,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 @@ -166,10 +177,12 @@ std::optional CCreditPoolManager::GetFromCache(const CBlockIndex& b MaybeWriteSnapshot(block_hash, block_index.nHeight, pool); return pool; } - if (block_index.nHeight % DISK_SNAPSHOT_PERIOD == 0) { + // A snapshot base carries its full pool at whatever height the base has. + if (block_index.nHeight % DISK_SNAPSHOT_PERIOD == 0 || + (view.identity == EvoDbIdentity::SNAPSHOT && block_index.nHeight == view.base_height)) { 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 +209,98 @@ 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); +} + +bool CCreditPoolManager::SeedSnapshot(const EvoViewToken& view, const CBlockIndex* block, const CCreditPool& pool) +{ + if (!Assume(block != nullptr) || !Assume(evoDb.HasActiveTransaction())) return false; + evoDb.RequireTransactionView(view); + if (!evoDb.WriteSeed(std::make_pair(DB_CREDITPOOL_SNAPSHOT, block->GetBlockHash()), pool)) { + return false; + } + LOCK(cache_mutex); + creditPoolCache.For(view).erase(block->GetBlockHash()); + return true; +} + +bool CCreditPoolManager::SeedHistory(const EvoViewToken& view, const CBlockIndex* base, + const std::vector& entries) +{ + if (!Assume(base != nullptr) || !Assume(evoDb.HasActiveTransaction())) return false; + // Seeding may precede the chain checks, which refuse such a window. + if (entries.size() > static_cast(base->nHeight) + 1) return false; + evoDb.RequireTransactionView(view); + const int first_height{base->nHeight - static_cast(entries.size()) + 1}; + for (size_t i{0}; i < entries.size(); ++i) { + const CBlockIndex* index{base->GetAncestor(first_height + static_cast(i))}; + if (!evoDb.WriteSeed(std::make_pair(DB_CREDITPOOL_HISTORY, index->GetBlockHash()), entries[i])) { + return false; + } + } + return true; +} + +std::optional CCreditPoolManager::ReadHistoryEntry(gsl::not_null block_index, + const node::BlockManager& blockman, + const Consensus::Params& consensus_params, + std::string& error) +{ + if (!DeploymentActiveAt(*block_index, consensus_params, Consensus::DEPLOYMENT_DIP0003)) return CreditHistoryEntry{}; + CBlock block; + if (!blockman.ReadBlockFromDisk(block, *block_index)) { + error = strprintf("credit-pool window block %s is unreadable", block_index->GetBlockHash().ToString()); + return std::nullopt; + } + try { + if (const auto data{ReadCreditData(block, block_index->nHeight)}) { + return CreditHistoryEntry{data->credit_pool, data->unlocked}; + } + } catch (const std::exception& e) { + error = e.what(); + return std::nullopt; + } + error = strprintf("credit-pool window block %s has no valid CbTx", block_index->GetBlockHash().ToString()); + return std::nullopt; +} + +std::optional CCreditPoolManager::GetDistantEntry(gsl::not_null block_index) +{ + const auto& consensus{m_chainman.GetConsensus()}; + const EvoViewToken view{evoDb.CurrentView()}; + if (view.identity != EvoDbIdentity::SNAPSHOT || block_index->nHeight > view.base_height) { + const auto data{GetCreditDataFromBlock(block_index, m_chainman.m_blockman, consensus)}; + if (!data) return std::nullopt; + return CreditHistoryEntry{data->credit_pool, data->unlocked}; + } + // At or below the base the snapshot view carries the window entries. A + // body this node also has must agree with them; the carried record never + // enters the cache of entries parsed from real blocks. + if (!DeploymentActiveAt(*block_index, consensus, Consensus::DEPLOYMENT_DIP0003)) return std::nullopt; + CreditHistoryEntry carried; + if (!evoDb.Read(std::make_pair(DB_CREDITPOOL_HISTORY, block_index->GetBlockHash()), carried)) { + throw BlockDataUnavailableError( + strprintf("credit-pool window entry for block %s is not carried", block_index->GetBlockHash().ToString())); + } + if (WITH_LOCK(::cs_main, return (block_index->nStatus & BLOCK_HAVE_DATA) != 0)) { + std::string error; + const auto real{ReadHistoryEntry(block_index, m_chainman.m_blockman, consensus, error)}; + if (real && *real != carried) { + throw evo::SnapshotStateMismatchError( + strprintf("carried credit-pool window entry for block %s differs from the block", + block_index->GetBlockHash().ToString())); + } + } + return carried; } -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 +314,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}; @@ -236,11 +333,9 @@ CCreditPool CCreditPoolManager::ConstructCreditPool(const gsl::not_null distant_block{ - GetCreditDataFromBlock(distant_block_index, m_chainman.m_blockman, m_chainman.GetConsensus())}; - distant_block) { - distantUnlocked = distant_block->unlocked; - distantBalance = distant_block->credit_pool; + if (const auto distant{GetDistantEntry(distant_block_index)}) { + distantUnlocked = distant->unlocked; + distantBalance = distant->credit_pool; } } @@ -274,7 +369,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 +385,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 +397,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 +407,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..ce977185a75c 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 @@ -39,6 +40,16 @@ namespace llmq { class CQuorumManager; } // namespace llmq +/** One block's entry in the credit-pool sliding window: the pool balance its + * CbTx records and the amount its asset unlocks withdraw. */ +struct CreditHistoryEntry { + CAmount credit_pool{0}; + CAmount unlocked{0}; + + bool operator==(const CreditHistoryEntry&) const = default; + SERIALIZE_METHODS(CreditHistoryEntry, obj) { READWRITE(obj.credit_pool, obj.unlocked); } +}; + struct CCreditPool { CAmount locked{0}; @@ -121,7 +132,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; @@ -177,20 +189,42 @@ class CCreditPoolManager * it can happen if there limits of withdrawal (unlock) exceed */ CCreditPool GetCreditPool(const CBlockIndex* block) EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); + /** Seed the full pool at a snapshot base into `view`, inside the caller's + * open EvoDB transaction for that view. */ + bool SeedSnapshot(const EvoViewToken& view, const CBlockIndex* block, const CCreditPool& pool) + EXCLUSIVE_LOCKS_REQUIRED(!cache_mutex); + /** Seed the window entries of the blocks ending at `base`, oldest first, + * into `view`, inside the caller's open EvoDB transaction for that view. */ + bool SeedHistory(const EvoViewToken& view, const CBlockIndex* base, const std::vector& entries); + + /** A block's window entry from its body: {0, 0} before DIP3. Without a + * readable body, or with a malformed CbTx, nullopt and `error`. */ + static std::optional ReadHistoryEntry(gsl::not_null block_index, + const node::BlockManager& blockman, + const Consensus::Params& consensus_params, + std::string& error); /** Records the credit pool data of a block being connected, so that the next block's pool is * constructed from it without reading this block back from disk. */ void CacheBlockData(const CBlock& block, gsl::not_null block_index); + /** Forget the block bodies parsed so far, as a restart would. */ + static void ClearBlockDataCacheForTesting(); + 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); + /** The entry of the block leaving the window: the carried record at or + * below a snapshot base in the snapshot view, the block body otherwise. */ + std::optional GetDistantEntry(gsl::not_null block_index); }; std::optional GetCreditPoolDiffForBlock(CCreditPoolManager& cpoolman, diff --git a/src/evo/deterministicmns.cpp b/src/evo/deterministicmns.cpp index 151d150313ff..d55dae12abb6 100644 --- a/src/evo/deterministicmns.cpp +++ b/src/evo/deterministicmns.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -441,6 +442,16 @@ void CDeterministicMNList::ApplyDiffForSnapshot(const uint256& block_hash, int h nTotalRegisteredCount = total_registered_count; } +CDeterministicMNList CDeterministicMNList::Renumbered(const std::function& new_id, + uint32_t total_registered_count) const +{ + CDeterministicMNList result{blockHash, nHeight, total_registered_count}; + ForEachMNShared(/*onlyValid=*/false, [&](const CDeterministicMNCPtr& dmn) { + result.AddMN(std::make_shared(*dmn, new_id(*dmn)), /*fBumpTotalCount=*/false); + }); + return result; +} + void CDeterministicMNList::AddMN(const CDeterministicMNCPtr& dmn, bool fBumpTotalCount) { assert(dmn != nullptr); @@ -706,14 +717,117 @@ void CDeterministicMNList::RemoveMN(const uint256& proTxHash) InvalidateSMLCache(); } +namespace { +struct MNIdTranslation { + uint32_t snapshot_total{0}; + uint32_t normal_total{0}; + std::map base_ids; + + SERIALIZE_METHODS(MNIdTranslation, obj) { READWRITE(obj.snapshot_total, obj.normal_total, obj.base_ids); } + + // The snapshot view numbers registrations above the base from its own + // counter on, and NORMAL would have numbered them from its own. + uint64_t Id(uint64_t id) const + { + if (id >= snapshot_total) return id - snapshot_total + normal_total; + const auto it{base_ids.find(id)}; + if (it == base_ids.end()) { + throw std::runtime_error(strprintf("snapshot internal id %d is not a masternode of the base", id)); + } + return it->second; + } + + uint32_t Total(uint32_t total) const + { + if (total < snapshot_total || uint64_t{total} - snapshot_total + normal_total > std::numeric_limits::max()) { + throw std::runtime_error(strprintf("snapshot registration counter %d is out of range", total)); + } + return total - snapshot_total + normal_total; + } +}; + +bool HasKeyPrefix(Span key, const std::string& prefix) +{ + DataStream tag{}; + tag << prefix; + return key.size() >= tag.size() && std::equal(tag.begin(), tag.end(), key.begin()); +} +} // namespace + +bool TranslateMNRecord(Span table, Span key, DataStream& value) +{ + const bool is_diff{HasKeyPrefix(key, DB_LIST_DIFF)}; + if (table.empty() || (!is_diff && !HasKeyPrefix(key, DB_LIST_SNAPSHOT))) return true; + try { + MNIdTranslation translation; + DataStream{table} >> translation; + DataStream translated{}; + if (is_diff) { + CDeterministicMNListDiff diff; + value >> diff; + CDeterministicMNListDiff result; + for (const auto& dmn : diff.addedMNs) { + result.addedMNs.push_back(std::make_shared(*dmn, translation.Id(dmn->GetInternalId()))); + } + for (const auto& [id, state_diff] : diff.updatedMNs) result.updatedMNs.emplace(translation.Id(id), state_diff); + for (const uint64_t id : diff.removedMns) result.removedMns.emplace(translation.Id(id)); + translated << result; + } else { + CDeterministicMNList list; + value >> list; + translated << list.Renumbered([&](const CDeterministicMN& dmn) { return translation.Id(dmn.GetInternalId()); }, + translation.Total(list.GetTotalRegisteredCount())); + } + value = std::move(translated); + } catch (const std::exception& e) { + LogPrintf("ERROR: %s: %s\n", __func__, e.what()); + return false; + } + return true; +} + +std::optional> MNIdTranslationTable(const CDeterministicMNList& snapshot_base, + const CDeterministicMNList& normal_base) +{ + MNIdTranslation translation{snapshot_base.GetTotalRegisteredCount(), normal_base.GetTotalRegisteredCount(), {}}; + bool complete{snapshot_base.GetCounts().total() == normal_base.GetCounts().total()}; + snapshot_base.ForEachMN(/*onlyValid=*/false, [&](const CDeterministicMN& dmn) { + const auto normal{normal_base.GetMN(dmn.proTxHash)}; + if (!normal) { + complete = false; + return; + } + translation.base_ids.emplace(dmn.GetInternalId(), normal->GetInternalId()); + }); + if (!complete) return std::nullopt; + DataStream table{}; + table << translation; + return std::vector{UCharCast(table.data()), UCharCast(table.data() + table.size())}; +} + CDeterministicMNManager::CDeterministicMNManager(CEvoDB& evoDb, CMasternodeMetaMan& mn_metaman) : m_evoDb{evoDb}, m_mn_metaman{mn_metaman} { + m_views.SetOwner(evoDb); + evoDb.SetMNRecordTranslation(TranslateMNRecord); } CDeterministicMNManager::~CDeterministicMNManager() = default; +bool CDeterministicMNManager::SeedListForBlock(const EvoViewToken& view, const CDeterministicMNList& list) +{ + if (!Assume(m_evoDb.HasActiveTransaction())) return false; + m_evoDb.RequireTransactionView(view); + if (!m_evoDb.WriteSeed(std::make_pair(DB_LIST_SNAPSHOT, list.GetBlockHash()), list)) { + return false; + } + LOCK(cs); + View().mnListsCache.erase(list.GetBlockHash()); + View().mnListDiffsCache.erase(list.GetBlockHash()); + return true; +} + bool CDeterministicMNManager::ProcessBlock(gsl::not_null pindex, BlockValidationState& state, const CDeterministicMNList& oldList, const CDeterministicMNList& newList, MNListUpdates& updatesRet, kernel::Notifications& notifications) @@ -733,6 +847,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 +860,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"); @@ -809,11 +925,12 @@ void CDeterministicMNManager::ResetPlatformBans(const CBlock& block, const CBloc } } -void CDeterministicMNManager::DiscardBlock(const uint256& block_hash) +void CDeterministicMNManager::DiscardBlock(const EvoViewToken& view, const uint256& block_hash) { LOCK(cs); - mnListsCache.erase(block_hash); - mnListDiffsCache.erase(block_hash); + auto& state{m_views.For(view)}; + state.mnListsCache.erase(block_hash); + state.mnListDiffsCache.erase(block_hash); } bool CDeterministicMNManager::UndoBlock(gsl::not_null pindex, MNListUpdates& updatesRet) @@ -825,15 +942,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 +977,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 +991,46 @@ 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); + // At or below a snapshot base the snapshot view carries full lists + // only. A missing one is outside the carried set: never reconstruct it + // from diffs that do not exist there, and never guess an empty list. + if (const EvoViewToken current{m_evoDb.CurrentView()}; + current.AtOrBelowSnapshotBase(pindex->nHeight)) { + throw BlockDataUnavailableError(strprintf("CDeterministicMNManager::%s -- masternode list for block %s %s", + __func__, pindex->GetBlockHash().ToString(), + BLOCK_DATA_UNAVAILABLE_SUFFIX)); + } // 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 +1056,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 +1096,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 +1124,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 +1157,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 +1184,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 +1399,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()); @@ -1312,6 +1457,10 @@ CDeterministicMNManager::RecalcDiffsResult CDeterministicMNManager::RecalculateA const CBlockIndex* from_index = snapshot_blocks[i]; const CBlockIndex* to_index = snapshot_blocks[i + 1]; + // Verification and repair are NORMAL-only lifecycle operations. + LOCK(::cs_main); + auto normal_reads = m_evoDb.BeginTransaction(EvoDbIdentity::NORMAL); + // Load the snapshots from disk CDeterministicMNList from_snapshot; CDeterministicMNList to_snapshot; @@ -1373,12 +1522,19 @@ 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. + LOCK(::cs_main); + auto normal_reads = m_evoDb.BeginTransaction(EvoDbIdentity::NORMAL); + return m_evoDb.Exists(DB_LIST_REPAIRED); +} void CDeterministicMNManager::CompleteRepair() { AssertLockHeld(::cs_main); - auto dbTx = m_evoDb.BeginTransaction(); + // Repair is a NORMAL-only lifecycle operation. + auto dbTx = m_evoDb.BeginTransaction(EvoDbIdentity::NORMAL); m_evoDb.Write(DB_LIST_REPAIRED, 1); dbTx->Commit(); } @@ -1596,10 +1752,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..e7813ba39ef1 100644 --- a/src/evo/deterministicmns.h +++ b/src/evo/deterministicmns.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -23,8 +24,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -68,6 +71,13 @@ class CDeterministicMN // only non-initial values assert(_internalId != std::numeric_limits::max()); } + //! A copy of `other` under another internal id. + CDeterministicMN(const CDeterministicMN& other, uint64_t _internalId) : + CDeterministicMN{other} + { + assert(_internalId != std::numeric_limits::max()); + internalId = _internalId; + } template CDeterministicMN(deserialize_type, Stream& s) { s >> *this; } @@ -81,6 +91,14 @@ class CDeterministicMN READWRITE(obj.nType); } + //! Every serialized field but the internal id, which each node assigns + //! locally. + template + void SerializeWithoutInternalId(Stream& s) const + { + s << proTxHash << collateralOutpoint << nOperatorReward << pdmnState << nType; + } + [[nodiscard]] bool HasInternalId() const { return internalId != std::numeric_limits::max(); } [[nodiscard]] uint64_t GetInternalId() const; @@ -470,6 +488,11 @@ class CDeterministicMNList const CDeterministicMNListDiff& diff) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); + /** This list with each masternode's internal id replaced by `new_id(dmn)` + * and the registration counter by `total_registered_count`. */ + [[nodiscard]] CDeterministicMNList Renumbered(const std::function& new_id, + uint32_t total_registered_count) const; + void AddMN(const CDeterministicMNCPtr& dmn, bool fBumpTotalCount = true) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); void UpdateMN(const CDeterministicMN& oldDmn, const std::shared_ptr& pdmnState) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_sml_mutex); @@ -798,6 +821,16 @@ struct MNListUpdates inline constexpr std::string_view BLOCK_DATA_UNAVAILABLE_SUFFIX{ "is not available (pruned or below an unvalidated snapshot base)"}; +/** Translation table from the internal ids of a snapshot generation into + * NORMAL's, for promotion: the ids the masternodes of the base list hold in + * each view, and the counters both views had there. None if the two lists do + * not hold the same masternodes. */ +std::optional> MNIdTranslationTable(const CDeterministicMNList& snapshot_base, + const CDeterministicMNList& normal_base); + +//! CEvoDB::MNRecordTranslation for masternode list and list-diff records. +bool TranslateMNRecord(Span table, Span key, DataStream& value); + class CDeterministicMNManager { static constexpr int DISK_SNAPSHOT_PERIOD = 576; // once per day @@ -817,10 +850,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; @@ -837,21 +883,54 @@ class CDeterministicMNManager /** Apply local metadata updates only after successful active-chain connection. */ void ResetPlatformBans(const CBlock& block, const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); - /** Drop candidate state whose EvoDB transaction was rolled back. */ - void DiscardBlock(const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(!cs); + /** Drop candidate state of `view` whose EvoDB transaction was rolled back. */ + void DiscardBlock(const EvoViewToken& view, const uint256& block_hash) EXCLUSIVE_LOCKS_REQUIRED(!cs); void UpdatedBlockTip(gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs); 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); + /** Seed a canonical full list into `view`, inside the caller's open EvoDB + * transaction for that view. */ + bool SeedListForBlock(const EvoViewToken& view, const CDeterministicMNList& list) 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 +969,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..365d5b4ffeb9 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}, @@ -87,6 +91,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 +117,72 @@ 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); +} + +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::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 +198,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 @@ -180,6 +253,7 @@ bool CEvoDB::CommitRootTransaction(EvoDbIdentity identity, bool sync) { AssertLockHeld(::cs_main); LOCK(cs); + if (sync && m_sync_failpoint) throw dbwrapper_error("synced write failed (test failpoint)"); auto& context = GetContext(identity); assert(context.cur_transaction.IsClean()); context.root_transaction.Commit(); @@ -274,7 +348,8 @@ 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; + UpdateLiveGeneration(); + SetDefaultIdentityLocked(m_snapshot_generation ? m_default_identity : EvoDbIdentity::NORMAL); } bool CEvoDB::TransactionsClean() const @@ -297,7 +372,7 @@ bool IsValid(const EvoPromotionJournal& journal) bool CEvoDB::CreateSnapshotGeneration(const uint256& base, int base_height) { LOCK(cs); - if (m_snapshot_generation) return false; + if (m_snapshot_generation || m_revoked_generation) return false; uint32_t generation{1}; if (db->Exists(EVODB_GENERATION_NEXT) && !db->Read(EVODB_GENERATION_NEXT, generation)) { LogPrintf("ERROR: %s: cannot read the next snapshot EvoDB generation id\n", __func__); @@ -322,7 +397,8 @@ bool CEvoDB::CreateSnapshotGeneration(const uint256& base, int base_height) return true; } -bool CEvoDB::PublishSnapshotGeneration(const std::optional& base_mn_list_hash) +bool CEvoDB::PublishSnapshotGeneration(const std::optional& base_mn_list_hash, + const std::vector& evo_section) { LOCK(cs); if (!m_snapshot_generation || m_snapshot_generation->state != EvoGenerationState::UNPUBLISHED) return false; @@ -332,16 +408,28 @@ bool CEvoDB::PublishSnapshotGeneration(const std::optional& base_mn_lis batch.Write(GenerationRecordKey(record.generation), record); batch.Write(EVODB_DUAL_CHAINSTATE, uint8_t{1}); if (base_mn_list_hash) batch.Write(EVODB_SNAPSHOT_MNLIST_HASH, *base_mn_list_hash); + // Raw: a length-prefixed vector reads back only up to MAX_SIZE. + if (!evo_section.empty()) batch.Write(EVODB_SNAPSHOT_EVO_SECTION, Span{evo_section}); if (!db->WriteBatch(batch, /*fSync=*/true)) return false; m_snapshot_generation = record; + UpdateLiveGeneration(); return true; } +std::optional> CEvoDB::ReadRetainedEvoSection() const +{ + LOCK(cs); + DataStream evo_section; + if (!db->ReadDataStream(EVODB_SNAPSHOT_EVO_SECTION, evo_section)) return std::nullopt; + return std::vector{UCharCast(evo_section.data()), UCharCast(evo_section.data() + evo_section.size())}; +} + util::Result CEvoDB::LoadSnapshotGenerations() { LOCK(cs); if (!Assume(TransactionsClean())) return util::Error{_("Evo database transactions are pending at startup.")}; BindSnapshotGeneration(std::nullopt); + m_revoked_generation = false; std::vector records; { std::unique_ptr it{db->NewIterator()}; @@ -478,9 +566,11 @@ bool CEvoDB::CollectGeneration(uint32_t generation, bool erase_record) bool CEvoDB::DiscardBoundGeneration() { + if (m_rejection_failpoint) throw dbwrapper_error("rejection write failed (test failpoint)"); CDBBatch batch{*db}; batch.Erase(EVODB_SNAPSHOT_MNLIST_HASH); batch.Erase(EVODB_BACKGROUND_MNLIST_HASH); + batch.Erase(EVODB_SNAPSHOT_EVO_SECTION); batch.Erase(EVODB_DUAL_CHAINSTATE); batch.Erase(EVODB_PROMOTION_JOURNAL); if (m_snapshot_generation) { @@ -503,12 +593,26 @@ bool CEvoDB::AbandonSnapshotGeneration() AssertLockHeld(::cs_main); LOCK(cs); if (!Assume(!active_transaction.has_value())) return false; + ClearSnapshotTransactions(); + return DiscardBoundGeneration(); +} + +void CEvoDB::RevokeSnapshotGeneration() +{ + AssertLockHeld(::cs_main); + LOCK(cs); + if (m_snapshot_generation) m_revoked_generation = true; + ClearSnapshotTransactions(); + BindSnapshotGeneration(std::nullopt); +} + +void CEvoDB::ClearSnapshotTransactions() +{ if (auto it{transaction_contexts.find(EvoDbIdentity::SNAPSHOT)}; it != transaction_contexts.end()) { it->second->cur_transaction.Clear(); it->second->root_transaction.Clear(); it->second->root_batch.Clear(); } - return DiscardBoundGeneration(); } bool CEvoDB::DiscardSnapshotMarkers() @@ -518,7 +622,7 @@ bool CEvoDB::DiscardSnapshotMarkers() return DiscardBoundGeneration(); } -bool CEvoDB::PrepareSnapshotPromotion(const uint256& snapshot_tip) +bool CEvoDB::PrepareSnapshotPromotion(const uint256& snapshot_tip, std::vector mn_id_translation) { LOCK(cs); if (!m_snapshot_generation || !Assume(TransactionsClean())) return false; @@ -541,6 +645,7 @@ bool CEvoDB::PrepareSnapshotPromotion(const uint256& snapshot_tip) journal.generation = m_snapshot_generation->generation; journal.base = m_snapshot_generation->base; journal.tip = snapshot_tip; + journal.mn_id_translation = std::move(mn_id_translation); uint256 base_mn_list_hash; if (db->Read(EVODB_SNAPSHOT_MNLIST_HASH, base_mn_list_hash)) journal.base_mn_list_hash = base_mn_list_hash; EvoGenerationRecord record{*m_snapshot_generation}; @@ -551,6 +656,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; } @@ -598,6 +704,13 @@ bool CEvoDB::MergeGeneration(EvoPromotionJournal& journal) if (!db->ReadDataStream(raw_key, value)) return false; DataStream normal_value{}; const bool in_normal{db->ReadDataStream(key, normal_value)}; + if (!journal.mn_id_translation.empty() && + (!m_mn_record_translation || + !m_mn_record_translation(MakeByteSpan(journal.mn_id_translation), MakeByteSpan(key), value))) { + LogPrintf("ERROR: %s: cannot carry the masternode ids of snapshot generation %u into NORMAL for key %s\n", + __func__, journal.generation, HexStr(key)); + return false; + } if (!in_normal) { batch.Write(key, Span{value}); } else if (!SameBytes(normal_value, value)) { @@ -641,7 +754,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; @@ -664,12 +777,14 @@ bool CEvoDB::PromoteSnapshotMarkers(const uint256& expected_snapshot_tip) batch.Write(EVODB_BEST_BLOCK, journal.tip); batch.Erase(EVODB_SNAPSHOT_MNLIST_HASH); batch.Erase(EVODB_BACKGROUND_MNLIST_HASH); + batch.Erase(EVODB_SNAPSHOT_EVO_SECTION); batch.Erase(EVODB_DUAL_CHAINSTATE); batch.Erase(EVODB_PROMOTION_JOURNAL); batch.Erase(GenerationRecordKey(journal.generation)); 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..212f660458c2 100644 --- a/src/evo/evodb.h +++ b/src/evo/evodb.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -15,11 +16,16 @@ #include #include +#include #include +#include #include #include #include +#include +#include #include +#include namespace util { struct DbWrapperParams; @@ -45,6 +51,8 @@ static const std::string EVODB_GENERATION_RECORD = "assumeutxo_generation"; static const std::string EVODB_GENERATION_NEXT = "assumeutxo_next_generation"; static const std::string EVODB_PROMOTION_JOURNAL = "assumeutxo_promotion_journal"; static const std::string EVODB_GENERATION_NAMESPACE = "assumeutxo_state"; +// The evo section the live snapshot generation was seeded from. +static const std::string EVODB_SNAPSHOT_EVO_SECTION = "assumeutxo_evo_section"; // A generation's seed manifest: (EVODB_SEED_MANIFEST, key) for every key it was // seeded with, stored in the generation's own namespace. static const std::string EVODB_SEED_MANIFEST = "assumeutxo_seed_manifest"; @@ -83,8 +91,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 { @@ -140,11 +166,15 @@ struct EvoPromotionJournal { EvoPromotionPhase phase{EvoPromotionPhase::PREPARED}; //! Generation-relative key the merge resumes after; empty to start over. std::vector cursor; + //! How the merge carries masternode internal ids into NORMAL's; see + //! CEvoDB::SetMNRecordTranslation. Empty to merge records unchanged. + std::vector mn_id_translation; SERIALIZE_METHODS(EvoPromotionJournal, obj) { uint8_t phase{static_cast(obj.phase)}; - READWRITE(obj.schema_version, obj.generation, obj.base, obj.tip, obj.base_mn_list_hash, phase, obj.cursor); + READWRITE(obj.schema_version, obj.generation, obj.base, obj.tip, obj.base_mn_list_hash, phase, obj.cursor, + obj.mn_id_translation); SER_READ(obj, obj.phase = static_cast(phase)); } }; @@ -304,11 +334,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,9 +376,58 @@ 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); + //! Raise EvoViewBindingError unless this thread holds a transaction open + //! that resolves to `view`. + void RequireTransactionView(const EvoViewToken& view) const EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + if (!HoldsTransaction() || MakeView(*active_transaction) != view) { + throw EvoViewBindingError("EvoDB: no open transaction of the view to write"); + } + } + //! Whether this thread holds a transaction of `identity` open. + bool HoldsTransaction(EvoDbIdentity identity) const EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + return HoldsTransaction() && *active_transaction == identity; + } //! The current view of a chainstate with the given identity. EvoViewToken ViewFor(EvoDbIdentity identity) const EXCLUSIVE_LOCKS_REQUIRED(!cs); //! Whether this thread's accesses resolve to the active chainstate's view. @@ -347,6 +437,10 @@ class CEvoDB LOCK(cs); return GetCurrentIdentity() == m_default_identity; } + //! 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); CurTransaction& GetCurTransaction() EXCLUSIVE_LOCKS_REQUIRED(cs) { @@ -408,6 +502,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, @@ -440,6 +551,18 @@ class CEvoDB return true; } + //! Rewrite a promoted record `value` stored under `key` from the + //! generation's masternode internal ids into NORMAL's, per the journal's + //! translation table. Each node numbers masternodes by its own history, + //! and a snapshot generation numbers them as the snapshot did. Records it + //! does not know are left unchanged; false fails promotion. + using MNRecordTranslation = std::function table, Span key, DataStream& value)>; + void SetMNRecordTranslation(MNRecordTranslation translation) EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + m_mn_record_translation = std::move(translation); + } + template bool Exists(const K& key) EXCLUSIVE_LOCKS_REQUIRED(!cs) { @@ -483,7 +606,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); @@ -503,11 +626,16 @@ class CEvoDB /** Start a new, unpublished snapshot generation for a snapshot whose base * block is `base`, and bind the SNAPSHOT identity to it. Fails if a - * generation is already live. */ + * generation is already live, a revoked one included. */ bool CreateSnapshotGeneration(const uint256& base, int base_height) EXCLUSIVE_LOCKS_REQUIRED(!cs); - /** Publish the bound generation together with the dual-chainstate markers. */ - bool PublishSnapshotGeneration(const std::optional& base_mn_list_hash) EXCLUSIVE_LOCKS_REQUIRED(!cs); + /** Publish the bound generation together with the dual-chainstate markers + * and the encoded evo section it was seeded from (empty for a UTXO-only + * snapshot). */ + bool PublishSnapshotGeneration(const std::optional& base_mn_list_hash, + const std::vector& evo_section = {}) EXCLUSIVE_LOCKS_REQUIRED(!cs); + //! The evo section the live generation was published with, if any. + std::optional> ReadRetainedEvoSection() const EXCLUSIVE_LOCKS_REQUIRED(!cs); /** Startup: collect unpublished and rejected generations, then bind the * live one. Fails closed if a generation has another SCHEMA_VERSION, or @@ -517,9 +645,11 @@ class CEvoDB /** Abandon the bound generation of a snapshot whose activation failed. */ bool AbandonSnapshotGeneration() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs); - /** Record the decision to promote the bound generation at `snapshot_tip`. - * Must precede the first coins-directory rename. */ - bool PrepareSnapshotPromotion(const uint256& snapshot_tip) EXCLUSIVE_LOCKS_REQUIRED(!cs); + /** Record the decision to promote the bound generation at `snapshot_tip`, + * merging its masternode records through `mn_id_translation`. Must + * precede the first coins-directory rename. */ + bool PrepareSnapshotPromotion(const uint256& snapshot_tip, std::vector mn_id_translation = {}) + EXCLUSIVE_LOCKS_REQUIRED(!cs); std::optional ReadPromotionJournal() const EXCLUSIVE_LOCKS_REQUIRED(!cs); /** @@ -535,6 +665,12 @@ class CEvoDB * one synced batch, preserving NORMAL. The REJECTED record remains until * CollectRejectedGenerations(), after the coins directory is invalidated. */ bool DiscardSnapshotMarkers() EXCLUSIVE_LOCKS_REQUIRED(!cs); + /** Stop using the bound generation for the rest of this run when its + * rejection could not be saved: it is retired as a saved rejection retires + * it, so no access reaches it, and what it has not written is dropped. Its + * records stay on disk for startup recovery to reject; until then no new + * generation can be created. */ + void RevokeSnapshotGeneration() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs); //! Whether a rejected generation still awaits its coins invalidation, or //! the generation records cannot be read. bool HasRejectedGeneration() const EXCLUSIVE_LOCKS_REQUIRED(!cs); @@ -554,6 +690,20 @@ class CEvoDB LOCK(cs); m_promotion_failpoint = failpoint; } + //! Make DiscardSnapshotMarkers and AbandonSnapshotGeneration throw without + //! writing, as a failed LevelDB write does. + void SetRejectionFailpointForTesting(bool fail) EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + m_rejection_failpoint = fail; + } + //! Make every synced CommitRootTransaction throw without writing, as a + //! failed LevelDB write does. + void SetSyncFailpointForTesting(bool fail) EXCLUSIVE_LOCKS_REQUIRED(!cs) + { + LOCK(cs); + m_sync_failpoint = fail; + } //! Records merged per batch, so tests can stop a merge part-way. void SetMergeBatchSizeForTesting(size_t size) EXCLUSIVE_LOCKS_REQUIRED(!cs) { @@ -586,6 +736,9 @@ class CEvoDB } void BindSnapshotGeneration(std::optional record) EXCLUSIVE_LOCKS_REQUIRED(cs); + //! Drop what the SNAPSHOT transaction trees hold, without writing it. + void ClearSnapshotTransactions() 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); @@ -594,10 +747,54 @@ 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}; + std::atomic m_has_live_generation{false}; + //! 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}; + bool m_rejection_failpoint GUARDED_BY(cs){false}; + bool m_sync_failpoint GUARDED_BY(cs){false}; + //! A revoked generation is still live on disk. + bool m_revoked_generation GUARDED_BY(cs){false}; + MNRecordTranslation m_mn_record_translation GUARDED_BY(cs); size_t m_merge_batch_size GUARDED_BY(cs){10000}; }; +//! 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, 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) +{ + try { + round(); + } catch (const evo::LocalStateError& e) { + LogEvoRoundFailure(what, evodb ? std::make_optional(evodb->ActiveView().generation) : std::nullopt, e.what()); + return false; + } + LogEvoRoundRecovery(what); + return true; +} + +//! Wrap `task`, handed to another thread, so that a local Evo state error ends +//! it with a log line instead of escaping into the thread that runs it. +template +auto ContainLocalEvoErrors(F task) +{ + return [task = std::move(task)](auto&&... args) mutable { + try { + task(std::forward(args)...); + } catch (const evo::LocalStateError& e) { + LogPrintf("ERROR: Evo state unavailable to a queued task: %s\n", e.what()); + } + }; +} + #endif // BITCOIN_EVO_EVODB_H diff --git a/src/evo/mnhftx.cpp b/src/evo/mnhftx.cpp index 03235efd2e67..1e6eff97ad54 100644 --- a/src/evo/mnhftx.cpp +++ b/src/evo/mnhftx.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -51,6 +52,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; } @@ -65,7 +67,7 @@ CMNHFManager::Signals CMNHFManager::GetSignalsStage(const CBlockIndex* const pin { if (!DeploymentActiveAfter(pindexPrev, m_consensus_params, Consensus::DEPLOYMENT_V20)) return {}; - Signals signals_tmp = GetForBlock(pindexPrev); + Signals signals_tmp = GetRecord(pindexPrev, /*derive_requested=*/true); if (pindexPrev == nullptr) return {}; const int height = pindexPrev->nHeight + 1; @@ -286,8 +288,42 @@ bool CMNHFManager::UndoBlock(const CBlock& block, const CBlockIndex* const pinde } CMNHFManager::Signals CMNHFManager::GetForBlock(const CBlockIndex* pindex) +{ + return GetRecord(pindex, /*derive_requested=*/false); +} + +std::optional> CMNHFManager::SeededBase(const EvoViewToken& view) +{ + if (view.identity != EvoDbIdentity::SNAPSHOT) return std::nullopt; + const CBlockIndex* base{WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(view.base))}; + if (base == nullptr) return std::nullopt; + auto record{GetFromCache(base)}; + if (!record) return std::nullopt; + return std::make_pair(base, std::move(*record)); +} + +CMNHFManager::Signals CMNHFManager::GetRecord(const CBlockIndex* pindex, bool derive_requested) { 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 (const EvoViewToken view{m_evoDb.CurrentView()}; view.identity == EvoDbIdentity::SNAPSHOT) { + // A derived record is exact once filtered, so it may only answer a + // stage, never stand in for a raw record. Off the base's chain the + // base record says nothing. + if (derive_requested && view.AtOrBelowSnapshotBase(pindex->nHeight)) { + if (const auto base{SeededBase(view)}; base && base->first->GetAncestor(pindex->nHeight) == pindex) { + Signals derived; + for (const auto& [bit, height] : base->second) { + if (height <= pindex->nHeight) derived.emplace(bit, height); + } + return derived; + } + } + 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 +331,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 +391,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; } } @@ -384,7 +422,11 @@ void CMNHFManager::AddToCache(const Signals& signals, const CBlockIndex* const p { assert(pindex != nullptr); const uint256& blockHash = pindex->GetBlockHash(); + const EvoViewToken view{m_evoDb.CurrentView()}; + // A snapshot view's only record at or below its base is the seeded one: + // promotion fails on any other record NORMAL holds too. if (DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_V20) && Assume(m_evoDb.HasActiveTransaction()) && + !view.AtOrBelowSnapshotBase(pindex->nHeight) && !m_evoDb.WriteDerived(std::make_pair(DB_SIGNALS_v2, blockHash), signals)) { // A mismatch is local EvoDB corruption, not a statement about the // block. Abort here: some callers (miner, RPC) never pass through a @@ -395,22 +437,53 @@ void CMNHFManager::AddToCache(const Signals& signals, const CBlockIndex* const p m_notifications.fatalError(msg); throw EvoDbInconsistencyError(msg); } - { - LOCK(cs_cache); - mnhfCache.insert(blockHash, signals); + LOCK(cs_cache); + mnhfCache.For(view).insert(blockHash, signals); +} + +bool CMNHFManager::SeedSignals(const EvoViewToken& view, const CBlockIndex* pindex, const Signals& signals) +{ + if (!Assume(pindex != nullptr) || !Assume(m_evoDb.HasActiveTransaction())) return false; + // Seeding may precede the chain checks, which refuse such a record. + if (std::ranges::any_of(signals, [&](const auto& signal) { return signal.second < 0 || signal.second > pindex->nHeight; })) { + return false; } + m_evoDb.RequireTransactionView(view); + if (!m_evoDb.WriteSeed(std::make_pair(DB_SIGNALS_v2, pindex->GetBlockHash()), signals)) { + return false; + } + LOCK(cs_cache); + mnhfCache.For(view).erase(pindex->GetBlockHash()); + return true; } -bool CMNHFManager::ForceSignalDBUpdate(const CBlockIndex* tip) +bool CMNHFManager::ForceSignalDBUpdate(const EvoViewToken& view, const CBlockIndex* tip) { // 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 72d405a9d96f..f86aeca1c3a3 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; @@ -134,30 +136,59 @@ class CMNHFManager : public AbstractEHFManager bool UndoBlock(const CBlock& block, const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); // Implements interface. Only reads state computed when a block was connected, and throws if - // pindexPrev has none (e.g. it was never connected). A block whose connection failed after its + // pindexPrev has none (e.g. it was never connected); a snapshot view derives the stage of its + // base and the base's ancestors from the record it carries. A block whose connection failed after its // special transactions were processed can still be in the cache, so a caller that takes a block // 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); + /** Seed the signal record of a snapshot base into `view`, inside the + * caller's open EvoDB transaction for that view. */ + bool SeedSignals(const EvoViewToken& view, const CBlockIndex* pindex, const Signals& signals) + EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); /** * 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); -private: - void AddToCache(const Signals& signals, const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); - /** - * 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. + * The raw signal record of a block, before GetSignalsStage() filters it, from the cache or + * EvoDB; it is never rebuilt. Throws EvoDbMissingStateError if there is 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); +private: + /** + * GetForBlock(), except that with `derive_requested` the record of + * `pindex` itself may be derived. A snapshot view holds the record of its + * base and none below it; for a block on the base's chain at or below the + * base, the base record's signals mined up to that block are a record with + * the block's own stage: a signal is only ever dropped by the expiry rule, + * which depends on the signal alone and which GetSignalsStage() re-applies. + * A derived record is never cached or persisted, and never derived for a + * block off the base's chain, which only that branch's own records can + * answer, or where the view carries no base record. + */ + Signals GetRecord(const CBlockIndex* pindex, bool derive_requested) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); + //! The base of a snapshot view and the signal record it carries, if any. + std::optional> SeededBase(const EvoViewToken& view) + EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); + + void AddToCache(const Signals& signals, const CBlockIndex* const pindex) EXCLUSIVE_LOCKS_REQUIRED(!cs_cache); + /** * This function access to in-memory cache or to evo db but does not calculate anything * NOTE: that some signals could expired between blocks. diff --git a/src/evo/smldiff.cpp b/src/evo/smldiff.cpp index 6413b3bf58c1..2f7fa8e07e45 100644 --- a/src/evo/smldiff.cpp +++ b/src/evo/smldiff.cpp @@ -20,8 +20,11 @@ #include -// Forward declaration -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex); +// Forward declarations +std::optional> GetNonNullCoinbaseChainlock(const EvoViewToken& view, + const node::BlockManager& blockman, + const CBlockIndex* pindex); +std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, const CBlockIndex& index); CSimplifiedMNListDiff::CSimplifiedMNListDiff() = default; @@ -65,7 +68,8 @@ bool CSimplifiedMNListDiff::BuildQuorumsDiff(const CBlockIndex* baseBlockIndex, return true; } -bool CSimplifiedMNListDiff::BuildQuorumChainlockInfo(const llmq::CQuorumManager& qman, const node::BlockManager& blockman, const CBlockIndex* blockIndex) +bool CSimplifiedMNListDiff::BuildQuorumChainlockInfo(const llmq::CQuorumManager& qman, const node::BlockManager& blockman, + const CBlockIndex* blockIndex, std::string& error) { // Group quorums (indexes corresponding to entries of newQuorums) per CBlockIndex containing the expected CL // signature in CbTx. We want to avoid to load CbTx now, as more than one quorum will target the same block: hence @@ -94,7 +98,21 @@ 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); + std::optional> cbcl; + if (qman.CurrentView().identity == EvoDbIdentity::SNAPSHOT) { + // Without the work block's body the snapshot view cannot tell a + // certificate from none; never serve a guessed null signature. + CBlock block; + if (WITH_LOCK(::cs_main, return (pWorkBaseBlockIndex->nStatus & BLOCK_HAVE_DATA) == 0) || + !blockman.ReadBlockFromDisk(block, *pWorkBaseBlockIndex)) { + error = strprintf("coinbase ChainLock of block %s %s", pWorkBaseBlockIndex->GetBlockHash().ToString(), + BLOCK_DATA_UNAVAILABLE_SUFFIX); + return false; + } + cbcl = GetNonNullCoinbaseChainlock(block, *pWorkBaseBlockIndex); + } else { + cbcl = GetNonNullCoinbaseChainlock(qman.CurrentView(), blockman, pWorkBaseBlockIndex); + } CBLSSignature sig; if (cbcl.has_value()) { sig = cbcl.value().first; @@ -218,8 +236,16 @@ bool BuildSimplifiedMNListDiff(CDeterministicMNManager& dmnman, const Chainstate } if (DeploymentActiveAfter(blockIndex, chainman.GetConsensus(), Consensus::DEPLOYMENT_V20)) { - if (!mnListDiffRet.BuildQuorumChainlockInfo(qman, chainman.m_blockman, blockIndex)) { - errorRet = strprintf("failed to build quorum chainlock info"); + std::string chainlock_error; + try { + if (!mnListDiffRet.BuildQuorumChainlockInfo(qman, chainman.m_blockman, blockIndex, chainlock_error)) { + errorRet = chainlock_error.empty() ? "failed to build quorum chainlock info" : chainlock_error; + return false; + } + } catch (const BlockDataUnavailableError& e) { + // Unavailable snapshot-view state; the sentinel keeps the requesting + // peer from being penalized. + errorRet = strprintf("%s %s", e.what(), BLOCK_DATA_UNAVAILABLE_SUFFIX); return false; } } diff --git a/src/evo/smldiff.h b/src/evo/smldiff.h index d299b383ceaa..265138040103 100644 --- a/src/evo/smldiff.h +++ b/src/evo/smldiff.h @@ -89,7 +89,12 @@ class CSimplifiedMNListDiff bool BuildQuorumsDiff(const CBlockIndex* baseBlockIndex, const CBlockIndex* blockIndex, const llmq::CQuorumBlockProcessor& quorum_block_processor); - bool BuildQuorumChainlockInfo(const llmq::CQuorumManager& qman, const node::BlockManager& blockman, const CBlockIndex* blockIndex); + /** Collect the coinbase ChainLock each new quorum's work block certifies. + * In a snapshot view, a certificate this node cannot read is an error + * carrying BLOCK_DATA_UNAVAILABLE_SUFFIX, never a null signature; NORMAL + * answers from the blocks it has, as before. */ + bool BuildQuorumChainlockInfo(const llmq::CQuorumManager& qman, const node::BlockManager& blockman, + const CBlockIndex* blockIndex, std::string& error); [[nodiscard]] static RPCResult GetJsonHelp(const std::string& key, bool optional); [[nodiscard]] UniValue ToJson(bool extended = false) const; diff --git a/src/evo/snapshot.cpp b/src/evo/snapshot.cpp index fe8cecfa391c..6949c544b8f9 100644 --- a/src/evo/snapshot.cpp +++ b/src/evo/snapshot.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -16,6 +17,7 @@ #include #include #include +#include #include #include @@ -124,35 +126,30 @@ void ValidateCanonicalMNInvariants(const CDeterministicMNList& list) } // namespace -std::vector EvoSnapshotReconstructionHeights( - int base_height, const std::vector& enabled_llmqs) -{ - if (base_height < 0) throw std::invalid_argument("invalid reconstruction base height"); - std::vector heights; - for (const auto& params : enabled_llmqs) { - if (params.dkgInterval <= 0 || params.signingActiveQuorumCount <= 0) { - throw std::invalid_argument("invalid reconstruction LLMQ parameters"); - } - const int h{base_height - base_height % params.dkgInterval}; - const size_t count{params.useRotation ? EVO_SNAPSHOT_ROTATION_CYCLES - : SnapshotCommitmentCount(params, /*rotation_enabled=*/false)}; - const size_t first{params.useRotation ? 1U : 0U}; - for (size_t i{first}; i < first + count; ++i) { - const int quorum_height{h - static_cast(i) * params.dkgInterval}; - heights.push_back({params.type, params.useRotation, quorum_height, - quorum_height - llmq::WORK_DIFF_DEPTH}); - } - } - return heights; -} - uint256 CanonicalMNListHash(const CDeterministicMNList& list) { HashWriter writer{}; - SerializeCanonicalMNList(writer, list); + writer << list.GetBlockHash() << list.GetHeightForSnapshotCodec(); + std::vector mns; + mns.reserve(list.GetCounts().total()); + list.ForEachMNShared(/*onlyValid=*/false, [&](const auto& dmn) { mns.emplace_back(dmn); }); + std::sort(mns.begin(), mns.end(), [](const auto& a, const auto& b) { return a->proTxHash < b->proTxHash; }); + WriteCompactSize(writer, mns.size()); + for (const auto& dmn : mns) dmn->SerializeWithoutInternalId(writer); return writer.GetHash(); } +std::map CanonicalMNIds(const std::vector& lists) +{ + std::map ids; + for (const auto* list : lists) { + list->ForEachMN(/*onlyValid=*/false, [&](const auto& dmn) { ids.emplace(dmn.proTxHash, 0); }); + } + uint64_t rank{0}; + for (auto& [_, id] : ids) id = rank++; + return ids; +} + bool ReconstructHistoricalMNLists(const EvoSnapshot& snapshot, std::map& lists, std::string& error, size_t max_records) { @@ -226,6 +223,30 @@ void EvoSnapshot::Validate(bool require_canonical_order) const } ValidateCanonicalMNInvariants(mn_list); mn_list.ForEachMN(/*onlyValid=*/false, [](const auto& dmn) { ValidateMNEncoding(dmn); }); + if (base_coinbase) { + const CTransaction& coinbase{*base_coinbase}; + // A 64-byte transaction could pass for an inner merkle node. + if (!coinbase.IsCoinBase() || coinbase.nType != TRANSACTION_COINBASE || + coinbase.vExtraPayload.size() > MAX_TX_EXTRA_PAYLOAD || ::GetSerializeSize(coinbase) <= 64 || + ::GetSerializeSize(coinbase) > EVO_SNAPSHOT_MAX_COINBASE_BYTES) { + throw std::ios_base::failure("invalid evo snapshot base coinbase"); + } + // The CbTx header precedes its scheme-dependent fields, so the height + // is readable without knowing the base's BLS scheme. + DataStream payload{coinbase.vExtraPayload}; + uint16_t cbtx_version; + int32_t cbtx_height; + payload >> cbtx_version >> cbtx_height; + if (cbtx_height != mn_list.GetHeightForSnapshotCodec()) { + throw std::ios_base::failure("evo snapshot base coinbase height mismatch"); + } + if (base_coinbase_branch.size() > EVO_SNAPSHOT_MAX_COINBASE_BRANCH) { + throw std::ios_base::failure("oversized evo snapshot base coinbase branch"); + } + } else if (!base_coinbase_branch.empty() || mn_list.GetCounts().total() != 0 || !quorums.empty()) { + // Without a CbTx at the base there can be no MN or quorum state. + throw std::ios_base::failure("evo snapshot state without a base coinbase"); + } if (quorums.size() > Consensus::available_llmqs.size() || historical_mn_list_diffs.size() > EvoSnapshotMaxHistoricalMNLists() || quorum_modifiers.size() > EVO_SNAPSHOT_MAX_MODIFIERS || @@ -247,6 +268,23 @@ void EvoSnapshot::Validate(bool require_canonical_order) const if (credit_pool.indexes.RangeCount() > EVO_SNAPSHOT_MAX_RANGES) { throw std::ios_base::failure("oversized CRangesSet range count"); } + // The window entries sum to the pool's lately unlocked amount and end at + // the base, whose recorded balance is the pool's. + if (credit_history.size() > EVO_SNAPSHOT_MAX_CREDIT_HISTORY) { + throw std::ios_base::failure("oversized evo snapshot credit history"); + } + CAmount window_unlocked{0}; + for (const auto& entry : credit_history) { + const auto sum{CheckedAdd(window_unlocked, entry.unlocked)}; + if (!MoneyRange(entry.credit_pool) || !MoneyRange(entry.unlocked) || !sum || !MoneyRange(*sum)) { + throw std::ios_base::failure("invalid evo snapshot credit history amount"); + } + window_unlocked = *sum; + } + if (window_unlocked != credit_pool.latelyUnlocked || + (!credit_history.empty() && credit_history.back().credit_pool != credit_pool.locked)) { + throw std::ios_base::failure("evo snapshot credit history disagrees with the credit pool"); + } // Consensus admits MNHF signals only for bits below VERSIONBITS_NUM_BITS // and records the mined height, which cannot exceed the base height. for (const auto& [bit, height] : mnhf_signals) { @@ -278,13 +316,11 @@ void EvoSnapshot::Validate(bool require_canonical_order) const } const size_t active_count{static_cast(params.signingActiveQuorumCount)}; const size_t total_count{SnapshotCommitmentCount(params, data.rotation_enabled)}; - // Parameter-derived counts are maxima, not exact requirements: a young - // chain carries however much quorum history exists. The chain-aware - // validation and the completion-time CbTx quorum merkle root establish - // that nothing available was withheld. - if (data.active_commitments.size() > active_count || - data.safety_commitments.size() > total_count - active_count || - data.rotation_snapshots.size() > (data.rotation_enabled ? EVO_SNAPSHOT_ROTATION_CYCLES : size_t{0})) { + // Parameter-derived counts are maxima here. The chain-aware validation + // requires the exact sets the dependency planner derives. + if (data.active_commitments.size() > active_count || data.safety_commitments.size() > total_count - active_count || + data.rotation_snapshots.size() > (data.rotation_enabled ? EvoSnapshotMaxRotationSnapshots(params) : size_t{0}) || + data.bootstrap_work.size() > EVO_SNAPSHOT_MAX_BOOTSTRAP_WORK) { throw std::ios_base::failure("invalid params-derived evo per-type quorum counts"); } std::set quorum_hashes; @@ -303,7 +339,7 @@ void EvoSnapshot::Validate(bool require_canonical_order) const for (const auto& entry : data.rotation_snapshots) { if (entry.cycle_base_block_hash.IsNull() || entry.work_block_hash.IsNull() || !cycle_hashes.insert(entry.cycle_base_block_hash).second || - !historical_hashes.contains(entry.work_block_hash) || + (!historical_hashes.contains(entry.work_block_hash) && entry.work_block_hash != base_block_hash) || entry.snapshot.mnSkipListMode < SnapshotSkipMode::MODE_NO_SKIPPING || entry.snapshot.mnSkipListMode > SnapshotSkipMode::MODE_ALL_SKIPPED || entry.snapshot.activeQuorumMembers.size() > EVO_SNAPSHOT_MAX_MNS || @@ -318,7 +354,22 @@ void EvoSnapshot::Validate(bool require_canonical_order) const required_work_hashes.insert(entry.work_block_hash); required_modifiers.emplace(data.llmq_type, entry.work_block_hash); } + if (require_canonical_order && !IsCanonicallySorted(data.bootstrap_work)) { + throw std::ios_base::failure("noncanonical evo bootstrap work order"); + } + std::set bootstrap_heights; + for (const auto& entry : data.bootstrap_work) { + if (entry.cycle_base_height < 0 || entry.work_block_hash.IsNull() || + !bootstrap_heights.insert(entry.cycle_base_height).second) { + throw std::ios_base::failure("invalid evo bootstrap work entry"); + } + required_work_hashes.insert(entry.work_block_hash); + required_modifiers.emplace(data.llmq_type, entry.work_block_hash); + } } + // The base list is the work list for a work block equal to the base, so + // it has no historical diff of its own. + required_work_hashes.erase(base_block_hash); if (historical_hashes != required_work_hashes) { throw std::ios_base::failure("missing or extra historical MN-list diff target"); } @@ -345,6 +396,37 @@ uint256 GetEvoSnapshotHash(const EvoSnapshot& snapshot) return hash; } +uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector& branch, uint32_t index) +{ + uint256 hash{leaf}; + for (const uint256& node : branch) { + hash = (index & 1) ? Hash(node, hash) : Hash(hash, node); + index >>= 1; + } + return hash; +} + +std::vector BlockMerkleBranch(const CBlock& block, uint32_t index) +{ + std::vector level; + level.reserve(block.vtx.size()); + for (const auto& tx : block.vtx) + level.push_back(tx->GetHash()); + std::vector branch; + while (level.size() > 1) { + // ComputeMerkleRoot pairs an odd last node with itself. + const size_t sibling{(index ^ 1) < level.size() ? (index ^ 1) : index}; + branch.push_back(level[sibling]); + std::vector next; + for (size_t i{0}; i < level.size(); i += 2) { + next.push_back(Hash(level[i], level[std::min(i + 1, level.size() - 1)])); + } + level = std::move(next); + index >>= 1; + } + return branch; +} + bool VerifyEvoSnapshotCbTx(const EvoSnapshot& snapshot, const CCbTx& cbtx, std::string& error) { error.clear(); diff --git a/src/evo/snapshot.h b/src/evo/snapshot.h index 4f1755d6dbb1..afedda83c47a 100644 --- a/src/evo/snapshot.h +++ b/src/evo/snapshot.h @@ -9,13 +9,17 @@ #include #include #include +#include +#include #include #include #include +#include #include #include #include +#include #include #include @@ -25,21 +29,37 @@ #include #include #include +#include #include #include #include #include +class CBlockIndex; +class CChainParams; +class ChainstateManager; class CCbTx; +class CBlock; +class CCreditPoolManager; +class CMNHFManager; +class CEvoDB; +class CSpecialTxProcessor; +struct EvoViewToken; + +namespace llmq { +class CQuorumBlockProcessor; +class CQuorumSnapshotManager; +struct ScanCoverageRecord; +} // namespace llmq +namespace node { +class BlockManager; +} // namespace node namespace evo { -static constexpr uint16_t EVO_SNAPSHOT_VERSION{3}; +static constexpr uint16_t EVO_SNAPSHOT_VERSION{4}; /** Serialized little-endian bytes are "DASHEVO\0". */ static constexpr uint64_t EVO_SNAPSHOT_MARKER{0x004f564548534144ULL}; -// ComputeQuorumMembersByQuarterRotation consumes H-C, H-2C and H-3C. To -// reconstruct both H and the safety cycle H-C, the union is H-C..H-4C. -static constexpr size_t EVO_SNAPSHOT_ROTATION_CYCLES{4}; // A hard allocation bound, not a network population target. 100,000 full MN // records is already far beyond today's list while limiting hostile snapshots // to a tractable decode. Changes above this require a format-version review. @@ -55,7 +75,6 @@ static constexpr size_t EVO_SNAPSHOT_MAX_PAYOUT_SHARES{8}; // each MN a cumulative budget so nested counts cannot multiply decode work. // This comfortably covers protocol-valid scripts and network information. static constexpr size_t EVO_SNAPSHOT_MAX_MN_COMPACT_ITEMS{10'000}; -static constexpr size_t EVO_SNAPSHOT_MAX_MODIFIERS{4'096}; // A cycle's skip list accumulates across every quorum index and the build can // wrap the combined MN list more than once, so a single quorum's size does not // bound its legitimate length. This is a decode ceiling on claimed sizes only, @@ -76,15 +95,73 @@ static constexpr size_t EVO_SNAPSHOT_MAX_QUORUM_SIZE{10'000}; static constexpr size_t EVO_SNAPSHOT_MAX_HASH_PREFIX_RUN{8}; // Every historical entry costs a full traversal, sort, and canonical hash of // the reconstructed list, so a few hundred bytes of zero-operation diffs could -// otherwise drag a maximum-size list across the whole table-wide history -// horizon (~19M record visits). The horizon that sums every table entry is -// unreachable on a real chain: no network enables more than a fraction of the -// LLMQ table at once, so even a ceiling-sized list on a fully loaded mainnet -// configuration stays well below half of this cumulative record budget. +// otherwise drag a maximum-size list across every planned work block: the +// table-wide bound is 436 lists (330 for the mainnet table), ~44M record visits +// at the 100,000-MN ceiling, so this budget refuses such inputs. An honest base +// plans only the work blocks its commitments and h/N name: tens of lists at +// today's populations of a few thousand MNs, and even the worst case of every +// LLMQ_60_75 index failing its DKG in a different cycle (262 lists) stays below +// a million visits at 3,000 MNs. static constexpr size_t EVO_SNAPSHOT_MAX_RECONSTRUCTION_RECORDS{8'000'000}; +// The base coinbase is length-delimited and bounded before allocation; its +// merkle branch proves it against the base header, so it is at most as deep as +// a tree over 2^32 transactions. +static constexpr size_t EVO_SNAPSHOT_MAX_COINBASE_BYTES{1'000'000}; +static constexpr size_t EVO_SNAPSHOT_MAX_COINBASE_BRANCH{32}; +// The credit-pool window is CreditPoolPeriodBlocks() long: 576 on main, test +// and devnet, 100 on regtest. A test pins every network to this bound. +static constexpr size_t EVO_SNAPSHOT_MAX_CREDIT_HISTORY{576}; +// At most two bootstrap work entries per type: the cycle containing the base +// and the next one. +static constexpr size_t EVO_SNAPSHOT_MAX_BOOTSTRAP_WORK{2}; static_assert(std::ranges::all_of(Consensus::available_llmqs, [](const auto& params) { return !params.useRotation || params.keepOldConnections <= 2 * params.signingActiveQuorumCount; }), "rotated LLMQ retention exceeds the two serialized cycles"); +// Bootstrap work entries are ordered by cycle height, and a cycle's work block +// precedes it. Both need every cycle to be longer than the work depth. +static_assert(std::ranges::all_of(Consensus::available_llmqs, + [](const auto& params) { return params.dkgInterval > llmq::WORK_DIFF_DEPTH; }), + "an LLMQ cycle must be longer than the quorum work depth"); + +/** Commitments carried for one type: max(a + 1, keepOld) without rotation, 2a with it. */ +constexpr size_t SnapshotCommitmentCountFor(const Consensus::LLMQParams& params, bool rotation_enabled) +{ + return rotation_enabled + ? 2 * static_cast(params.signingActiveQuorumCount) + : static_cast(std::max(params.signingActiveQuorumCount + 1, params.keepOldConnections)); +} + +/** Rotation quarters a rotating type can need: three per commitment cycle, plus h..h-3C. */ +constexpr size_t EvoSnapshotMaxRotationSnapshots(const Consensus::LLMQParams& params) +{ + return 3 * SnapshotCommitmentCountFor(params, /*rotation_enabled=*/true) + 4; +} + +/** Work blocks one type can need, over every mode the type can run in. */ +constexpr size_t EvoSnapshotMaxWorkBlocks(const Consensus::LLMQParams& params) +{ + const size_t plain{SnapshotCommitmentCountFor(params, /*rotation_enabled=*/false) + 2}; + if (!params.useRotation) return plain; + return std::max(plain, 4 * SnapshotCommitmentCountFor(params, /*rotation_enabled=*/true) + 6); +} + +/** + * Maximum number of distinct historical work-block lists a snapshot can need. + * The serialized set is deduplicated, so summing every type's bound over the + * static table is conservative. + */ +constexpr size_t EvoSnapshotMaxHistoricalMNLists() +{ + size_t count{0}; + for (const auto& params : Consensus::available_llmqs) + count += EvoSnapshotMaxWorkBlocks(params); + return count; +} +static constexpr size_t EVO_SNAPSHOT_MAX_MODIFIERS{4'096}; +// Modifiers are one per (type, work block), so they number at most the sum of +// the per-type work-block bounds. +static_assert(EvoSnapshotMaxHistoricalMNLists() <= EVO_SNAPSHOT_MAX_MODIFIERS, + "one modifier per (type, work block) must fit the modifier bound"); template size_t ReadBoundedCompactSize(Stream& s, size_t limit, const char* field) @@ -111,32 +188,12 @@ inline const Consensus::LLMQParams& SnapshotLLMQParams(Consensus::LLMQType type) inline size_t SnapshotCommitmentCount(const Consensus::LLMQParams& params, bool rotation_enabled) { - if (!rotation_enabled) { - return static_cast(std::max(params.signingActiveQuorumCount + 1, params.keepOldConnections)); - } - const size_t active{static_cast(params.signingActiveQuorumCount)}; - const size_t retained{static_cast(params.keepOldConnections)}; // Rotation seeding promises the active and previous complete cycles. A // future parameter set retaining more must extend the serialized cycles. - if (retained > 2 * active) throw std::ios_base::failure("rotated LLMQ retention exceeds two cycles"); - return 2 * active; -} - -/** - * Maximum number of distinct historical work-block lists a snapshot can need. - * The serialized set is deduplicated, so summing every enabled-type horizon is - * conservative: two retained commitment cycles plus H-C..H-4C for rotated - * types, or the retained commitment horizon for non-rotated types. - */ -inline size_t EvoSnapshotMaxHistoricalMNLists() -{ - size_t count{0}; - for (const auto& params : Consensus::available_llmqs) { - count += params.useRotation - ? SnapshotCommitmentCount(params, /*rotation_enabled=*/true) + EVO_SNAPSHOT_ROTATION_CYCLES - : SnapshotCommitmentCount(params, /*rotation_enabled=*/false); + if (rotation_enabled && params.keepOldConnections > 2 * params.signingActiveQuorumCount) { + throw std::ios_base::failure("rotated LLMQ retention exceeds two cycles"); } - return count; + return SnapshotCommitmentCountFor(params, rotation_enabled); } /** @@ -215,10 +272,12 @@ uint64_t ReadCompactSize(SnapshotBoundedInput& stream) /** * Snapshot-local canonical deterministic-MN encoding. * - * internalId and nTotalRegisteredCount are intentionally retained. They are - * consensus-deterministic for nodes synced from genesis: registrations assign - * internalId in on-chain order and advance the counter identically. Thus a - * from-genesis background validation re-derives the dumper's exact values. + * A node's internalIds and nTotalRegisteredCount depend on its history: no + * diff records a masternode registered and removed in one block, so a list + * rebuilt from a stored list and diffs (after a restart, or once the cache + * dropped it) counts one registration fewer, and later registrations take + * lower ids. A section therefore carries its own numbering, from + * CanonicalMNIds(), and CanonicalMNListHash() covers neither value. * Entries are sorted by the full proTxHash, never by immer iteration order. */ template @@ -284,9 +343,16 @@ CDeterministicMNList UnserializeCanonicalMNList(Stream& s) return list; } -/** Canonical hash shared by snapshot encoding and M3 completion comparison. */ +/** Canonical hash shared by snapshot encoding and M3 completion comparison. + * It leaves out the internal ids and the registration counter, so every node + * derives the same hash for the same list. */ uint256 CanonicalMNListHash(const CDeterministicMNList& list); +/** The internal ids an evo snapshot carries for the masternodes of `lists`: + * each proTxHash's rank among all of them. The registration counter of every + * carried list is their number. */ +std::map CanonicalMNIds(const std::vector& lists); + /** Canonical snapshot-local encoding of a deterministic-MN list diff. */ template void SerializeCanonicalMNListDiff(Stream& s, const CDeterministicMNListDiff& diff) @@ -470,12 +536,27 @@ struct QuorumModifier { SERIALIZE_METHODS(QuorumModifier, obj) { READWRITE(obj.llmq_type, obj.work_block_hash, obj.modifier); } }; +/** + * A work block the snapshot carries for the cycle containing the base (h) or + * the next one (N) that no carried commitment or rotation quarter references. + * The cycle need not be mined: only its height and the work block are named. + */ +struct BootstrapWork { + int32_t cycle_base_height{-1}; + uint256 work_block_hash; + + bool operator==(const BootstrapWork&) const = default; + SERIALIZE_METHODS(BootstrapWork, obj) { READWRITE(obj.cycle_base_height, obj.work_block_hash); } +}; + struct QuorumSnapshotData { Consensus::LLMQType llmq_type{Consensus::LLMQType::LLMQ_NONE}; bool rotation_enabled{false}; std::vector active_commitments; std::vector safety_commitments; std::vector rotation_snapshots; + //! Strictly ascending by cycle height. + std::vector bootstrap_work; template void Serialize(Stream& s) const; template void Unserialize(Stream& s); @@ -488,10 +569,16 @@ class EvoSnapshot uint16_t version{EVO_SNAPSHOT_VERSION}; uint256 base_block_hash; CDeterministicMNList mn_list; + //! The base block's coinbase, null exactly when DIP3 is inactive at the base. + CTransactionRef base_coinbase; + //! Merkle branch of the coinbase (index 0) to the base header, leaf to root. + std::vector base_coinbase_branch; std::vector quorums; std::vector historical_mn_list_diffs; std::vector quorum_modifiers; CCreditPool credit_pool; + //! The window entries of the blocks ending at the base, oldest first. + std::vector credit_history; AbstractEHFManager::Signals mnhf_signals; template void Serialize(Stream& s) const; @@ -528,6 +615,11 @@ inline bool IsCanonicallyBefore(const QuorumModifier& a, const QuorumModifier& b return std::tie(a.llmq_type, a.work_block_hash) < std::tie(b.llmq_type, b.work_block_hash); } +inline bool IsCanonicallyBefore(const BootstrapWork& a, const BootstrapWork& b) +{ + return a.cycle_base_height < b.cycle_base_height; +} + inline bool IsCanonicallyBefore(const QuorumSnapshotData& a, const QuorumSnapshotData& b) { return a.llmq_type < b.llmq_type; @@ -593,6 +685,7 @@ void QuorumSnapshotData::Serialize(Stream& s) const const auto snapshots{CanonicallySortedCopy(rotation_snapshots)}; s << llmq_type << rotation_enabled << active << safety; WriteSnapshotVector(s, snapshots, [&](const auto& entry) { WriteRotationSnapshot(s, entry); }); + s << CanonicallySortedCopy(bootstrap_work); } template @@ -608,6 +701,7 @@ void QuorumSnapshotData::Unserialize(Stream& s) active_commitments.clear(); safety_commitments.clear(); rotation_snapshots.clear(); + bootstrap_work.clear(); const auto& params{SnapshotLLMQParams(llmq_type)}; const size_t total_count{SnapshotCommitmentCount(params, rotation_enabled)}; const size_t expected_active{static_cast(params.signingActiveQuorumCount)}; @@ -621,9 +715,20 @@ void QuorumSnapshotData::Unserialize(Stream& s) for (size_t i{0}; i < safety_count; ++i) { safety_commitments.emplace_back(ReadMinedQuorumCommitment(s)); } - const size_t snapshot_count{ReadBoundedCompactSize(s, EVO_SNAPSHOT_ROTATION_CYCLES, "rotation snapshots")}; + const size_t snapshot_count{ + ReadBoundedCompactSize(s, rotation_enabled ? EvoSnapshotMaxRotationSnapshots(params) : size_t{0}, + "rotation snapshots")}; rotation_snapshots.reserve(snapshot_count); for (size_t i{0}; i < snapshot_count; ++i) rotation_snapshots.emplace_back(ReadRotationSnapshot(s, params)); + const size_t bootstrap_count{ReadBoundedCompactSize(s, EVO_SNAPSHOT_MAX_BOOTSTRAP_WORK, "bootstrap work")}; + for (size_t i{0}; i < bootstrap_count; ++i) { + BootstrapWork entry; + s >> entry; + if (!bootstrap_work.empty() && bootstrap_work.back().cycle_base_height >= entry.cycle_base_height) { + throw std::ios_base::failure("noncanonical evo bootstrap work order"); + } + bootstrap_work.emplace_back(entry); + } } template @@ -634,6 +739,15 @@ void EvoSnapshot::Serialize(Stream& s) const const auto sorted_modifiers{CanonicallySortedCopy(quorum_modifiers)}; s << version << base_block_hash; SerializeCanonicalMNList(s, mn_list); + if (base_coinbase) { + DataStream coinbase{}; + coinbase << *base_coinbase; + WriteCompactSize(s, coinbase.size()); + s.write(MakeByteSpan(coinbase)); + } else { + WriteCompactSize(s, 0); + } + s << base_coinbase_branch; s << sorted_quorums; WriteCompactSize(s, sorted_history.size()); for (const auto& entry : sorted_history) { @@ -642,6 +756,7 @@ void EvoSnapshot::Serialize(Stream& s) const } s << sorted_modifiers; s << credit_pool.locked << credit_pool.currentLimit << credit_pool.latelyUnlocked << credit_pool.indexes; + s << credit_history; WriteCompactSize(s, mnhf_signals.size()); for (const auto& signal : mnhf_signals) s << signal; } @@ -658,8 +773,28 @@ void EvoSnapshot::Unserialize(Stream& s) quorums.clear(); historical_mn_list_diffs.clear(); quorum_modifiers.clear(); + credit_history.clear(); mnhf_signals.clear(); mn_list = UnserializeCanonicalMNList(s); + base_coinbase.reset(); + if (const size_t coinbase_size{ReadBoundedCompactSize(s, EVO_SNAPSHOT_MAX_COINBASE_BYTES, "base coinbase")}) { + std::vector bytes(coinbase_size); + s.read(bytes); + DataStream coinbase{bytes}; + CMutableTransaction tx; + coinbase >> tx; + if (!coinbase.empty()) throw std::ios_base::failure("trailing bytes after the evo snapshot base coinbase"); + base_coinbase = MakeTransactionRef(std::move(tx)); + DataStream reencoded{}; + reencoded << *base_coinbase; + if (reencoded.size() != bytes.size() || !std::equal(bytes.begin(), bytes.end(), reencoded.begin())) { + throw std::ios_base::failure("noncanonical evo snapshot base coinbase"); + } + } + const size_t branch_size{ReadBoundedCompactSize(s, EVO_SNAPSHOT_MAX_COINBASE_BRANCH, "coinbase branch")}; + base_coinbase_branch.resize(branch_size); + for (auto& node : base_coinbase_branch) + s >> node; const size_t quorum_count{ReadBoundedCompactSize(s, Consensus::available_llmqs.size(), "quorum-type count")}; quorums.reserve(quorum_count); for (size_t i{0}; i < quorum_count; ++i) { @@ -686,6 +821,10 @@ void EvoSnapshot::Unserialize(Stream& s) } s >> credit_pool.locked >> credit_pool.currentLimit >> credit_pool.latelyUnlocked; credit_pool.indexes.UnserializeBounded(s, EVO_SNAPSHOT_MAX_RANGES); + const size_t history_entries{ReadBoundedCompactSize(s, EVO_SNAPSHOT_MAX_CREDIT_HISTORY, "credit history")}; + credit_history.resize(history_entries); + for (auto& entry : credit_history) + s >> entry; const size_t signal_count{ReadBoundedCompactSize(s, VERSIONBITS_NUM_BITS, "MNHF signals")}; // The signal map normalizes iteration order, so wire order is observable // only here: require the strictly ascending bit order the serializer @@ -706,24 +845,174 @@ void EvoSnapshot::Unserialize(Stream& s) /** Single SHA256 of the canonical encoding. */ uint256 GetEvoSnapshotHash(const EvoSnapshot& snapshot); -struct QuorumReconstructionHeight { - Consensus::LLMQType llmq_type; - bool rotation; - int quorum_height; - int work_height; +/** A work block the snapshot carries for one type, and the cycle (or, without + * rotation, the quorum) whose score modifier it carries. */ +struct EvoSnapshotWorkBlock { + const CBlockIndex* work_index{nullptr}; + int cycle_height{-1}; +}; + +/** The Evo state one LLMQ type needs at a snapshot base: every quorum member + * computation the snapshot chainstate makes at or below the base reads only + * these, plus the carried commitments. */ +struct EvoSnapshotDependencyPlan { + Consensus::LLMQType llmq_type{Consensus::LLMQType::LLMQ_NONE}; + bool rotation_enabled{false}; + //! S_T: cycles whose rotation quarters are carried, ascending. + std::vector rotation_cycles; + //! W_T: work blocks whose lists and modifiers are carried, ascending. + std::vector work_blocks; + //! The entries of W_T for h and N that nothing else references. + std::vector bootstrap_work; +}; + +/** The work block a quorum's members are computed from: the cycle's work block + * with rotation, otherwise the quorum's own block before v20 and its work + * block after. */ +int EvoSnapshotWorkHeight(const Consensus::Params& consensus, const Consensus::LLMQParams& params, + bool rotation_enabled, int quorum_height); + +/** Derive the exact dependency sets of `llmq_type` at `base_index` from the + * carried commitments' quorum blocks. The builder, the chain validator and + * the completion rebuild all use it. */ +bool PlanEvoSnapshotDependencies(const ChainstateManager& chainman, const CBlockIndex* base_index, + Consensus::LLMQType llmq_type, const std::vector& commitments, + EvoSnapshotDependencyPlan& plan, std::string& error) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** The inputs of a section that only block bodies provide, as the background + * chainstate captured them while connecting those blocks. */ +struct EvoSnapshotCaptures { + std::map, uint256> modifiers; + std::map credit_history; + CTransactionRef base_coinbase; + std::vector base_coinbase_branch; + std::optional base_credit_pool; +}; + +/** The blocks at or below the base whose bodies a section's inputs come from: + * the work blocks of the v20 modifiers, the credit-pool window and the base, + * whose pool folds in every block back to the last pool on disk. */ +struct EvoSnapshotCapturePlan { + uint256 base; + int base_height{-1}; + int window_first{-1}; + std::map> modifier_blocks; + //! Heights of every block whose body is an input. + std::set heights; }; -/** Pure conservative reconstruction horizon for the supplied enabled types. */ -std::vector EvoSnapshotReconstructionHeights( - int base_height, const std::vector& enabled_llmqs); +std::optional PlanEvoSnapshotCaptures(const EvoSnapshot& snapshot, const ChainstateManager& chainman) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** Record, in the calling thread's open transaction, what `block` contributes + * to the planned inputs. At the base that includes its credit pool, read + * through `cpoolman` in the calling thread's Evo view; a LocalStateError + * from that read propagates. */ +bool WriteEvoSnapshotCaptures(CEvoDB& evodb, CCreditPoolManager& cpoolman, const node::BlockManager& blockman, + const EvoSnapshotCapturePlan& plan, const CBlock& block, const CBlockIndex& index, + const Consensus::Params& consensus, std::string& error); + +/** The planned inputs captured so far. */ +EvoSnapshotCaptures ReadEvoSnapshotCaptures(CEvoDB& evodb, const EvoSnapshotCapturePlan& plan, + const ChainstateManager& chainman) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** Remove every capture on disk, whatever snapshot it was for. Only for when + * no snapshot generation is live, e.g. after a crash before publication. */ +bool EraseAllEvoSnapshotCaptures(CEvoDB& evodb); + +/** Remove every capture, in the calling thread's open transaction. */ +void EraseEvoSnapshotCaptures(CEvoDB& evodb, const EvoSnapshotCapturePlan& plan, const ChainstateManager& chainman) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** Why the evo section could not be built or checked. Only a disagreement + * says anything about the section; the others are about this node. */ +enum class EvoSectionFailure : uint8_t { + MISSING_INPUT, //!< data this node lacks, which a later attempt may have + LOCAL_CORRUPTION, //!< data this node has but cannot read, or that is inconsistent + INTERNAL_ERROR, //!< a bug in this node + DISAGREEMENT, //!< the section disagrees with the chain or with validated state +}; + +std::string EvoSectionFailureName(EvoSectionFailure failure); + +/** The failure that an exception raised while building or checking the section + * stands for. */ +EvoSectionFailure ClassifyEvoSectionError(const std::exception& e); +EvoSectionFailure ClassifyEvoSectionError(const LocalStateError& e); + +/** Build the Evo section at `base_index` from the calling thread's Evo view. + * Body-derived inputs come from `captures` where present, otherwise from the + * blocks. On failure `failure`, if given, says why; an exception is + * classified by ClassifyEvoSectionError(). */ +bool BuildEvoSnapshot(const CChainParams& chainparams, const ChainstateManager& chainman, CDeterministicMNManager& dmnman, + const llmq::CQuorumBlockProcessor& qblockman, llmq::CQuorumSnapshotManager& qsnapman, + CCreditPoolManager& cpoolman, CMNHFManager& mnhfman, const CBlockIndex* base_index, + EvoSnapshot& snapshot, std::string& error, const EvoSnapshotCaptures* captures = nullptr, + EvoSectionFailure* failure = nullptr) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** Apply the complete diff chain and return lists keyed by target block hash. */ bool ReconstructHistoricalMNLists(const EvoSnapshot& snapshot, std::map& lists, std::string& error, size_t max_records = EVO_SNAPSHOT_MAX_RECONSTRUCTION_RECORDS); +/** Validate all snapshot invariants requiring the block index or deployments, + * including exact equality with the planned dependency sets. */ +bool ValidateEvoSnapshotAgainstChain(const EvoSnapshot& snapshot, const ChainstateManager& chainman, + const CBlockIndex* base_index, std::string& error) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + /** Pure CbTx checks over already-built snapshot content. */ bool VerifyEvoSnapshotCbTx(const EvoSnapshot& snapshot, const CCbTx& cbtx, std::string& error); +/** The merkle root a leaf at `index` reaches through `branch` (leaf to root). */ +uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector& branch, uint32_t index); +/** The merkle branch of the transaction at `index` in `block`, leaf to root. */ +std::vector BlockMerkleBranch(const CBlock& block, uint32_t index); + +/** Load-time anchor of the section to the base header: the carried coinbase + * must hash through its branch to the header's merkle root, and its CbTx + * must commit to the carried MN list, active quorums and credit pool. */ +bool VerifyEvoSnapshotBaseBlock(const EvoSnapshot& snapshot, const CBlockIndex& base_index, std::string& error); + +/** The chain checks export and load share: ValidateEvoSnapshotAgainstChain() + * and, once DIP3 is active at the base, VerifyEvoSnapshotBaseBlock(). They + * read headers, the section and the calling thread's Evo view: the exporter + * runs them on NORMAL, the loader in the unpublished generation it seeded the + * section into, so deployment state at or below the base comes from the + * carried signal record and never from history the loading node lacks. */ +bool PreflightEvoSnapshot(const EvoSnapshot& snapshot, const ChainstateManager& chainman, const CBlockIndex* base_index, + std::string& error, EvoSectionFailure* failure = nullptr) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** The scan-coverage gate of ValidateEvoSnapshotAgainstChain on its own: + * every ChainLock verification scan B + 1 may make and the asset-unlock scan + * of B + 1 must be proven from the section. */ +bool CheckEvoSnapshotScanCoverage(const EvoSnapshot& snapshot, const ChainstateManager& chainman, + const CBlockIndex* base_index, std::string& error) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** How the scan sequences of `params`' type end in the section: END where the + * canonical commitment selection carries fewer records than it takes, so no + * older one exists; UNKNOWN otherwise. Local-only, recorded at seeding. + * + * END rests on the carried counts alone. The CbTx quorum root binds only the + * active set and headers say nothing about how many older commitments exist, + * so validation bounds the safety commitments from above only: a section + * omitting one would turn UNKNOWN into END and a short scan into a wrong + * answer. Only the mandatory evo-hash pin binds the counts, so no section may + * be seeded without it. */ +llmq::ScanCoverageRecord EvoSnapshotScanCoverage(const EvoSnapshot& snapshot, const Consensus::LLMQParams& params); + +/** Seed the decoded snapshot's state into `view`, inside the caller's open + * EvoDB transaction for that view. */ +bool SeedEvoSnapshotState(const EvoViewToken& view, const EvoSnapshot& snapshot, CSpecialTxProcessor& special_tx, + const node::BlockManager& blockman, const CBlockIndex* base_index, std::string& error) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + +/** Compute, in the calling thread's (seeded) view, the members of every + * carried quorum, of the base's cycle, and of the next cycle when its work + * block is at or below the base. Seeded state that cannot support them is an + * error. */ +bool DryRunEvoSnapshot(const EvoSnapshot& snapshot, const ChainstateManager& chainman, CSpecialTxProcessor& special_tx, + const CBlockIndex* base_index, std::string& error) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + } // namespace evo #endif // BITCOIN_EVO_SNAPSHOT_H diff --git a/src/evo/snapshot_chain.cpp b/src/evo/snapshot_chain.cpp new file mode 100644 index 000000000000..1d25f59d4f3a --- /dev/null +++ b/src/evo/snapshot_chain.cpp @@ -0,0 +1,1205 @@ +// 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. + +// Chain-aware companions to evo/snapshot.cpp, deliberately header-less: these +// implementations are declared in evo/snapshot.h but need validation.h and +// llmq internals, so they live in their own compilation unit to keep the +// snapshot codec free of an evo/snapshot -> validation -> evo/snapshot cycle. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace evo { +namespace { + +//! V20 is buried, so its state after a height is known even for a cycle that +//! is not mined yet. +bool V20ActiveAfterHeight(const Consensus::Params& consensus, int height) +{ + return height + 1 >= consensus.DeploymentHeight(Consensus::DEPLOYMENT_V20); +} + +bool ValidateCommitmentAgainstChain(const MinedQuorumCommitment& entry, const ChainstateManager& chainman, + const CBlockIndex* base_index, const Consensus::LLMQParams& params, + bool rotation_enabled) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + const CBlockIndex* quorum_index{chainman.m_blockman.LookupBlockIndex(entry.quorum_base_block_hash)}; + const CBlockIndex* mined_index{chainman.m_blockman.LookupBlockIndex(entry.mined_block_hash)}; + if (quorum_index == nullptr || mined_index == nullptr || + base_index->GetAncestor(quorum_index->nHeight) != quorum_index || + base_index->GetAncestor(mined_index->nHeight) != mined_index) + return false; + const int cycle_height{quorum_index->nHeight - quorum_index->nHeight % params.dkgInterval}; + if (rotation_enabled) { + if (entry.commitment.quorumIndex != quorum_index->nHeight % params.dkgInterval || + entry.commitment.quorumIndex < 0 || entry.commitment.quorumIndex >= params.signingActiveQuorumCount) + return false; + } else if (quorum_index->nHeight != cycle_height || entry.commitment.quorumIndex != 0) { + return false; + } + const int mined_cycle{mined_index->nHeight - mined_index->nHeight % params.dkgInterval}; + if (mined_cycle != cycle_height || mined_index->nHeight % params.dkgInterval < params.dkgMiningWindowStart || + mined_index->nHeight % params.dkgInterval > params.dkgMiningWindowEnd) + return false; + const uint16_t expected_version{ + llmq::CFinalCommitment::GetVersion(rotation_enabled, DeploymentActiveAfter(quorum_index, chainman.GetConsensus(), + Consensus::DEPLOYMENT_V19))}; + return entry.commitment.nVersion == expected_version && entry.commitment.VerifySizes(params); +} + +//! Applicable(Y): a rotation cycle at or below the base whose quarter the +//! ordinary computation builds and later reads. +bool IsApplicableRotationCycle(const ChainstateManager& chainman, const Consensus::LLMQParams& params, + const CBlockIndex* base_index, int cycle_height) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + if (cycle_height < 0 || cycle_height > base_index->nHeight || cycle_height % params.dkgInterval != 0) return false; + const CBlockIndex* cycle{base_index->GetAncestor(cycle_height)}; + return cycle != nullptr && llmq::IsQuorumRotationEnabled(params, cycle) && + chainman.IsQuorumTypeEnabled(params.type, cycle->pprev); +} + +//! The modifier of the cycle at `work.cycle_height`, from the work block's +//! data or, when this node lacks the block, from `seeded`; a block it has but +//! cannot read raises BlockDataReadError. Mirrors the ordinary calculation +//! (llmq/utils.cpp), but reports a v20 work block it can neither read nor +//! take from `seeded` through `error`, and needs no unmined cycle's block. +std::optional ExactWorkModifier(const Consensus::LLMQParams& params, const Consensus::Params& consensus, + const node::BlockManager& blockman, const CBlockIndex* base_index, + const EvoSnapshotWorkBlock& work, const std::optional& seeded, + std::string& error, EvoSectionFailure& failure) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + const CBlockIndex* modifier_work{base_index->GetAncestor(work.cycle_height - llmq::WORK_DIFF_DEPTH)}; + if (modifier_work == nullptr) { + error = "evo quorum modifier work block is not an ancestor of the base"; + failure = EvoSectionFailure::INTERNAL_ERROR; + return std::nullopt; + } + if (DeploymentActiveAfter(modifier_work, consensus, Consensus::DEPLOYMENT_V20)) { + if ((modifier_work->nStatus & BLOCK_HAVE_DATA) == 0) { + if (!seeded) { + error = "quorum work block data unavailable for its exact score modifier"; + failure = EvoSectionFailure::MISSING_INPUT; + } + return seeded; + } + CBlock block; + if (blockman.ReadBlockFromDisk(block, modifier_work->GetBlockPos()) != modifier_work->GetBlockHash()) { + throw BlockDataReadError( + strprintf("quorum work block %s cannot be read", modifier_work->GetBlockHash().ToString())); + } + return llmq::utils::GetWorkBlockModifier(params, block, *modifier_work); + } + if (params.useRotation) return ::SerializeHash(std::make_pair(params.type, modifier_work->GetBlockHash())); + if (work.cycle_height > base_index->nHeight) { + error = "pre-v20 modifier of a cycle above the base is undecidable"; + failure = EvoSectionFailure::INTERNAL_ERROR; + return std::nullopt; + } + return ::SerializeHash(std::make_pair(params.type, base_index->GetAncestor(work.cycle_height)->GetBlockHash())); +} + +//! A carried list for the snapshot: an unbound pre-DIP3 list is the empty list +//! bound to its block, which is what the snapshot view reads there. +CDeterministicMNList BoundList(const CDeterministicMNList& list, const CBlockIndex* index) +{ + if (list.GetBlockHash().IsNull()) return CDeterministicMNList{index->GetBlockHash(), index->nHeight, 0}; + return list; +} + +//! Whether every activation input of a quorum type is the same for the block +//! after `target_height` as for the block after the base: no buried deployment +//! or DIP0024 quorum height switches in between, and no versionbits deployment +//! that is not yet active crosses a period boundary. +bool ContextUnchangedUntil(const ChainstateManager& chainman, const CBlockIndex* base_index, int64_t target_height) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + const auto& consensus{chainman.GetConsensus()}; + const int64_t base_height{base_index->nHeight}; + for (int16_t dep{Consensus::DEPLOYMENT_HEIGHTINCB}; + Consensus::ValidDeployment(static_cast(dep)); ++dep) { + const int64_t height{consensus.DeploymentHeight(static_cast(dep))}; + if ((base_height + 1 >= height) != (target_height + 1 >= height)) return false; + } + if ((base_height >= consensus.DIP0024QuorumsHeight) != (target_height >= consensus.DIP0024QuorumsHeight)) { + return false; + } + for (int pos{0}; pos < Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++pos) { + const auto dep{static_cast(pos)}; + if (DeploymentActiveAfter(base_index, chainman, dep)) continue; + const auto& deployment{consensus.vDeployments[dep]}; + const int64_t period{deployment.nWindowSize ? deployment.nWindowSize : int64_t{consensus.nMinerConfirmationWindow}}; + // A state is constant within a period: blocks base+1 .. target+1 share + // one unless one of them starts a new period. + if (period > 0 && (target_height + 1) / period != (base_height + 1) / period) return false; + } + return true; +} + +//! I6 for the next cycle N: its members read work data at or below the base +//! once N - D <= B, and the planner derives h and N from the context at B. +//! A type enabled, or switching rotation, between B and N would need inputs +//! nothing carries, so such a base is refused at export and load alike. +bool CheckNextCycleContext(const ChainstateManager& chainman, const CBlockIndex* base_index, std::string& error) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + for (const auto& params : chainman.GetConsensus().llmqs) { + const int64_t base_height{base_index->nHeight}; + const int64_t next{base_height - base_height % params.dkgInterval + params.dkgInterval}; + // N - 1 == B makes N's context the base's own. + if (next - llmq::WORK_DIFF_DEPTH > base_height || next - 1 == base_height) continue; + if (!ContextUnchangedUntil(chainman, base_index, next - 1)) { + error = strprintf("evo snapshot base precedes an undecidable activation context at the next %s cycle %d", + params.name, next); + return false; + } + } + return true; +} + +//! The carried records of `params`' type in the family its scans read, newest +//! mined first: per quorum index with rotation, one sequence otherwise. +std::vector>> CarriedScanRecords(const EvoSnapshot& snapshot, + const ChainstateManager& chainman, + const Consensus::LLMQParams& params) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + std::vector>> records( + params.useRotation ? static_cast(params.signingActiveQuorumCount) : 1); + const auto data{std::ranges::find_if(snapshot.quorums, [&](const auto& q) { return q.llmq_type == params.type; })}; + // Scans of a rotating type read the indexed family only. Without rotation + // at the base there is no indexed record at or below it. + if (data == snapshot.quorums.end() || data->rotation_enabled != params.useRotation) return records; + for (const auto* commitments : {&data->active_commitments, &data->safety_commitments}) { + for (const auto& entry : *commitments) { + const size_t sequence{params.useRotation ? static_cast(entry.commitment.quorumIndex) : 0}; + const CBlockIndex* mined{chainman.m_blockman.LookupBlockIndex(entry.mined_block_hash)}; + const CBlockIndex* quorum{chainman.m_blockman.LookupBlockIndex(entry.quorum_base_block_hash)}; + if (sequence < records.size() && mined != nullptr && quorum != nullptr) { + records[sequence].emplace_back(mined->nHeight, quorum); + } + } + } + for (auto& sequence : records) { + std::sort(sequence.begin(), sequence.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + } + return records; +} + +//! Prove the scans the snapshot chainstate must answer from carried history +//! alone: ChainLock verification for every height B + 1 may certify, and the +//! asset-unlock quorum check of B + 1. With `full_index`, the exporter's +//! complete commitment index, the proven vectors must also equal it, and +//! `failure`, if given, says whether that index was unreadable. +bool CheckScanCoverage(const EvoSnapshot& snapshot, const ChainstateManager& chainman, const CBlockIndex* base_index, + const llmq::CQuorumBlockProcessor* full_index, std::string& error, + EvoSectionFailure* failure = nullptr) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) +{ + const auto& consensus{chainman.GetConsensus()}; + struct Request { + Consensus::LLMQType type{Consensus::LLMQType::LLMQ_NONE}; + const CBlockIndex* start{nullptr}; + size_t count{0}; + }; + std::vector requests; + // Without v20 at B + 1 its CbTx carries no ChainLock to verify. + const auto chainlocks{chainman.GetParams().GetLLMQ(consensus.llmqTypeChainLocks)}; + if (chainlocks && DeploymentActiveAfter(base_index, consensus, Consensus::DEPLOYMENT_V20)) { + // B + 1 may certify any height from the base's certified one on; with + // no certificate at the base, any height at all. + int first_height{0}; + if (const auto cbtx{snapshot.base_coinbase ? DecodeCbTxPayload(*snapshot.base_coinbase) : std::nullopt}; + cbtx && cbtx->nVersion >= CCbTx::Version::CLSIG_AND_BALANCE && cbtx->bestCLSignature.Get().IsValid() && + cbtx->bestCLHeightDiff < static_cast(base_index->nHeight)) { + first_height = base_index->nHeight - static_cast(cbtx->bestCLHeightDiff) - 1; + } + // With a fixed type and count, coverage only grows with the cutoff, + // and the cutoff with the start. So only the first start of each + // context (enablement and whether the scan is empty by genesis) needs + // proving. + std::optional> context; + for (int height{std::max(first_height, llmq::SIGN_HEIGHT_OFFSET)}; height <= base_index->nHeight; ++height) { + const CBlockIndex* start{base_index->GetAncestor(height - llmq::SIGN_HEIGHT_OFFSET)}; + const bool enabled{chainman.IsQuorumTypeEnabled(chainlocks->type, start)}; + const std::pair current{enabled, enabled && llmq::NormalizeScanStart(*chainlocks, start)}; + if (context == current) continue; + context = current; + if (current.second) { + requests.push_back({chainlocks->type, start, static_cast(chainlocks->signingActiveQuorumCount)}); + } + } + } + if (const auto platform{chainman.GetParams().GetLLMQ(consensus.llmqTypePlatform)}) { + requests.push_back({platform->type, base_index, static_cast(platform->signingActiveQuorumCount) + 1}); + } + + std::map>>> carried; + std::set> checked; + for (const auto& request : requests) { + const auto params{*Assert(chainman.GetParams().GetLLMQ(request.type))}; + if (!chainman.IsQuorumTypeEnabled(request.type, request.start)) continue; + const auto cutoff{llmq::NormalizeScanStart(params, request.start)}; + if (!cutoff || !checked.emplace(request.type, (*cutoff)->nHeight, request.count).second) continue; + auto [it, inserted]{carried.try_emplace(request.type)}; + if (inserted) it->second = CarriedScanRecords(snapshot, chainman, params); + const auto coverage{EvoSnapshotScanCoverage(snapshot, params)}; + std::vector sequences; + for (size_t i{0}; i < it->second.size(); ++i) { + llmq::ScanSequence sequence{{}, coverage.End(i)}; + for (const auto& [mined_height, quorum] : it->second[i]) { + if (mined_height <= (*cutoff)->nHeight) sequence.records.push_back(quorum); + } + sequences.push_back(std::move(sequence)); + } + const auto proven{llmq::TraverseScanSequences(params.useRotation, sequences, request.count)}; + if (!proven) { + error = strprintf("evo snapshot cannot prove the llmqType=%d scan of %d from height %d", + static_cast(request.type), request.count, (*cutoff)->nHeight); + return false; + } + if (full_index == nullptr) continue; + std::vector complete; + bool unreadable{false}; + if (params.useRotation) { + for (int index{0}; index < params.signingActiveQuorumCount; ++index) { + complete.push_back({full_index->GetMinedCommitmentsByQuorumIndexUntilBlock(request.type, *cutoff, index, + request.count, &unreadable), + llmq::ScanSequenceEnd::END}); + } + } else { + complete.push_back({full_index->GetMinedCommitmentsUntilBlock(request.type, *cutoff, request.count, &unreadable), + llmq::ScanSequenceEnd::END}); + } + if (unreadable) { + error = strprintf("the llmqType=%d mined commitment index is unreadable", static_cast(request.type)); + if (failure) *failure = EvoSectionFailure::LOCAL_CORRUPTION; + return false; + } + if (llmq::TraverseScanSequences(params.useRotation, complete, request.count) != proven) { + error = strprintf("evo snapshot llmqType=%d scan from height %d differs from the full index", + static_cast(request.type), (*cutoff)->nHeight); + return false; + } + } + return true; +} + +} // namespace + +bool CheckEvoSnapshotScanCoverage(const EvoSnapshot& snapshot, const ChainstateManager& chainman, + const CBlockIndex* base_index, std::string& error) +{ + AssertLockHeld(::cs_main); + return CheckScanCoverage(snapshot, chainman, base_index, /*full_index=*/nullptr, error); +} + +llmq::ScanCoverageRecord EvoSnapshotScanCoverage(const EvoSnapshot& snapshot, const Consensus::LLMQParams& params) +{ + llmq::ScanCoverageRecord coverage; + const auto data{std::ranges::find_if(snapshot.quorums, [&](const auto& q) { return q.llmq_type == params.type; })}; + const auto end_of = [](size_t carried, size_t selected) { + return static_cast(carried < selected ? llmq::ScanSequenceEnd::END : llmq::ScanSequenceEnd::UNKNOWN); + }; + if (params.useRotation) { + // The canonical selection carries the last two of every quorum index; + // fewer means none older exists. Without rotation at the base the + // indexed family is empty there. + std::vector counts(static_cast(params.signingActiveQuorumCount)); + if (data != snapshot.quorums.end() && data->rotation_enabled) { + for (const auto* commitments : {&data->active_commitments, &data->safety_commitments}) { + for (const auto& entry : *commitments) { + if (entry.commitment.quorumIndex >= 0 && + static_cast(entry.commitment.quorumIndex) < counts.size()) { + ++counts[entry.commitment.quorumIndex]; + } + } + } + } + for (const size_t count : counts) + coverage.ends.push_back(end_of(count, 2)); + } else { + const size_t carried{data == snapshot.quorums.end() + ? size_t{0} + : data->active_commitments.size() + data->safety_commitments.size()}; + coverage.ends.push_back(end_of(carried, SnapshotCommitmentCount(params, /*rotation_enabled=*/false))); + } + return coverage; +} + +int EvoSnapshotWorkHeight(const Consensus::Params& consensus, const Consensus::LLMQParams& params, + bool rotation_enabled, int quorum_height) +{ + if (rotation_enabled) return quorum_height - quorum_height % params.dkgInterval - llmq::WORK_DIFF_DEPTH; + return V20ActiveAfterHeight(consensus, quorum_height) ? quorum_height - llmq::WORK_DIFF_DEPTH : quorum_height; +} + +bool PlanEvoSnapshotDependencies(const ChainstateManager& chainman, const CBlockIndex* base_index, + Consensus::LLMQType llmq_type, const std::vector& commitments, + EvoSnapshotDependencyPlan& plan, std::string& error) +{ + AssertLockHeld(::cs_main); + plan = EvoSnapshotDependencyPlan{}; + plan.llmq_type = llmq_type; + const auto params_opt{chainman.GetParams().GetLLMQ(llmq_type)}; + if (base_index == nullptr || !params_opt) { + error = "evo snapshot dependency plan without a base or LLMQ parameters"; + return false; + } + const auto& params{*params_opt}; + const auto& consensus{chainman.GetConsensus()}; + const int base_height{base_index->nHeight}; + const int interval{params.dkgInterval}; + const int h{base_height - base_height % interval}; + const int next{h + interval}; + plan.rotation_enabled = llmq::IsQuorumRotationEnabled(params, base_index); + + // A_T for a rotating type (cycle heights), or the quorum heights K_T ∪ {h, N}. + std::set cycles; + for (const CBlockIndex* quorum : commitments) { + if (quorum == nullptr || base_index->GetAncestor(quorum->nHeight) != quorum) { + error = "evo snapshot commitment is not an ancestor of the base"; + return false; + } + cycles.insert(plan.rotation_enabled ? quorum->nHeight - quorum->nHeight % interval : quorum->nHeight); + } + // A type that forms no quorum at the base is carried only for its retained + // commitments, so it needs no members for h or N. + const bool enabled{chainman.IsQuorumTypeEnabled(llmq_type, base_index)}; + if (enabled) { + cycles.insert(h); + cycles.insert(next); + } + + std::map work_cycles; // work height -> the cycle whose modifier it carries + const auto add_work = [&](int work_height, int cycle_height) { + if (work_height < 0 || work_height > base_height) return; + work_cycles.emplace(work_height, cycle_height); + }; + std::set referenced_work; + for (const CBlockIndex* quorum : commitments) { + referenced_work.insert(EvoSnapshotWorkHeight(consensus, params, plan.rotation_enabled, quorum->nHeight)); + } + + if (plan.rotation_enabled) { + std::set quarters; + for (const int cycle : cycles) { + for (int k{1}; k <= 3; ++k) { + if (IsApplicableRotationCycle(chainman, params, base_index, cycle - k * interval)) { + quarters.insert(cycle - k * interval); + } + } + } + for (const int quarter : quarters) { + plan.rotation_cycles.push_back(base_index->GetAncestor(quarter)); + add_work(quarter - llmq::WORK_DIFF_DEPTH, quarter); + referenced_work.insert(quarter - llmq::WORK_DIFF_DEPTH); + } + for (const int cycle : cycles) + add_work(cycle - llmq::WORK_DIFF_DEPTH, cycle); + } else { + for (const int quorum : cycles) { + add_work(EvoSnapshotWorkHeight(consensus, params, /*rotation_enabled=*/false, quorum), quorum); + } + } + + for (const auto& [work_height, cycle_height] : work_cycles) { + plan.work_blocks.push_back({base_index->GetAncestor(work_height), cycle_height}); + } + if (enabled) { + for (const int cycle : {h, next}) { + const int work_height{EvoSnapshotWorkHeight(consensus, params, plan.rotation_enabled, cycle)}; + if (!work_cycles.contains(work_height) || referenced_work.contains(work_height)) continue; + plan.bootstrap_work.push_back({cycle, base_index->GetAncestor(work_height)->GetBlockHash()}); + } + } + return true; +} + +std::string EvoSectionFailureName(EvoSectionFailure failure) +{ + switch (failure) { + case EvoSectionFailure::MISSING_INPUT: + return "missing input"; + case EvoSectionFailure::LOCAL_CORRUPTION: + return "local data unreadable or inconsistent"; + case EvoSectionFailure::INTERNAL_ERROR: + return "internal error"; + case EvoSectionFailure::DISAGREEMENT: + return "disagreement"; + } // no default case, so the compiler can warn about missing cases + assert(false); +} + +EvoSectionFailure ClassifyEvoSectionError(const std::exception& e) +{ + if (dynamic_cast(&e) || dynamic_cast(&e) || + dynamic_cast(&e)) { + return EvoSectionFailure::LOCAL_CORRUPTION; + } + return EvoSectionFailure::INTERNAL_ERROR; +} + +EvoSectionFailure ClassifyEvoSectionError(const LocalStateError& e) +{ + if (dynamic_cast(&e)) return EvoSectionFailure::DISAGREEMENT; + if (dynamic_cast(&e)) return EvoSectionFailure::MISSING_INPUT; + if (dynamic_cast(&e)) return EvoSectionFailure::LOCAL_CORRUPTION; + return EvoSectionFailure::INTERNAL_ERROR; +} + +bool BuildEvoSnapshot(const CChainParams& chainparams, const ChainstateManager& chainman, + CDeterministicMNManager& dmnman, const llmq::CQuorumBlockProcessor& qblockman, + llmq::CQuorumSnapshotManager& qsnapman, CCreditPoolManager& cpoolman, CMNHFManager& mnhfman, + const CBlockIndex* base_index, EvoSnapshot& snapshot, std::string& error, + const EvoSnapshotCaptures* captures, EvoSectionFailure* failure_out) +{ + AssertLockHeld(::cs_main); + error.clear(); + EvoSectionFailure unused; + EvoSectionFailure& failure{failure_out ? *failure_out : unused}; + failure = EvoSectionFailure::INTERNAL_ERROR; + const auto fail = [&](EvoSectionFailure why) { + failure = why; + return false; + }; + // A block body this node lacks may come back; one it has is unreadable. + const auto body_failure = [](const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + return (index.nStatus & BLOCK_HAVE_DATA) ? EvoSectionFailure::LOCAL_CORRUPTION : EvoSectionFailure::MISSING_INPUT; + }; + if (base_index == nullptr) { + error = "evo snapshot base block is null"; + return fail(EvoSectionFailure::INTERNAL_ERROR); + } + const auto& consensus{chainparams.GetConsensus()}; + + EvoSnapshot result; + result.base_block_hash = base_index->GetBlockHash(); + if (!DeploymentActiveAt(*base_index, consensus, Consensus::DEPLOYMENT_DIP0003)) { + result.mn_list = CDeterministicMNList{base_index->GetBlockHash(), base_index->nHeight, 0}; + try { + result.Validate(); + } catch (const std::exception& e) { + error = e.what(); + return fail(EvoSectionFailure::INTERNAL_ERROR); + } + snapshot = std::move(result); + return true; + } + // The context at the base derives from the signal record the section + // carries; validated state deciding otherwise disagrees with it. + if (!CheckNextCycleContext(chainman, base_index, error)) return fail(EvoSectionFailure::DISAGREEMENT); + result.mn_list = dmnman.GetListForBlock(base_index); + if (captures && captures->base_coinbase) { + result.base_coinbase = captures->base_coinbase; + result.base_coinbase_branch = captures->base_coinbase_branch; + } else { + CBlock base_block; + if (!chainman.m_blockman.ReadBlockFromDisk(base_block, *base_index) || base_block.vtx.empty()) { + error = "evo snapshot base block is unreadable"; + return fail(body_failure(*base_index)); + } + result.base_coinbase = base_block.vtx[0]; + result.base_coinbase_branch = BlockMerkleBranch(base_block, 0); + } + std::map historical; + + for (const auto& params : consensus.llmqs) { + QuorumSnapshotData data; + data.llmq_type = params.type; + data.rotation_enabled = llmq::IsQuorumRotationEnabled(params, base_index); + + const size_t active_count{static_cast(params.signingActiveQuorumCount)}; + const size_t total_count{SnapshotCommitmentCount(params, data.rotation_enabled)}; + std::vector active; + std::vector safety; + bool unreadable{false}; + if (data.rotation_enabled) { + active = qblockman.GetLastMinedCommitmentsPerQuorumIndexUntilBlock(params.type, base_index, 0, &unreadable); + safety = qblockman.GetLastMinedCommitmentsPerQuorumIndexUntilBlock(params.type, base_index, 1, &unreadable); + } else { + active = qblockman.GetMinedCommitmentsUntilBlock(params.type, base_index, total_count, &unreadable); + const size_t emit_active{std::min(active.size(), active_count)}; + safety.assign(active.begin() + emit_active, active.end()); + active.resize(emit_active); + } + if (unreadable) { + error = strprintf("the llmqType=%d mined commitment index is unreadable", static_cast(params.type)); + return fail(EvoSectionFailure::LOCAL_CORRUPTION); + } + if (active.size() > active_count) active.resize(active_count); + if (safety.size() > total_count - active_count) safety.resize(total_count - active_count); + // A type that can no longer form quorums (e.g. LLMQ_50_60 after DIP24 + // on mainnet) still contributes its retained commitments to the CbTx + // quorum merkle root, so it is carried whenever it has any. + if (active.empty() && safety.empty() && !chainman.IsQuorumTypeEnabled(params.type, base_index)) continue; + + std::vector carried{active}; + carried.insert(carried.end(), safety.begin(), safety.end()); + EvoSnapshotDependencyPlan plan; + if (!PlanEvoSnapshotDependencies(chainman, base_index, params.type, carried, plan, error)) { + return fail(EvoSectionFailure::INTERNAL_ERROR); + } + + // The commitment index lists the quorum, so its record must be there. + const auto read_commitment = [&](const CBlockIndex* quorum) -> std::optional { + auto [commitment, mined_hash] = qblockman.GetMinedCommitment(params.type, quorum->GetBlockHash()); + if (mined_hash.IsNull()) { + error = "mined quorum commitment not found for " + quorum->GetBlockHash().ToString(); + failure = EvoSectionFailure::LOCAL_CORRUPTION; + return std::nullopt; + } + const int work_height{EvoSnapshotWorkHeight(consensus, params, data.rotation_enabled, quorum->nHeight)}; + if (work_height < 0) { + error = "mined quorum commitment below its work depth"; + failure = EvoSectionFailure::INTERNAL_ERROR; + return std::nullopt; + } + return MinedQuorumCommitment{quorum->GetBlockHash(), base_index->GetAncestor(work_height)->GetBlockHash(), + std::move(commitment), mined_hash}; + }; + for (const CBlockIndex* quorum : active) { + auto entry{read_commitment(quorum)}; + if (!entry) return false; + data.active_commitments.emplace_back(std::move(*entry)); + } + for (const CBlockIndex* quorum : safety) { + auto entry{read_commitment(quorum)}; + if (!entry) return false; + data.safety_commitments.emplace_back(std::move(*entry)); + } + + for (const CBlockIndex* cycle : plan.rotation_cycles) { + auto stored{qsnapman.GetSnapshotForBlock(params.type, cycle)}; + const auto inputs_complete = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + for (int k{1}; k <= 3; ++k) { + const int previous{cycle->nHeight - k * params.dkgInterval}; + if (IsApplicableRotationCycle(chainman, params, base_index, previous) && + !qsnapman.GetSnapshotForBlock(params.type, base_index->GetAncestor(previous))) { + return false; + } + } + return true; + }; + if (!stored && inputs_complete()) { + // Block connection stores every applicable quarter when its + // cycle connects (PreComputeQuorumMembers), so this only + // restores a lost one, from complete inputs, the same way. + (void)llmq::utils::GetAllQuorumMembers(params.type, {dmnman, qsnapman, chainman, cycle}); + stored = qsnapman.GetSnapshotForBlock(params.type, cycle); + } + // Block connection stored it, and its inputs too unless they are lost. + if (!stored) { + error = strprintf("rotation quarter for applicable cycle %d is unavailable", cycle->nHeight); + return fail(EvoSectionFailure::LOCAL_CORRUPTION); + } + const CBlockIndex* work{cycle->GetAncestor(cycle->nHeight - llmq::WORK_DIFF_DEPTH)}; + data.rotation_snapshots.push_back({cycle->GetBlockHash(), work->GetBlockHash(), *stored}); + } + for (const auto& work : plan.work_blocks) { + std::optional modifier; + if (captures) { + const auto captured{captures->modifiers.find({params.type, work.work_index->GetBlockHash()})}; + if (captured != captures->modifiers.end()) modifier = captured->second; + } + if (!modifier) { + modifier = ExactWorkModifier(params, consensus, chainman.m_blockman, base_index, work, + qsnapman.GetSeededQuorumModifier(params.type, work.work_index->GetBlockHash()), + error, failure); + } + if (!modifier) return false; + result.quorum_modifiers.push_back({params.type, work.work_index->GetBlockHash(), *modifier}); + if (work.work_index != base_index) historical.emplace(work.work_index->GetBlockHash(), work.work_index); + } + data.bootstrap_work = plan.bootstrap_work; + data.active_commitments = CanonicallySortedCopy(std::move(data.active_commitments)); + data.safety_commitments = CanonicallySortedCopy(std::move(data.safety_commitments)); + data.rotation_snapshots = CanonicallySortedCopy(std::move(data.rotation_snapshots)); + result.quorums.emplace_back(std::move(data)); + } + + std::vector ordered_history; + ordered_history.reserve(historical.size()); + for (const auto& [_, index] : historical) + ordered_history.push_back(index); + std::sort(ordered_history.begin(), ordered_history.end(), [](const auto* a, const auto* b) { + return std::make_tuple(a->nHeight, a->GetBlockHash()) > std::make_tuple(b->nHeight, b->GetBlockHash()); + }); + std::vector> history; + history.reserve(ordered_history.size()); + for (const CBlockIndex* index : ordered_history) { + history.emplace_back(index, BoundList(dmnman.GetListForBlock(index), index)); + } + std::vector carried{&result.mn_list}; + for (const auto& [_, list] : history) carried.push_back(&list); + const auto canonical_ids{CanonicalMNIds(carried)}; + const auto renumber = [&](const CDeterministicMNList& list) { + return list.Renumbered([&](const CDeterministicMN& dmn) { return canonical_ids.at(dmn.proTxHash); }, + static_cast(canonical_ids.size())); + }; + result.mn_list = renumber(result.mn_list); + CDeterministicMNList previous_list{result.mn_list}; + uint256 previous_hash{result.base_block_hash}; + for (const auto& [index, local_list] : history) { + const CDeterministicMNList list{renumber(local_list)}; + result.historical_mn_list_diffs.push_back({previous_hash, index->GetBlockHash(), index->nHeight, + list.GetTotalRegisteredCount(), CanonicalMNListHash(list), + previous_list.BuildDiff(list)}); + previous_hash = index->GetBlockHash(); + previous_list = list; + } + result.credit_pool = captures && captures->base_credit_pool ? *captures->base_credit_pool + : cpoolman.GetCreditPool(base_index); + const int window{chainparams.CreditPoolPeriodBlocks()}; + for (int height{std::max(0, base_index->nHeight - window + 1)}; height <= base_index->nHeight; ++height) { + const CBlockIndex* index{base_index->GetAncestor(height)}; + if (captures) { + if (const auto captured{captures->credit_history.find(index->GetBlockHash())}; + captured != captures->credit_history.end()) { + result.credit_history.push_back(captured->second); + continue; + } + } + const auto entry{CCreditPoolManager::ReadHistoryEntry(index, chainman.m_blockman, consensus, error)}; + if (!entry) return fail(body_failure(*index)); + result.credit_history.push_back(*entry); + } + // The raw record: GetSignalsStage() would filter it for the next block, + // which the snapshot chainstate does itself. + result.mnhf_signals = mnhfman.GetForBlock(base_index); + result.quorums = CanonicallySortedCopy(std::move(result.quorums)); + result.historical_mn_list_diffs = CanonicallySortedCopy(std::move(result.historical_mn_list_diffs)); + result.quorum_modifiers = CanonicallySortedCopy(std::move(result.quorum_modifiers)); + try { + result.Validate(); + } catch (const std::exception& e) { + error = e.what(); + return fail(EvoSectionFailure::INTERNAL_ERROR); + } + // Export and load apply the same coverage gate; the exporter also checks + // the proven scans against its complete index. + EvoSectionFailure coverage_failure{EvoSectionFailure::INTERNAL_ERROR}; + if (!CheckScanCoverage(result, chainman, base_index, &qblockman, error, &coverage_failure)) + return fail(coverage_failure); + snapshot = std::move(result); + return true; +} + +bool ValidateEvoSnapshotAgainstChain(const EvoSnapshot& snapshot, const ChainstateManager& chainman, + const CBlockIndex* base_index, std::string& error) +{ + AssertLockHeld(::cs_main); + error.clear(); + const auto fail = [&](const std::string& message) { + error = message; + return false; + }; + if (base_index == nullptr || snapshot.base_block_hash != base_index->GetBlockHash() || + snapshot.mn_list.GetBlockHash() != base_index->GetBlockHash() || + snapshot.mn_list.GetHeightForSnapshotCodec() != base_index->nHeight) { + return fail("evo snapshot base block/height mismatch"); + } + try { + snapshot.Validate(/*require_canonical_order=*/true); + } catch (const std::exception& e) { + return fail(e.what()); + } + + const auto& consensus{chainman.GetConsensus()}; + if (!DeploymentActiveAt(*base_index, consensus, Consensus::DEPLOYMENT_DIP0003)) { + if (!snapshot.quorums.empty() || !snapshot.historical_mn_list_diffs.empty() || + !snapshot.quorum_modifiers.empty() || snapshot.mn_list.GetCounts().total() != 0 || + snapshot.mn_list.GetTotalRegisteredCount() != 0 || snapshot.credit_pool.locked != 0 || + snapshot.credit_pool.currentLimit != 0 || snapshot.credit_pool.latelyUnlocked != 0 || + !snapshot.credit_pool.indexes.IsEmpty() || !snapshot.credit_history.empty() || + !snapshot.mnhf_signals.empty() || snapshot.base_coinbase || !snapshot.base_coinbase_branch.empty()) { + return fail("nonempty pre-DIP3 evo snapshot"); + } + return true; + } + if (!CheckNextCycleContext(chainman, base_index, error)) return false; + // Anchor the section to the base header. + if (!snapshot.base_coinbase || + ComputeMerkleRootFromBranch(snapshot.base_coinbase->GetHash(), snapshot.base_coinbase_branch, 0) != + base_index->hashMerkleRoot) { + return fail("evo snapshot base coinbase is not proven by the base header"); + } + + // The credit-pool window: one entry per block of the window ending at the + // base, zero wherever the pool did not exist yet. + const int window{chainman.GetParams().CreditPoolPeriodBlocks()}; + if (window <= 0 || static_cast(window) > EVO_SNAPSHOT_MAX_CREDIT_HISTORY || + snapshot.credit_history.size() != static_cast(std::min(window, base_index->nHeight + 1))) { + return fail("evo credit history does not cover the credit-pool window"); + } + const int first_height{base_index->nHeight - static_cast(snapshot.credit_history.size()) + 1}; + for (size_t i{0}; i < snapshot.credit_history.size(); ++i) { + if (first_height + static_cast(i) < consensus.DeploymentHeight(Consensus::DEPLOYMENT_V20) && + snapshot.credit_history[i] != CreditHistoryEntry{}) { + return fail("evo credit history before v20 is not empty"); + } + } + if (!DeploymentActiveAt(*base_index, consensus, Consensus::DEPLOYMENT_V20) && + (snapshot.credit_pool.locked != 0 || snapshot.credit_pool.currentLimit != 0 || + snapshot.credit_pool.latelyUnlocked != 0 || !snapshot.credit_pool.indexes.IsEmpty())) { + return fail("evo credit pool before v20 is not empty"); + } + + std::map historical_lists; + if (!ReconstructHistoricalMNLists(snapshot, historical_lists, error)) return false; + historical_lists.emplace(snapshot.base_block_hash, snapshot.mn_list); + for (const auto& entry : snapshot.historical_mn_list_diffs) { + const CBlockIndex* index{chainman.m_blockman.LookupBlockIndex(entry.block_hash)}; + if (index == nullptr || base_index->GetAncestor(index->nHeight) != index || entry.height != index->nHeight) { + return fail("invalid historical evo MN list chain data"); + } + } + + std::map, uint256> carried_modifiers; + for (const auto& entry : snapshot.quorum_modifiers) { + carried_modifiers.emplace(std::make_pair(entry.llmq_type, entry.work_block_hash), entry.modifier); + } + std::map actual; + for (const auto& data : snapshot.quorums) + actual.emplace(data.llmq_type, &data); + size_t known_count{0}; + std::set required_work_hashes; + std::set> required_modifiers; + for (const auto& params : consensus.llmqs) { + const bool enabled{chainman.IsQuorumTypeEnabled(params.type, base_index)}; + const auto it{actual.find(params.type)}; + if (it == actual.end()) { + if (enabled) return fail("missing enabled evo quorum type"); + continue; + } + ++known_count; + const auto& data{*it->second}; + // A disabled type is carried only for the retained commitments it + // still contributes to the CbTx quorum merkle root. + if (!enabled && data.active_commitments.empty()) return fail("empty disabled evo quorum type"); + const bool rotation_enabled{llmq::IsQuorumRotationEnabled(params, base_index)}; + const size_t active_count{static_cast(params.signingActiveQuorumCount)}; + const size_t total_count{SnapshotCommitmentCount(params, rotation_enabled)}; + if (data.rotation_enabled != rotation_enabled || data.active_commitments.size() > active_count || + data.safety_commitments.size() > total_count - active_count) { + return fail("evo quorum params/count mismatch"); + } + + std::set active_indexes; + std::vector carried; + const auto check_commitment = [&](const MinedQuorumCommitment& entry) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + if (!ValidateCommitmentAgainstChain(entry, chainman, base_index, params, rotation_enabled)) return false; + const CBlockIndex* quorum{chainman.m_blockman.LookupBlockIndex(entry.quorum_base_block_hash)}; + const CBlockIndex* work{ + base_index->GetAncestor(EvoSnapshotWorkHeight(consensus, params, rotation_enabled, quorum->nHeight))}; + if (work == nullptr || entry.work_block_hash != work->GetBlockHash()) return false; + carried.push_back(quorum); + return true; + }; + for (const auto& entry : data.active_commitments) { + if (!check_commitment(entry) || + (rotation_enabled && !active_indexes.insert(entry.commitment.quorumIndex).second)) { + return fail("invalid active evo quorum commitment chain data"); + } + } + for (const auto& entry : data.safety_commitments) { + if (!check_commitment(entry)) return fail("invalid safety evo quorum commitment chain data"); + } + + EvoSnapshotDependencyPlan plan; + if (!PlanEvoSnapshotDependencies(chainman, base_index, params.type, carried, plan, error)) return false; + + std::set expected_cycles; + for (const CBlockIndex* cycle : plan.rotation_cycles) + expected_cycles.insert(cycle->GetBlockHash()); + std::set actual_cycles; + for (const auto& entry : data.rotation_snapshots) + actual_cycles.insert(entry.cycle_base_block_hash); + if (actual_cycles != expected_cycles) return fail("evo rotation cycles differ from the planned set"); + for (const auto& entry : data.rotation_snapshots) { + // A planned cycle: a known ancestor of the base, above the work depth. + const CBlockIndex* cycle{Assert(chainman.m_blockman.LookupBlockIndex(entry.cycle_base_block_hash))}; + const CBlockIndex* work{Assert(cycle->GetAncestor(cycle->nHeight - llmq::WORK_DIFF_DEPTH))}; + if (entry.work_block_hash != work->GetBlockHash()) return fail("evo rotation cycle/work ancestor mismatch"); + const auto historical{historical_lists.find(work->GetBlockHash())}; + if (historical == historical_lists.end() || + entry.snapshot.activeQuorumMembers.size() != historical->second.GetCounts().total()) { + return fail("evo rotation bitset/work-block MN count mismatch"); + } + // The ordinary computation stores no quarter for a cycle with too + // few masternodes, so later cycles read without one, and a base + // that needs such a cycle is unsupported. This catches the first + // no-store path only; the pin covers the other (no member added). + if (historical->second.GetCounts().enabled() < static_cast(params.size / 4)) { + return fail("evo rotation quarter carried for a cycle the ordinary computation leaves without one"); + } + } + if (data.bootstrap_work != plan.bootstrap_work) return fail("evo bootstrap work differs from the planned set"); + + for (const auto& work : plan.work_blocks) { + const uint256& work_hash{work.work_index->GetBlockHash()}; + required_work_hashes.insert(work_hash); + required_modifiers.emplace(params.type, work_hash); + const auto carried_modifier{carried_modifiers.find(std::make_pair(params.type, work_hash))}; + if (carried_modifier == carried_modifiers.end()) return fail("missing planned evo quorum modifier"); + // Recompute wherever the chain allows; only an unreadable v20 work + // block leaves the carried value to the pin. + std::string modifier_error; + EvoSectionFailure modifier_failure; + const auto expected{ExactWorkModifier(params, consensus, chainman.m_blockman, base_index, work, + carried_modifier->second, modifier_error, modifier_failure)}; + if (!expected) return fail(modifier_error); + if (*expected != carried_modifier->second) return fail("evo carried quorum modifier mismatch"); + } + } + if (actual.size() != known_count) return fail("unknown evo quorum type"); + + std::set historical_hashes; + for (const auto& entry : snapshot.historical_mn_list_diffs) + historical_hashes.insert(entry.block_hash); + required_work_hashes.erase(base_index->GetBlockHash()); + if (historical_hashes != required_work_hashes) return fail("historical evo MN lists differ from the planned set"); + std::set> actual_modifiers; + for (const auto& [key, _] : carried_modifiers) + actual_modifiers.insert(key); + if (actual_modifiers != required_modifiers) return fail("evo quorum modifiers differ from the planned set"); + + if (!MoneyRange(snapshot.credit_pool.locked) || !MoneyRange(snapshot.credit_pool.currentLimit) || + !MoneyRange(snapshot.credit_pool.latelyUnlocked)) + return fail("invalid evo credit pool monetary value"); + for (const auto& [bit, height] : snapshot.mnhf_signals) { + if (bit >= VERSIONBITS_NUM_BITS || height < 0 || height > base_index->nHeight) { + return fail("invalid evo MNHF signal bit/height"); + } + } + return CheckEvoSnapshotScanCoverage(snapshot, chainman, base_index, error); +} + +bool VerifyEvoSnapshotBaseBlock(const EvoSnapshot& snapshot, const CBlockIndex& base_index, std::string& error) +{ + if (!snapshot.base_coinbase) { + error = "evo snapshot without a base coinbase"; + return false; + } + if (ComputeMerkleRootFromBranch(snapshot.base_coinbase->GetHash(), snapshot.base_coinbase_branch, 0) != + base_index.hashMerkleRoot) { + error = "evo snapshot base coinbase is not proven by the base header"; + return false; + } + const auto cbtx{DecodeCbTxPayload(*snapshot.base_coinbase)}; + if (!cbtx) { + error = "evo snapshot base coinbase has no valid CbTx payload"; + return false; + } + return VerifyEvoSnapshotCbTx(snapshot, *cbtx, error); +} + +bool PreflightEvoSnapshot(const EvoSnapshot& snapshot, const ChainstateManager& chainman, const CBlockIndex* base_index, + std::string& error, EvoSectionFailure* failure) +{ + AssertLockHeld(::cs_main); + if (failure) *failure = base_index ? EvoSectionFailure::DISAGREEMENT : EvoSectionFailure::INTERNAL_ERROR; + if (!ValidateEvoSnapshotAgainstChain(snapshot, chainman, base_index, error)) return false; + return !DeploymentActiveAt(*base_index, chainman.GetConsensus(), Consensus::DEPLOYMENT_DIP0003) || + VerifyEvoSnapshotBaseBlock(snapshot, *base_index, error); +} + +bool SeedEvoSnapshotState(const EvoViewToken& view, const EvoSnapshot& snapshot, CSpecialTxProcessor& special_tx, + const node::BlockManager& blockman, const CBlockIndex* base_index, std::string& error) +{ + auto& dmnman{special_tx.DeterministicMNManager()}; + auto& qblockman{special_tx.QuorumBlockProcessor()}; + auto& qsnapman{special_tx.QuorumSnapshotManager()}; + auto& cpoolman{*special_tx.m_cpoolman}; + auto& mnhfman{*special_tx.m_mnhfman}; + AssertLockHeld(::cs_main); + const auto fail = [&](const std::string& message) { + error = message; + return false; + }; + if (base_index == nullptr || base_index->GetBlockHash() != snapshot.base_block_hash) { + return fail("evo snapshot seeding base mismatch"); + } + std::map historical_lists; + if (!ReconstructHistoricalMNLists(snapshot, historical_lists, error)) return false; + if (!dmnman.SeedListForBlock(view, snapshot.mn_list)) return fail("failed to seed the base MN list"); + for (const auto& [_, list] : historical_lists) { + if (!dmnman.SeedListForBlock(view, list)) return fail("failed to seed a historical MN list"); + } + for (const auto& modifier : snapshot.quorum_modifiers) { + if (!qsnapman.SeedQuorumModifier(view, modifier.llmq_type, modifier.work_block_hash, modifier.modifier)) { + return fail("failed to seed a quorum score modifier"); + } + } + for (const auto& data : snapshot.quorums) { + for (const auto* commitments : {&data.active_commitments, &data.safety_commitments}) { + for (const auto& entry : *commitments) { + if (!qblockman.SeedMinedCommitment(view, data.llmq_type, entry.quorum_base_block_hash, entry.commitment, + entry.mined_block_hash)) { + return fail("failed to seed a mined quorum commitment"); + } + } + } + for (const auto& rotation : data.rotation_snapshots) { + const CBlockIndex* cycle{blockman.LookupBlockIndex(rotation.cycle_base_block_hash)}; + if (cycle == nullptr || !qsnapman.SeedSnapshotForBlock(view, data.llmq_type, cycle, rotation.snapshot)) { + return fail("failed to seed a rotation quarter"); + } + } + } + if (!cpoolman.SeedSnapshot(view, base_index, snapshot.credit_pool) || + !cpoolman.SeedHistory(view, base_index, snapshot.credit_history)) { + return fail("failed to seed the credit pool"); + } + if (!mnhfman.SeedSignals(view, base_index, snapshot.mnhf_signals)) return fail("failed to seed the MNHF signals"); + if (snapshot.base_coinbase && !special_tx.SeedBaseCoinbase(view, base_index, *snapshot.base_coinbase)) { + return fail("failed to seed the base coinbase"); + } + for (const auto& params : special_tx.ConsensusParams().llmqs) { + if (!qblockman.SeedScanCoverage(view, params.type, EvoSnapshotScanCoverage(snapshot, params))) { + return fail("failed to seed quorum scan coverage"); + } + } + return true; +} + +bool DryRunEvoSnapshot(const EvoSnapshot& snapshot, const ChainstateManager& chainman, CSpecialTxProcessor& special_tx, + const CBlockIndex* base_index, std::string& error) +{ + AssertLockHeld(::cs_main); + const auto& consensus{chainman.GetConsensus()}; + const llmq::UtilParameters util{special_tx.DeterministicMNManager(), special_tx.QuorumSnapshotManager(), chainman, + Assert(base_index)}; + try { + for (const auto& data : snapshot.quorums) { + const auto& params{SnapshotLLMQParams(data.llmq_type)}; + for (const auto* commitments : {&data.active_commitments, &data.safety_commitments}) { + for (const auto& entry : *commitments) { + const CBlockIndex* quorum{chainman.m_blockman.LookupBlockIndex(entry.quorum_base_block_hash)}; + if (quorum == nullptr) { + error = "evo snapshot dry run: unknown carried quorum"; + return false; + } + (void)llmq::utils::GetAllQuorumMembers(data.llmq_type, util.replace_index(quorum), + /*reset_cache=*/true); + } + } + if (!chainman.IsQuorumTypeEnabled(data.llmq_type, base_index)) continue; + const int h{base_index->nHeight - base_index->nHeight % params.dkgInterval}; + if (h > 0) { + (void)llmq::utils::GetAllQuorumMembers(data.llmq_type, util.replace_index(base_index->GetAncestor(h)), + /*reset_cache=*/true); + } + // The next cycle has no header yet; its members are computable + // from the section only when its work block is at or below the base. + const int next{h + params.dkgInterval}; + const int work_height{EvoSnapshotWorkHeight(consensus, params, data.rotation_enabled, next)}; + if (work_height >= 0 && work_height <= base_index->nHeight) { + const CBlockIndex* work{base_index->GetAncestor(work_height)}; + // Before v20 the modifier needs the next cycle's own block hash. + if (!llmq::utils::ComputeQuorumMembersFromWorkBlock(data.llmq_type, util.replace_index(work), work, next) && + DeploymentActiveAfter(work, consensus, Consensus::DEPLOYMENT_V20)) { + error = "evo snapshot dry run: the members of the next cycle are not computable"; + return false; + } + } + } + } catch (const LocalStateError& e) { + error = strprintf("evo snapshot dry run: %s", e.what()); + return false; + } + return true; +} + +namespace { +// Captures are NORMAL records that exist only while a snapshot is being +// validated: (prefix, kind, block hash, LLMQ type). +const std::string EVODB_SNAPSHOT_CAPTURE{"assumeutxo_capture"}; +enum class CaptureKind : uint8_t { + MODIFIER, + CREDIT_HISTORY, + BASE_COINBASE, + BASE_CREDIT_POOL +}; +using CaptureKey = std::tuple; + +CaptureKey MakeCaptureKey(CaptureKind kind, const uint256& block_hash, + Consensus::LLMQType llmq_type = Consensus::LLMQType::LLMQ_NONE) +{ + return {EVODB_SNAPSHOT_CAPTURE, static_cast(kind), block_hash, static_cast(llmq_type)}; +} +} // namespace + +std::optional PlanEvoSnapshotCaptures(const EvoSnapshot& snapshot, const ChainstateManager& chainman) +{ + AssertLockHeld(::cs_main); + const CBlockIndex* base{chainman.m_blockman.LookupBlockIndex(snapshot.base_block_hash)}; + if (base == nullptr) return std::nullopt; + EvoSnapshotCapturePlan plan; + plan.base = base->GetBlockHash(); + plan.base_height = base->nHeight; + if (!snapshot.base_coinbase) return plan; + // The chain checks, which refuse a credit window reaching below genesis, + // run after the captures. + if (snapshot.credit_history.size() > static_cast(base->nHeight) + 1) return std::nullopt; + plan.heights.insert(base->nHeight); + plan.window_first = base->nHeight - static_cast(snapshot.credit_history.size()) + 1; + for (int height{plan.window_first}; height <= base->nHeight; ++height) + plan.heights.insert(height); + for (const auto& entry : snapshot.quorum_modifiers) { + const CBlockIndex* work{chainman.m_blockman.LookupBlockIndex(entry.work_block_hash)}; + if (work == nullptr || base->GetAncestor(work->nHeight) != work) return std::nullopt; + // Only a v20 work block's modifier comes from its body. + if (!DeploymentActiveAfter(work, chainman.GetConsensus(), Consensus::DEPLOYMENT_V20)) continue; + plan.modifier_blocks[work->GetBlockHash()].push_back(entry.llmq_type); + plan.heights.insert(work->nHeight); + } + return plan; +} + +bool WriteEvoSnapshotCaptures(CEvoDB& evodb, CCreditPoolManager& cpoolman, const node::BlockManager& blockman, + const EvoSnapshotCapturePlan& plan, const CBlock& block, const CBlockIndex& index, + const Consensus::Params& consensus, std::string& error) +{ + if (!plan.heights.contains(index.nHeight) || index.nHeight > plan.base_height) return true; + const uint256 hash{index.GetBlockHash()}; + if (const auto it{plan.modifier_blocks.find(hash)}; it != plan.modifier_blocks.end()) { + for (const auto llmq_type : it->second) { + const uint256 modifier{ + llmq::utils::GetWorkBlockModifier(SnapshotLLMQParams(llmq_type), block, index)}; + if (!evodb.WriteDerived(MakeCaptureKey(CaptureKind::MODIFIER, hash, llmq_type), modifier)) { + error = "conflicting quorum modifier capture"; + return false; + } + } + } + if (index.nHeight >= plan.window_first) { + const auto entry{CCreditPoolManager::ReadHistoryEntry(&index, blockman, consensus, error)}; + if (!entry || !evodb.WriteDerived(MakeCaptureKey(CaptureKind::CREDIT_HISTORY, hash), *entry)) { + if (error.empty()) error = "conflicting credit-pool window capture"; + return false; + } + } + if (hash == plan.base) { + if (block.vtx.empty() || !evodb.WriteDerived(MakeCaptureKey(CaptureKind::BASE_COINBASE, hash), + std::make_pair(block.vtx[0], BlockMerkleBranch(block, 0)))) { + error = "conflicting base coinbase capture"; + return false; + } + // The pool at the base folds in every block back to the last pool on + // disk, which may lie below the window. + std::optional pool; + try { + pool = cpoolman.GetCreditPool(&index); + } catch (const LocalStateError&) { + // This node's own data, e.g. a pruned body: the caller stalls. + throw; + } catch (const std::exception& e) { + error = strprintf("the credit pool at the base is not computable: %s", e.what()); + return false; + } + if (!evodb.WriteDerived(MakeCaptureKey(CaptureKind::BASE_CREDIT_POOL, hash), *pool)) { + error = "conflicting base credit pool capture"; + return false; + } + } + return true; +} + +EvoSnapshotCaptures ReadEvoSnapshotCaptures(CEvoDB& evodb, const EvoSnapshotCapturePlan& plan, + const ChainstateManager& chainman) +{ + AssertLockHeld(::cs_main); + EvoSnapshotCaptures captures; + for (const auto& [hash, types] : plan.modifier_blocks) { + for (const auto llmq_type : types) { + uint256 modifier; + if (evodb.Read(MakeCaptureKey(CaptureKind::MODIFIER, hash, llmq_type), modifier)) { + captures.modifiers.emplace(std::make_pair(llmq_type, hash), modifier); + } + } + } + const CBlockIndex* base{chainman.m_blockman.LookupBlockIndex(plan.base)}; + if (base == nullptr || plan.window_first < 0) return captures; + for (int height{plan.window_first}; height <= plan.base_height; ++height) { + const uint256 hash{base->GetAncestor(height)->GetBlockHash()}; + CreditHistoryEntry entry; + if (evodb.Read(MakeCaptureKey(CaptureKind::CREDIT_HISTORY, hash), entry)) { + captures.credit_history.emplace(hash, entry); + } + } + std::pair> coinbase; + if (evodb.Read(MakeCaptureKey(CaptureKind::BASE_COINBASE, plan.base), coinbase)) { + std::tie(captures.base_coinbase, captures.base_coinbase_branch) = std::move(coinbase); + } + if (CCreditPool pool; evodb.Read(MakeCaptureKey(CaptureKind::BASE_CREDIT_POOL, plan.base), pool)) { + captures.base_credit_pool = std::move(pool); + } + return captures; +} + +bool EraseAllEvoSnapshotCaptures(CEvoDB& evodb) +{ + CDBWrapper& db{evodb.GetRawDB()}; + DataStream prefix; + prefix << EVODB_SNAPSHOT_CAPTURE; + std::unique_ptr it{db.NewIterator()}; + CDBBatch batch{db}; + for (it->Seek(prefix); it->Valid(); it->Next()) { + const auto key{it->GetKey()}; + if (key.size() < prefix.size() || !std::equal(prefix.begin(), prefix.end(), key.begin())) break; + batch.Erase(key); + } + // Most startups have nothing to erase; spare them the synced write. + return !it->HasError() && (batch.SizeEstimate() == 0 || db.WriteBatch(batch, /*fSync=*/true)); +} + +void EraseEvoSnapshotCaptures(CEvoDB& evodb, const EvoSnapshotCapturePlan& plan, const ChainstateManager& chainman) +{ + AssertLockHeld(::cs_main); + for (const auto& [hash, types] : plan.modifier_blocks) { + for (const auto llmq_type : types) + evodb.Erase(MakeCaptureKey(CaptureKind::MODIFIER, hash, llmq_type)); + } + const CBlockIndex* base{chainman.m_blockman.LookupBlockIndex(plan.base)}; + if (base == nullptr || plan.window_first < 0) return; + for (int height{plan.window_first}; height <= plan.base_height; ++height) { + evodb.Erase(MakeCaptureKey(CaptureKind::CREDIT_HISTORY, base->GetAncestor(height)->GetBlockHash())); + } + evodb.Erase(MakeCaptureKey(CaptureKind::BASE_COINBASE, plan.base)); + evodb.Erase(MakeCaptureKey(CaptureKind::BASE_CREDIT_POOL, plan.base)); +} + +} // namespace evo diff --git a/src/evo/specialtxman.cpp b/src/evo/specialtxman.cpp index b1a64860b094..2280c9c275e7 100644 --- a/src/evo/specialtxman.cpp +++ b/src/evo/specialtxman.cpp @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include #include @@ -28,6 +30,7 @@ #include #include #include +#include #include #include @@ -38,6 +41,7 @@ CSpecialTxProcessor::CSpecialTxProcessor(CEvoDB& evodb, CDeterministicMNManager& const chainlock::Chainlocks& chainlocks, const llmq::CQuorumManager& qman) : m_cpoolman{std::make_unique(evodb, chainman)}, m_mnhfman{std::make_unique(evodb, blockman, consensus_params, notifications)}, + m_evodb{evodb}, m_dmnman{dmnman}, m_qblockman{qblockman}, m_qsnapman{qsnapman}, @@ -52,6 +56,52 @@ CSpecialTxProcessor::CSpecialTxProcessor(CEvoDB& evodb, CDeterministicMNManager& CSpecialTxProcessor::~CSpecialTxProcessor() = default; +// The coinbase of an assumeutxo snapshot base, carried by the snapshot and +// proven against the base header. Written only into a snapshot generation. +static const std::string DB_BASE_COINBASE{"cb_S"}; + +CoinbaseChainlock CSpecialTxProcessor::GetCoinbaseChainlock(const CBlockIndex* pindex) const +{ + CoinbaseChainlock result; + // There's no CL in CbTx before v20 activation + if (pindex == nullptr || !DeploymentActiveAt(*pindex, m_consensus_params, Consensus::DEPLOYMENT_V20)) return result; + const auto from_coinbase = [&](const CTransaction& coinbase) { + const auto cbtx{DecodeCbTxPayload(coinbase)}; + if (cbtx && cbtx->nVersion >= CCbTx::Version::CLSIG_AND_BALANCE && cbtx->nHeight == pindex->nHeight && + cbtx->bestCLSignature.Get().IsValid() && cbtx->bestCLHeightDiff < static_cast(pindex->nHeight)) { + result = {CoinbaseChainlock::Status::CERTIFIED, cbtx->bestCLSignature.Get(), cbtx->bestCLHeightDiff}; + } + return result; + }; + const EvoViewToken view{m_evodb.CurrentView()}; + const bool snapshot_view{view.identity == EvoDbIdentity::SNAPSHOT}; + if (snapshot_view && pindex->nHeight == view.base_height) { + CMutableTransaction carried; + if (m_evodb.Read(std::make_pair(DB_BASE_COINBASE, pindex->GetBlockHash()), carried)) { + return from_coinbase(CTransaction{carried}); + } + } + const auto [have_data, block_pos]{WITH_LOCK(::cs_main, return std::make_pair( + (pindex->nStatus & BLOCK_HAVE_DATA) != 0, pindex->GetBlockPos()))}; + if (!have_data) { + if (snapshot_view) result.status = CoinbaseChainlock::Status::UNAVAILABLE; + return result; + } + CBlock block; + if (m_blockman.ReadBlockFromDisk(block, block_pos) != pindex->GetBlockHash()) { + throw BlockDataReadError(strprintf("coinbase of block %s cannot be read", pindex->GetBlockHash().ToString())); + } + if (block.vtx.empty()) return result; + return from_coinbase(*block.vtx[0]); +} + +bool CSpecialTxProcessor::SeedBaseCoinbase(const EvoViewToken& view, const CBlockIndex* base, const CTransaction& coinbase) +{ + if (!Assume(base != nullptr) || !Assume(m_evodb.HasActiveTransaction())) return false; + m_evodb.RequireTransactionView(view); + return m_evodb.WriteSeed(std::make_pair(DB_BASE_COINBASE, base->GetBlockHash()), CMutableTransaction{coinbase}); +} + static bool AddNetInfoEntries(const std::shared_ptr& net_info, NetInfoPurpose purpose, const NetInfoList& entries, BlockValidationState& state) { @@ -147,14 +197,15 @@ static bool ApplyProUpServTx(CDeterministicMNState& state_mn, const CProUpServTx } bool CheckCbTxBestChainlock(const CCbTx& cbTx, const CBlockIndex* pindex, const Consensus::Params& consensus_params, - const node::BlockManager& blockman, const CChain& chain, const llmq::CQuorumManager& qman, - const chainlock::Chainlocks& chainlocks, BlockValidationState& state) + const CChain& chain, const llmq::CQuorumManager& qman, const chainlock::Chainlocks& chainlocks, + const CSpecialTxProcessor& special_tx, BlockValidationState& state) { if (cbTx.nVersion < CCbTx::Version::CLSIG_AND_BALANCE) { return true; } 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 +215,35 @@ 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); + const CoinbaseChainlock previous{special_tx.GetCoinbaseChainlock(pindex->pprev)}; + if (previous.status == CoinbaseChainlock::Status::UNAVAILABLE) { + throw BlockDataUnavailableError( + strprintf("coinbase ChainLock of block %s is not available", pindex->pprev->GetBlockHash().ToString())); + } + if (previous.status == CoinbaseChainlock::Status::CERTIFIED) { + prevBlockCoinbaseChainlock = std::make_pair(previous.signature, previous.height_diff); + } } // If std::optional prevBlockCoinbaseChainlock is empty, then up to the previous block, coinbase Chainlock is null. if (prevBlockCoinbaseChainlock.has_value()) { @@ -204,7 +266,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 +275,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 +291,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"); @@ -875,9 +940,17 @@ bool CMNListBuilder::Finish(const CBlock& block, BlockValidationState& state, CD mnListRet); } +uint256 CanonicalDeterministicMNListHash(gsl::not_null pindex, const CDeterministicMNList& list) +{ + if (list.GetBlockHash().IsNull()) { + return evo::CanonicalMNListHash(CDeterministicMNList{pindex->GetBlockHash(), pindex->nHeight, 0}); + } + return evo::CanonicalMNListHash(list); +} + uint256 CSpecialTxProcessor::GetDeterministicMNListHash(gsl::not_null pindex) const { - return SerializeHash(m_dmnman.GetListForBlock(pindex)); + return CanonicalDeterministicMNListHash(pindex, m_dmnman.GetListForBlock(pindex)); } void CSpecialTxProcessor::UpdatedMNListTip(gsl::not_null pindex) { m_dmnman.UpdatedBlockTip(pindex); } @@ -890,7 +963,10 @@ void CSpecialTxProcessor::ResetPlatformBans(const CBlock& block, const CBlockInd m_dmnman.ResetPlatformBans(block, index); } -void CSpecialTxProcessor::DiscardDeterministicMNBlock(const uint256& block_hash) { m_dmnman.DiscardBlock(block_hash); } +void CSpecialTxProcessor::DiscardDeterministicMNBlock(const EvoViewToken& view, const uint256& block_hash) +{ + m_dmnman.DiscardBlock(view, block_hash); +} bool CSpecialTxProcessor::ProcessSpecialTxsInBlock(Chainstate& chainstate, const CChain& chain, const CBlock& block, const CBlockIndex* pindex, SpecialTxRules rules, @@ -900,6 +976,10 @@ bool CSpecialTxProcessor::ProcessSpecialTxsInBlock(Chainstate& chainstate, const { AssertLockHeld(::cs_main); + if (!HoldsEvoTransaction(chainstate)) { + throw EvoViewBindingError(strprintf("%s: outside the chainstate's Evo transaction", __func__)); + } + try { static SteadyClock::duration nTimeLoop{}; static SteadyClock::duration nTimeQuorum{}; @@ -1063,7 +1143,7 @@ bool CSpecialTxProcessor::ProcessSpecialTxsInBlock(Chainstate& chainstate, const LogPrint(BCLog::BENCHMARK, " - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\n", Ticks(nTime6_2 - nTime6_1), Ticks(nTimeMerkleQuorums)); - if (!CheckCbTxBestChainlock(*opt_cbTx, pindex, m_consensus_params, m_blockman, chain, m_qman, m_chainlocks, state)) { + if (!CheckCbTxBestChainlock(*opt_cbTx, pindex, m_consensus_params, chain, m_qman, m_chainlocks, *this, state)) { // pass the state returned by the function above return false; } @@ -1097,9 +1177,13 @@ bool CSpecialTxProcessor::ProcessSpecialTxsInBlock(Chainstate& chainstate, const return true; } -bool CSpecialTxProcessor::UndoSpecialTxsInBlock(const Chainstate& chainstate, const CBlock& block, const CBlockIndex* pindex, MNListUpdates& updatesRet) +bool CSpecialTxProcessor::UndoSpecialTxsInBlock(const Chainstate& chainstate, const CBlock& block, + const CBlockIndex* pindex, MNListUpdates& updatesRet) { AssertLockHeld(::cs_main); + if (!HoldsEvoTransaction(chainstate)) { + throw EvoViewBindingError(strprintf("%s: outside the chainstate's Evo transaction", __func__)); + } try { if (!m_mnhfman->UndoBlock(block, pindex)) { diff --git a/src/evo/specialtxman.h b/src/evo/specialtxman.h index 4dac8cd057f6..cd526088d64d 100644 --- a/src/evo/specialtxman.h +++ b/src/evo/specialtxman.h @@ -5,6 +5,7 @@ #ifndef BITCOIN_EVO_SPECIALTXMAN_H #define BITCOIN_EVO_SPECIALTXMAN_H +#include #include #include #include @@ -33,8 +34,13 @@ class Chainstate; class CMNHFManager; class TxValidationState; class uint256; +struct EvoViewToken; struct MNListUpdates; +//! Whether the calling thread holds `chainstate`'s Evo transaction (defined in +//! validation.cpp, so callers need only this declaration). +bool HoldsEvoTransaction(const Chainstate& chainstate); + namespace chainlock { class Chainlocks; } @@ -64,6 +70,21 @@ struct SpecialTxRules { BLSScheme bls_scheme{BLSScheme::Basic}; }; +/** The ChainLock a block's coinbase certifies, as far as this node can tell. */ +struct CoinbaseChainlock { + enum class Status { + //! The coinbase carries a non-null ChainLock. + CERTIFIED, + //! The coinbase is known to carry none (or there is no CbTx ChainLock yet). + NONE, + //! This node cannot tell: the block's data is not available to its view. + UNAVAILABLE, + }; + Status status{Status::NONE}; + CBLSSignature signature{}; + uint32_t height_diff{0}; +}; + class CSpecialTxProcessor { public: @@ -73,6 +94,7 @@ class CSpecialTxProcessor const std::unique_ptr m_mnhfman; private: + CEvoDB& m_evodb; CDeterministicMNManager& m_dmnman; llmq::CQuorumBlockProcessor& m_qblockman; llmq::CQuorumSnapshotManager& m_qsnapman; @@ -99,8 +121,8 @@ class CSpecialTxProcessor CAmount blockSubsidy, bool fJustCheck, bool fCheckCbTxMerkleRoots, BlockValidationState& state, MNListUpdates& updatesRet) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); - bool UndoSpecialTxsInBlock(const Chainstate& chainstate, const CBlock& block, const CBlockIndex* pindex, MNListUpdates& updatesRet) - EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + bool UndoSpecialTxsInBlock(const Chainstate& chainstate, const CBlock& block, const CBlockIndex* pindex, + MNListUpdates& updatesRet) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); void RemoveMineableCommitmentsForBlock(const CBlock& block, gsl::not_null pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); @@ -120,6 +142,20 @@ class CSpecialTxProcessor /** Return a canonical hash of the deterministic MN list derived at a block. */ uint256 GetDeterministicMNListHash(gsl::not_null pindex) const; + /** The ChainLock certified by `pindex`'s coinbase. At a snapshot base, in + * the snapshot view, it comes from the carried coinbase. Without the + * block's data the snapshot view answers UNAVAILABLE; NORMAL keeps the + * legacy answer NONE. A block this node has but cannot read raises + * BlockDataReadError. */ + CoinbaseChainlock GetCoinbaseChainlock(const CBlockIndex* pindex) const; + /** Seed the header-proven coinbase of a snapshot base into `view`, inside + * the caller's open EvoDB transaction for that view. */ + bool SeedBaseCoinbase(const EvoViewToken& view, const CBlockIndex* base, const CTransaction& coinbase); + + const Consensus::Params& ConsensusParams() const { return m_consensus_params; } + CDeterministicMNManager& DeterministicMNManager() { return m_dmnman; } + llmq::CQuorumBlockProcessor& QuorumBlockProcessor() { return m_qblockman; } + llmq::CQuorumSnapshotManager& QuorumSnapshotManager() { return m_qsnapman; } /** Passthrough to CDeterministicMNManager::UpdatedBlockTip */ void UpdatedMNListTip(gsl::not_null pindex); @@ -128,7 +164,7 @@ class CSpecialTxProcessor void RebuildMNHFSignals(const CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); void ResetPlatformBans(const CBlock& block, const CBlockIndex& index) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); - void DiscardDeterministicMNBlock(const uint256& block_hash); + void DiscardDeterministicMNBlock(const EvoViewToken& view, const uint256& block_hash); private: friend class CMNListBuilder; @@ -152,6 +188,10 @@ class CSpecialTxProcessor CAmount blockSubsidy, BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); }; +/** Canonical hash of a block's deterministic MN list. An unbound list (none is + * built before DIP3) hashes as the empty list bound to the block. */ +uint256 CanonicalDeterministicMNListHash(gsl::not_null pindex, const CDeterministicMNList& list); + /** * Builds the masternode list for a block one transaction at a time, with the same result as * CSpecialTxProcessor::RebuildListFromBlock() over the same transactions. Block assembly uses it to @@ -197,8 +237,8 @@ std::optional GetValidatedPayload(const CTransaction& tx, gsl::not_null pindexPrev, CDeterministicMNManager& dmnman, const CCoinsViewCache& view, const Consensus::Params& consensus_params, SpecialTxRules rules, 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/governance/governance.cpp b/src/governance/governance.cpp index 607f5679d779..fbd74e559a04 100644 --- a/src/governance/governance.cpp +++ b/src/governance/governance.cpp @@ -916,30 +916,32 @@ void CGovernanceManager::CheckPostponedObjects() AssertLockNotHeld(cs_relay); if (!m_mn_sync.IsSynced()) return; - // Check postponed proposals - for (auto it = mapPostponedObjects.begin(); it != mapPostponedObjects.end();) { - const uint256& nHash = it->first; - auto& govobj = *Assert(it->second); - - assert(govobj.GetObjectType() != GovernanceObject::TRIGGER); - - std::string strError; - bool fMissingConfirmations; - if (govobj.IsCollateralValid(m_collateral, m_chainman, strError, fMissingConfirmations)) { - if (govobj.IsValidLocally(m_dmnman.GetListAtChainTip(), m_chainman, /*collateral=*/nullptr, strError, false)) { - AddGovernanceObjectInternal(govobj, ""); - } else { - LogPrint(BCLog::GOBJECT, "CGovernanceManager::CheckPostponedObjects -- %s invalid\n", nHash.ToString()); + // Check postponed proposals, unless their collateral can't be looked up yet: a failed lookup drops them + if (!IsCollateralSourceBehind()) { + for (auto it = mapPostponedObjects.begin(); it != mapPostponedObjects.end();) { + const uint256& nHash = it->first; + auto& govobj = *Assert(it->second); + + assert(govobj.GetObjectType() != GovernanceObject::TRIGGER); + + std::string strError; + bool fMissingConfirmations; + if (govobj.IsCollateralValid(m_collateral, m_chainman, strError, fMissingConfirmations)) { + if (govobj.IsValidLocally(m_dmnman.GetListAtChainTip(), m_chainman, /*collateral=*/nullptr, strError, false)) { + AddGovernanceObjectInternal(govobj, ""); + } else { + LogPrint(BCLog::GOBJECT, "CGovernanceManager::CheckPostponedObjects -- %s invalid\n", nHash.ToString()); + } + + } else if (fMissingConfirmations) { + // wait for more confirmations + ++it; + continue; } - } else if (fMissingConfirmations) { - // wait for more confirmations - ++it; - continue; + // remove processed or invalid object from the queue + mapPostponedObjects.erase(it++); } - - // remove processed or invalid object from the queue - mapPostponedObjects.erase(it++); } diff --git a/src/governance/net_governance.cpp b/src/governance/net_governance.cpp index 862af01c5148..a76e1a3569bb 100644 --- a/src/governance/net_governance.cpp +++ b/src/governance/net_governance.cpp @@ -176,23 +176,23 @@ void NetGovernance::ProcessMessage(CNode& peer, const std::string& msg_type, Dat LogPrint(BCLog::GOBJECT, "MNGOVERNANCEOBJECT -- Received object: %s\n", strHash); - // Only accept an object if this peer announced it or we requested it from this peer. The - // net-layer per-peer request tracker is the authorization source (already bounded), so no - // separate governance-side request cache is needed. Consume only after the sync gate, so a - // message dropped while not synced does not burn the authorization for a later retransmit. - const bool announced_or_requested = WITH_LOCK( - ::cs_main, return m_peer_manager->PeerConsumeObjectRequest(peer.GetId(), CInv{MSG_GOVERNANCE_OBJECT, nHash})); - if (!announced_or_requested) { - LogPrint(BCLog::GOBJECT, "MNGOVERNANCEOBJECT -- Received unrequested object: %s\n", strHash); - return; - } - - if (WITH_LOCK(::cs_main, return m_gov_manager.ProcessObject(peer.GetLogString(), nHash, govobj))) { - WITH_LOCK(::cs_main, m_peer_manager->PeerForgetObjectRequest(CInv{MSG_GOVERNANCE_OBJECT, nHash})); - } else { - // apply node's ban score - m_peer_manager->PeerMisbehaving(peer.GetId(), 20); + // Accept only an object this peer announced or we requested from it, and consume that authorization only + // after the readiness gates, so an object they drop can still be accepted when it is sent again. + const CInv inv{MSG_GOVERNANCE_OBJECT, nHash}; + bool valid; + { + LOCK(::cs_main); + // Snapshot activation can leave collateral impossible to look up since the check above + // cppcheck-suppress knownConditionTrueFalse + if (m_gov_manager.IsCollateralSourceBehind()) return; + if (!m_peer_manager->PeerConsumeObjectRequest(peer.GetId(), inv)) { + LogPrint(BCLog::GOBJECT, "MNGOVERNANCEOBJECT -- Received unrequested object: %s\n", strHash); + return; + } + valid = m_gov_manager.ProcessObject(peer.GetLogString(), nHash, govobj); + if (valid) m_peer_manager->PeerForgetObjectRequest(inv); } + if (!valid) m_peer_manager->PeerMisbehaving(peer.GetId(), 20); } // A NEW GOVERNANCE OBJECT VOTE HAS ARRIVED diff --git a/src/index/base.cpp b/src/index/base.cpp index 3e77c9f55399..37a116e53267 100644 --- a/src/index/base.cpp +++ b/src/index/base.cpp @@ -102,9 +102,15 @@ BaseIndex::~BaseIndex() bool BaseIndex::Init() { + AssertLockNotHeld(cs_main); + + // May need reset if index is being restarted. + m_interrupt.reset(); + // m_chainstate member gives indexing code access to node internals. It is // removed in followup https://github.com/bitcoin/bitcoin/pull/24230 - m_chainstate = &m_chain->context()->chainman->ActiveChainstate(); + m_chainstate = WITH_LOCK(::cs_main, + return &m_chain->context()->chainman->GetChainstateForIndexing()); // Register to validation interface before setting the 'm_synced' flag, so that // callbacks are not missed once m_synced is true. RegisterValidationInterface(this); @@ -112,7 +118,8 @@ bool BaseIndex::Init() const auto locator{GetDB().ReadBestBlock()}; LOCK(cs_main); - CChain& active_chain = m_chainstate->m_chain; + CChain& index_chain = m_chainstate->m_chain; + const CBlockIndex* locator_index{nullptr}; if (!locator.IsNull()) { // Setting the best block to the locator's top block. If it is not part of the @@ -147,7 +154,7 @@ bool BaseIndex::Init() // Note: this will latch to true immediately if the user starts up with an empty // datadir and an index enabled. If this is the case, indexation will happen solely // via `BlockConnected` signals until, possibly, the next restart. - m_synced = start_block == active_chain.Tip(); + m_synced = start_block == index_chain.Tip(); m_init = true; return true; } @@ -182,6 +189,8 @@ void BaseIndex::ThreadSync() auto last_locator_write_time{last_log_time}; while (true) { if (m_interrupt) { + LogPrintf("%s: m_interrupt set; exiting ThreadSync\n", GetName()); + SetBestBlockIndex(pindex); // No need to handle errors in Commit. If it fails, the error will be already be // logged. The best way to recover is to continue, as index cannot be corrupted by @@ -341,8 +350,19 @@ bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_ti return true; } -void BaseIndex::BlockConnected(const std::shared_ptr& block, const CBlockIndex* pindex) +void BaseIndex::BlockConnected(ChainstateRole role, const std::shared_ptr& block, const CBlockIndex* pindex) { + // Ignore events from the assumed-valid chain; we will process its blocks + // (sequentially) after it is fully verified by the background chainstate. This + // is to avoid any out-of-order indexing. + // + // TODO at some point we could parameterize whether a particular index can be + // built out of order, but for now just do the conservative simple thing. + if (role == ChainstateRole::ASSUMEDVALID) { + return; + } + + // Ignore BlockConnected signals until we have fully indexed the chain. if (!m_synced) { return; } @@ -416,8 +436,14 @@ void BaseIndex::BlockDisconnected(const std::shared_ptr& block, co } } -void BaseIndex::ChainStateFlushed(const CBlockLocator& locator) +void BaseIndex::ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) { + // Ignore events from the assumed-valid chain; we will process its blocks + // (sequentially) after it is fully verified by the background chainstate. + if (role == ChainstateRole::ASSUMEDVALID) { + return; + } + if (!m_synced) { return; } diff --git a/src/index/base.h b/src/index/base.h index faada1e6a9e5..6ef4e29a08eb 100644 --- a/src/index/base.h +++ b/src/index/base.h @@ -19,6 +19,7 @@ class CBlock; class CBlockIndex; class Chainstate; +class ChainstateManager; namespace node { class BlockManager; } // namespace node @@ -37,6 +38,11 @@ struct IndexSummary { * Base class for indices of blockchain data. This implements * CValidationInterface and ensures blocks are indexed sequentially according * to their position in the active chain. + * + * In the presence of multiple chainstates (i.e. if a UTXO snapshot is loaded), + * only the background "IBD" chainstate will be indexed to avoid building the + * index out of order. When the background chainstate completes validation, the + * index will be reinitialized and indexing will continue. */ class BaseIndex : public CValidationInterface { @@ -123,11 +129,11 @@ class BaseIndex : public CValidationInterface Chainstate* m_chainstate{nullptr}; const std::string m_name; - void BlockConnected(const std::shared_ptr& block, const CBlockIndex* pindex) override; + void BlockConnected(ChainstateRole role, const std::shared_ptr& block, const CBlockIndex* pindex) override; void BlockDisconnected(const std::shared_ptr& block, const CBlockIndex* pindex) override; - void ChainStateFlushed(const CBlockLocator& locator) override; + void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override; /// Initialize internal state from the database and block index. [[nodiscard]] virtual bool CustomInit(const std::optional& block) { return true; } @@ -161,9 +167,6 @@ class BaseIndex : public CValidationInterface virtual DB& GetDB() const = 0; - /// Get the name of the index for display in logs. - const std::string& GetName() const LIFETIMEBOUND { return m_name; } - /// Update the internal best block index as well as the prune lock. void SetBestBlockIndex(const CBlockIndex* block); @@ -172,6 +175,9 @@ class BaseIndex : public CValidationInterface /// Destructor interrupts sync thread if running and blocks until it exits. virtual ~BaseIndex(); + /// Get the name of the index for display in logs. + const std::string& GetName() const LIFETIMEBOUND { return m_name; } + /// Blocks the current thread until the index is caught up to the current /// state of the block chain. This only blocks if the index has gotten in /// sync once and only needs to process blocks in the ValidationInterface diff --git a/src/index/govcollateralindex.cpp b/src/index/govcollateralindex.cpp index f729797b87f6..1800096cbfa7 100644 --- a/src/index/govcollateralindex.cpp +++ b/src/index/govcollateralindex.cpp @@ -80,11 +80,13 @@ GovCollateralIndex::~GovCollateralIndex() = default; bool GovCollateralIndex::CustomInit(const std::optional& block) { + AssertLockHeld(::cs_main); // BaseIndex only locks pruning once a new index has read its first block, so pruning at startup could // still delete the blocks it is about to read. if (!block) { - WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(GetName(), node::PruneLockInfo{/*height_first=*/0})); + m_chainstate->m_blockman.UpdatePruneLock(GetName(), node::PruneLockInfo{/*height_first=*/0}); } + m_indexed_chainstate = m_chainstate; return true; } @@ -147,7 +149,13 @@ bool GovCollateralIndex::CanSync(Chainstate& chainstate) const return true; } -bool GovCollateralIndex::IsCollateralSynced() const { return GetSummary().synced; } +bool GovCollateralIndex::IsCollateralSynced() const +{ + // While a snapshot is validated in the background, the index follows the background chainstate. + LOCK(::cs_main); + return m_indexed_chainstate && m_indexed_chainstate == &m_indexed_chainstate->m_chainman.ActiveChainstate() && + GetSummary().synced; +} std::optional GovCollateralIndex::FindCollateral(const uint256& txid) const { diff --git a/src/index/govcollateralindex.h b/src/index/govcollateralindex.h index bc1fa2b58cad..d2b7cb355c12 100644 --- a/src/index/govcollateralindex.h +++ b/src/index/govcollateralindex.h @@ -27,6 +27,7 @@ class GovCollateralIndex final : public BaseIndex, public governance::Collateral private: const std::unique_ptr m_db; + const Chainstate* m_indexed_chainstate GUARDED_BY(::cs_main){nullptr}; bool AllowPrune() const override { return true; } @@ -36,7 +37,7 @@ class GovCollateralIndex final : public BaseIndex, public governance::Collateral // A collateral only confirms while its block is on the active chain bool IgnoresEntriesOffActiveChain() const override { return true; } - bool CustomInit(const std::optional& block) override; + bool CustomInit(const std::optional& block) override EXCLUSIVE_LOCKS_REQUIRED(::cs_main); bool CustomAppend(const interfaces::BlockInfo& block) override; diff --git a/src/init.cpp b/src/init.cpp index b95c0e631b54..b5436771d534 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -70,6 +70,7 @@ #include #include #include +#include #include #include #include @@ -661,8 +662,8 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc) argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); argsman.AddArg("-addressindex", strprintf("Maintain a full address index, used to query for the balance, txids and unspent outputs for addresses (default: %u)", DEFAULT_ADDRESSINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); - argsman.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk. This will also rebuild active optional indexes.", ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); - argsman.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); + argsman.AddArg("-reindex", "If enabled, wipe chain state and block index, and rebuild them from blk*.dat files on disk. Also wipe and rebuild other optional indexes that are active. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); + argsman.AddArg("-reindex-chainstate", "If enabled, wipe chain state, and rebuild it from blk*.dat files on disk. If an assumeutxo snapshot was loaded, its chainstate will be wiped as well. The snapshot can then be reloaded via RPC.", ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); argsman.AddArg("-spentindex", strprintf("Maintain a full spent index, used to query the spending txid and input index for an outpoint (default: %u)", DEFAULT_SPENTINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); argsman.AddArg("-timestampindex", strprintf("Maintain a timestamp index for block hashes, used to query blocks hashes by a range of timestamps (default: %u)", DEFAULT_TIMESTAMPINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); argsman.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::INDEXING); @@ -1224,6 +1225,11 @@ bool AppInitParameterInteraction(const ArgsManager& args) const CChainParams& chainparams = Params(); // ********************************************************* Step 2: parameter interactions + // Snapshot authorizations are reviewed chain parameters on every other network. + if (args.IsArgSet("-assumeutxodata") && chainparams.GetChainType() != ChainType::REGTEST) { + return InitError(_("-assumeutxodata is only available on regtest.")); + } + // also see: InitParameterInteraction() // Error if network-specific options (-addnode, -connect, etc) are @@ -1524,6 +1530,135 @@ bool AppInitInterfaces(NodeContext& node) return true; } +void ReleaseChainstateLoadAttempt(NodeContext& node) +{ + // Validation events a failed attempt queued can read 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(); +} + +// 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) +{ + { + const CBlockIndex* tip{WITH_LOCK(::cs_main, return node.chainman->ActiveTip())}; + 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 +1700,11 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) assert(!node.scheduler); node.scheduler = std::make_unique(); + // A local Evo state error ends a scheduled task, never the scheduler. The + // scheduler starts before the block databases load, and a load retry + // replaces the Evo database, so its rounds log no view generation. + node.scheduler->SetTaskWrapper( + [](const CScheduler::Function& task) { RunActiveEvoRound(/*evodb=*/nullptr, "scheduler", task); }); // Start the lightweight task scheduler thread node.scheduler->m_service_thread = std::thread(util::TraceThread, "scheduler", [&] { node.scheduler->serviceQueue(); }); @@ -2001,6 +2141,27 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) // ********************************************************* Step 7b: load block chain + // A snapshot chainstate, validated or not, stays in use until a restart + // promotes it, and neither chainstate can run with these options. A + // reindex discards it before it is opened. + if (node::FindSnapshotChainstateDir(args.GetDataDirNet()) && !args.GetBoolArg("-reindex", false) && + !args.GetBoolArg("-reindex-chainstate", false)) { + if (args.GetIntArg("-prune", 0)) { + return InitError(_("An assumeutxo snapshot chainstate is in use, which pruning would break. Restart without " + "-prune until the snapshot has been validated and a restart has promoted it.")); + } + if (node::LegacyIndexesEnabled(args)) { + return InitError(_("An assumeutxo snapshot chainstate is in use, which -addressindex, -spentindex and " + "-timestampindex do not support. Restart without them until the snapshot has been " + "validated and a restart has promoted it.")); + } + if (args.IsArgSet("-masternodeblsprivkey")) { + return InitError(_("An assumeutxo snapshot chainstate is in use, which a masternode cannot run on. Restart " + "without -masternodeblsprivkey until the snapshot has been validated and a restart has " + "promoted it.")); + } + } + node.notifications = std::make_unique(node.exit_status); ReadNotificationArgs(args, *node.notifications); fReindex = args.GetBoolArg("-reindex", false); @@ -2067,12 +2228,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(); @@ -2098,6 +2254,31 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) node.chainman = std::make_unique(node.kernel->interrupt, chainman_opts, blockman_opts); ChainstateManager& chainman = *node.chainman; + // This is defined and set here instead of inline in validation.h to avoid a hard + // dependency between validation and index/base, since the latter is not in + // libbitcoinkernel. + chainman.snapshot_download_completed = [&node]() { + if (!node.chainman->m_blockman.IsPruneMode()) { + LogPrintf("[snapshot] re-enabling NODE_NETWORK services\n"); + node.connman->AddLocalServices(NODE_NETWORK); + } + + LogPrintf("[snapshot] restarting indexes\n"); + + // Drain the validation interface queue to ensure that the old indexes + // don't have any pending work. + SyncWithValidationInterfaceQueue(); + + LOCK(node.index_start_mutex); + for (auto* index : node.indexes) { + index->Interrupt(); + index->Stop(); + if (!(index->Init() && (!node.index_threads_started || index->StartBackgroundSync()))) { + LogPrintf("[snapshot] WARNING failed to restart index %s on snapshot chain\n", index->GetName()); + } + } + }; + node::ChainstateLoadOptions options; options.chainlocks = Assert(node.chainlocks.get()); options.data_dir = args.GetDataDirNet(); @@ -2205,7 +2386,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) // The index can't catch up once the node has pruned blocks it hasn't read, e.g. after upgrading a pruned // node, because a new index has to start from the genesis block. Starting it would fail with an init // error, so leave governance off instead. - if (WITH_LOCK(::cs_main, return gov_collateral_index->CanSync(chainman.ActiveChainstate()))) { + if (WITH_LOCK(::cs_main, return gov_collateral_index->CanSync(chainman.GetChainstateForIndexing()))) { node.gov_collateral_index = std::move(gov_collateral_index); } else if (is_governance_enabled) { is_governance_enabled = false; @@ -2410,8 +2591,13 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info) } } } else { - LogPrintf("Setting NODE_NETWORK on non-prune mode\n"); - nLocalServices = ServiceFlags(nLocalServices | NODE_NETWORK); + // Prior to setting NODE_NETWORK, check if we can provide historical blocks. + if (!WITH_LOCK(chainman.GetMutex(), return chainman.BackgroundSyncInProgress())) { + LogPrintf("Setting NODE_NETWORK on non-prune mode\n"); + nLocalServices = ServiceFlags(nLocalServices | NODE_NETWORK); + } else { + LogPrintf("Running node in NODE_NETWORK_LIMITED mode until snapshot background sync completes\n"); + } } // As PruneAndFlush can take several minutes, it's possible the user @@ -2516,134 +2702,42 @@ 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(); - } + try { + // 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; } - }; - // 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); + // 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; } - } - - // 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; + // Load mempool from disk + Chainstate* chainstate; + CTxMemPool* pool; { - LOCK(cs_main); - const auto& consensus_params = Params().GetConsensus(); - start_index = chainman.ActiveChain()[consensus_params.DIP0003Height]; - stop_index = chainman.ActiveChain().Tip(); + LOCK(::cs_main); + chainstate = &chainman.ActiveChainstate(); + pool = chainstate->GetMempool(); } - - 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")); - 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)); + if (pool) { + LoadMempool(*pool, ShouldPersistMempool(args) ? MempoolPath(args) : fs::path{}, *chainstate, {}); + // A load stopped because the mempool moved to another chainstate did not finish. + const bool load_stopped{WITH_LOCK(::cs_main, return chainstate->GetMempool() != pool)}; + pool->SetLoadTried(!ShutdownRequested() && !load_stopped); } - } - { - // 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)); - } - - 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); + 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 @@ -2904,18 +2998,19 @@ bool StartIndexBackgroundSync(NodeContext& node) // indexes_start_block='nullptr' means "start from height 0". std::optional indexes_start_block; std::string older_index_name; - ChainstateManager& chainman = *Assert(node.chainman); + const Chainstate& chainstate = WITH_LOCK(::cs_main, return chainman.GetChainstateForIndexing()); + const CChain& index_chain = chainstate.m_chain; + for (auto index : node.indexes) { const IndexSummary& summary = index->GetSummary(); if (summary.synced) continue; // Get the last common block between the index best block and the active chain LOCK(::cs_main); - const CChain& active_chain = chainman.ActiveChain(); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(summary.best_block_hash); - if (!active_chain.Contains(pindex)) { - pindex = active_chain.FindFork(pindex); + if (!index_chain.Contains(pindex)) { + pindex = index_chain.FindFork(pindex); } if (!indexes_start_block || !pindex || pindex->nHeight < indexes_start_block.value()->nHeight) { @@ -2930,12 +3025,14 @@ bool StartIndexBackgroundSync(NodeContext& node) LOCK(::cs_main); const CBlockIndex* start_block = *indexes_start_block; if (!start_block) start_block = chainman.ActiveChain().Genesis(); - if (!chainman.m_blockman.CheckBlockDataAvailability(*chainman.ActiveChain().Tip(), *Assert(start_block))) { + if (!chainman.m_blockman.CheckBlockDataAvailability(*index_chain.Tip(), *Assert(start_block))) { return InitError(strprintf(Untranslated("%s best block of the index goes beyond pruned data. Please disable the index or reindex (which will download the whole blockchain again)"), older_index_name)); } } // Start threads + LOCK(node.index_start_mutex); for (auto index : node.indexes) if (!index->StartBackgroundSync()) return false; + node.index_threads_started = true; return true; } diff --git a/src/init.h b/src/init.h index eace57ae260d..4702dede9564 100644 --- a/src/init.h +++ b/src/init.h @@ -67,6 +67,16 @@ 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. + */ +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); void PrepareShutdown(node::NodeContext& node); /** diff --git a/src/instantsend/instantsend.cpp b/src/instantsend/instantsend.cpp index 09e6a3e4aacf..326c132f5a36 100644 --- a/src/instantsend/instantsend.cpp +++ b/src/instantsend/instantsend.cpp @@ -135,6 +135,12 @@ void CInstantSendManager::AddPendingISLock(const uint256& hash, const instantsen pendingNoTxInstantSendLocks.try_emplace(hash, instantsend::PendingISLockFromPeer{from, islock}); } +void CInstantSendManager::RemovePendingNoTxLock(const uint256& hash) +{ + LOCK(cs_pendingLocks); + pendingNoTxInstantSendLocks.erase(hash); +} + void CInstantSendManager::TransactionIsRemoved(const CTransactionRef& tx) { if (!instantsend::HasLockInputs(*tx)) { diff --git a/src/instantsend/instantsend.h b/src/instantsend/instantsend.h index ca967887f54a..ba8a2e6b76b3 100644 --- a/src/instantsend/instantsend.h +++ b/src/instantsend/instantsend.h @@ -140,6 +140,8 @@ class CInstantSendManager void WriteNewISLock(const uint256& hash, const instantsend::InstantSendLockPtr& islock, std::optional minedHeight); void AddPendingISLock(const uint256& hash, const instantsend::InstantSendLockPtr& islock, NodeId from) EXCLUSIVE_LOCKS_REQUIRED(!cs_pendingLocks); + //! Forget a lock that waits for its transaction. + void RemovePendingNoTxLock(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(!cs_pendingLocks); bool PreVerifyIsLock(const uint256& hash, const instantsend::InstantSendLockPtr& islock, NodeId from) const; diff --git a/src/instantsend/net_instantsend.cpp b/src/instantsend/net_instantsend.cpp index 353cbdde321a..ba5e5ef887b5 100644 --- a/src/instantsend/net_instantsend.cpp +++ b/src/instantsend/net_instantsend.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include #include #include @@ -144,9 +146,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. @@ -429,7 +440,7 @@ void NetInstantSend::ProcessInstantSendLock(NodeId from, const uint256& hash, co // We don't need the recovered sigs for the inputs anymore. This prevents unnecessary propagation of these sigs. // We only need the ISLOCK from now on to detect conflicts TruncateRecoveredSigsForInputs(*islock); - ResolveBlockConflicts(hash, *islock); + if (!ResolveBlockConflicts(hash, *islock)) return; if (found_transaction) { RemoveMempoolConflictsForLock(hash, *islock); @@ -452,8 +463,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 +474,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; @@ -560,8 +572,12 @@ void NetInstantSend::TransactionRemovedFromMempool(const CTransactionRef& tx, Me m_is_manager.TransactionIsRemoved(tx); } -void NetInstantSend::BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) +void NetInstantSend::BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindex) { + // Only the active chainstate's blocks concern this subscriber. + if (role == ChainstateRole::BACKGROUND) { + return; + } if (!m_is_manager.IsInstantSendEnabled()) { return; } @@ -608,9 +624,24 @@ void NetInstantSend::NotifyChainLock(const CBlockIndex* pindex, const std::share HandleFullyConfirmedBlock(pindex); } -void NetInstantSend::ResolveBlockConflicts(const uint256& islockHash, const instantsend::InstantSendLock& islock) +bool NetInstantSend::ResolveBlockConflicts(const uint256& islockHash, const instantsend::InstantSendLock& islock) { auto conflicts = m_is_manager.RetrieveISConflicts(islockHash, islock); + if (conflicts.empty()) return true; + + // Until a snapshot chainstate is validated in the background, it does not + // move away from blocks it cannot fully check: the chain wins and the lock + // is discarded, stored or still waiting for its transaction, so it is + // neither applied, announced, relayed nor served. This holds for a + // ChainLocked conflict too. + if (m_chainman.IsSnapshotActiveAndUnvalidated()) { + LogPrintf("NetInstantSend::%s -- txid=%s, islock=%s: conflicting blocks are kept before snapshot " + "validation completes, discarding the lock\n", + __func__, islock.txid.ToString(), islockHash.ToString()); + m_is_manager.RemoveConflictingLock(islockHash, islock); + m_is_manager.RemovePendingNoTxLock(islockHash); + return false; + } // Lets see if any of the conflicts was already mined into a ChainLocked block bool hasChainLockedConflict = false; @@ -630,9 +661,21 @@ void NetInstantSend::ResolveBlockConflicts(const uint256& islockHash, const inst LogPrintf("NetInstantSend::%s -- txid=%s, islock=%s: at least one conflicted TX already got a ChainLock\n", __func__, islock.txid.ToString(), islockHash.ToString()); m_is_manager.RemoveConflictingLock(islockHash, islock); - return; + return true; } + // A pruned node that cannot undo a block because block data it needs was + // pruned stalls instead of moving away from it: the lock stays, and its + // conflicts are given up on. A node that cannot read a block is shutting + // down. + const auto give_up{[&](const BlockValidationState& state) { + if (IsLocalEvoStateError(state)) return true; + if (m_chainman.m_interrupt) return false; + // This should not have happened and we are in a state were it's not safe to continue anymore + assert(false); + return false; + }}; + bool hasTxForLock = m_is_manager.HasTxForLock(islockHash); bool activateBestChain = false; @@ -645,28 +688,29 @@ void NetInstantSend::ResolveBlockConflicts(const uint256& islockHash, const inst BlockValidationState state; // need non-const pointer auto pindex2 = WITH_LOCK(::cs_main, return m_chainman.ActiveChainstate().m_blockman.LookupBlockIndex(pindex->GetBlockHash())); - if (!m_chainman.ActiveChainstate().InvalidateBlock(state, pindex2)) { - LogPrintf("NetInstantSend::%s -- InvalidateBlock failed: %s\n", __func__, state.ToString()); - // This should not have happened and we are in a state were it's not safe to continue anymore - assert(false); - } - if (hasTxForLock) { - activateBestChain = true; - } else { + const bool invalidated{m_chainman.ActiveChainstate().InvalidateBlock(state, pindex2)}; + if (!hasTxForLock) { + // Without the locked transaction the invalidation is only temporary, + // also when it stopped partway. LogPrintf("NetInstantSend::%s -- resetting block %s\n", __func__, pindex2->GetBlockHash().ToString()); LOCK(::cs_main); m_chainman.ActiveChainstate().ResetBlockFailureFlags(pindex2); } + if (!invalidated) { + LogPrintf("NetInstantSend::%s -- InvalidateBlock failed: %s\n", __func__, state.ToString()); + return give_up(state); + } + if (hasTxForLock) activateBestChain = true; } if (activateBestChain) { BlockValidationState state; if (!m_chainman.ActiveChainstate().ActivateBestChain(state)) { LogPrintf("NetInstantSend::%s -- ActivateBestChain failed: %s\n", __func__, state.ToString()); - // This should not have happened and we are in a state were it's not safe to continue anymore - assert(false); + return give_up(state); } } + return true; } void NetInstantSend::TruncateRecoveredSigsForInputs(const instantsend::InstantSendLock& islock) diff --git a/src/instantsend/net_instantsend.h b/src/instantsend/net_instantsend.h index 0f26fe98643f..986835db1c3f 100644 --- a/src/instantsend/net_instantsend.h +++ b/src/instantsend/net_instantsend.h @@ -74,7 +74,7 @@ class NetInstantSend final : public NetHandler, public CValidationInterface void TransactionAddedToMempool(const CTransactionRef&, int64_t, uint64_t mempool_sequence) override; void TransactionRemovedFromMempool(const CTransactionRef& ptx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override; - void BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) override; + void BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindex) override; void BlockDisconnected(const std::shared_ptr& pblock, const CBlockIndex* pindexDisconnected) override; void NotifyChainLock(const CBlockIndex* pindex, const std::shared_ptr& clsig) override; @@ -101,7 +101,9 @@ class NetInstantSend final : public NetHandler, public CValidationInterface const Consensus::LLMQParams& llmq_params, int signOffset, bool ban, const std::vector& pend); - void ResolveBlockConflicts(const uint256& islockHash, const instantsend::InstantSendLock& islock); + //! Returns false if the caller must not go on with the lock: it was + //! discarded, or the node is shutting down. + [[nodiscard]] bool ResolveBlockConflicts(const uint256& islockHash, const instantsend::InstantSendLock& islock); void TruncateRecoveredSigsForInputs(const instantsend::InstantSendLock& islock); diff --git a/src/interfaces/chain.h b/src/interfaces/chain.h index 16aa05365946..7e7199ddf6dc 100644 --- a/src/interfaces/chain.h +++ b/src/interfaces/chain.h @@ -30,6 +30,7 @@ class CBlockIndex; class Coin; class uint256; enum class MemPoolRemovalReason; +enum class ChainstateRole; struct bilingual_str; struct CBlockLocator; struct FeeCalculation; @@ -193,8 +194,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 +295,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; @@ -326,10 +330,10 @@ class Chain virtual ~Notifications() {} virtual void transactionAddedToMempool(const CTransactionRef& tx, int64_t nAcceptTime) {} virtual void transactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason) {} - virtual void blockConnected(const BlockInfo& block) {} + virtual void blockConnected(ChainstateRole role, const BlockInfo& block) {} virtual void blockDisconnected(const BlockInfo& block) {} virtual void updatedBlockTip() {} - virtual void chainStateFlushed(const CBlockLocator& locator) {} + virtual void chainStateFlushed(ChainstateRole role, const CBlockLocator& locator) {} virtual void notifyChainLock(const CBlockIndex* pindexChainLock, const std::shared_ptr& clsig) {} virtual void notifyTransactionLock(const CTransactionRef &tx, const std::shared_ptr& islock) {} }; diff --git a/src/interfaces/node.h b/src/interfaces/node.h index 7cece18be3bc..b4bdcbf350e5 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 apply to the next block; 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/kernel/CMakeLists.txt b/src/kernel/CMakeLists.txt index 891bc08842b5..d6d76267c4f0 100644 --- a/src/kernel/CMakeLists.txt +++ b/src/kernel/CMakeLists.txt @@ -44,6 +44,8 @@ add_library(bitcoinkernel STATIC EXCLUDE_FROM_ALL ../evo/providertx_util.cpp ../evo/simplifiedmns.cpp ../evo/smldiff.cpp + ../evo/snapshot.cpp + ../evo/snapshot_chain.cpp ../evo/specialtx.cpp ../evo/specialtx_filter.cpp ../evo/specialtxman.cpp diff --git a/src/kernel/chain.cpp b/src/kernel/chain.cpp index 1c877866d0a2..318c956b386d 100644 --- a/src/kernel/chain.cpp +++ b/src/kernel/chain.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -25,3 +26,13 @@ interfaces::BlockInfo MakeBlockInfo(const CBlockIndex* index, const CBlock* data return info; } } // namespace kernel + +std::ostream& operator<<(std::ostream& os, const ChainstateRole& role) { + switch(role) { + case ChainstateRole::NORMAL: os << "normal"; break; + case ChainstateRole::ASSUMEDVALID: os << "assumedvalid"; break; + case ChainstateRole::BACKGROUND: os << "background"; break; + default: os.setstate(std::ios_base::failbit); + } + return os; +} diff --git a/src/kernel/chain.h b/src/kernel/chain.h index f0750f82663f..feba24a557e6 100644 --- a/src/kernel/chain.h +++ b/src/kernel/chain.h @@ -5,6 +5,8 @@ #ifndef BITCOIN_KERNEL_CHAIN_H #define BITCOIN_KERNEL_CHAIN_H +#include + class CBlock; class CBlockIndex; namespace interfaces { @@ -14,6 +16,24 @@ struct BlockInfo; namespace kernel { //! Return data from block index. interfaces::BlockInfo MakeBlockInfo(const CBlockIndex* block_index, const CBlock* data = nullptr); + } // namespace kernel +//! This enum describes the various roles a specific Chainstate instance can take. +//! Other parts of the system sometimes need to vary in behavior depending on the +//! existence of a background validation chainstate, e.g. when building indexes. +enum class ChainstateRole { + // Single chainstate in use, "normal" IBD mode. + NORMAL, + + // Doing IBD-style validation in the background. Implies use of an assumed-valid + // chainstate. + BACKGROUND, + + // Active assumed-valid chainstate. Implies use of a background IBD chainstate. + ASSUMEDVALID, +}; + +std::ostream& operator<<(std::ostream& os, const ChainstateRole& role); + #endif // BITCOIN_KERNEL_CHAIN_H diff --git a/src/kernel/chainparams.cpp b/src/kernel/chainparams.cpp index 80a9f6f6fe90..b6a622532078 100644 --- a/src/kernel/chainparams.cpp +++ b/src/kernel/chainparams.cpp @@ -361,8 +361,14 @@ class CMainParams : public CChainParams { } }; - m_assumeutxo_data = MapAssumeutxo{ - // TODO to be specified in a future patch. + m_assumeutxo_data = { + { + .height = 2579482, + .hash_serialized = AssumeutxoHash{uint256S("0x9f04690bf3ef7a4917eace719ac558cd6896a8bd22e905a74f19d76ce83d5811")}, + .evo_hash = EvoSnapshotHash{uint256S("0x5fe390df978e8e5ac259e02a0b0690a6e3a757f45177025cf5f4d864e59ebc6e")}, + .nChainTx = 71739012, + .blockhash = uint256S("0x000000000000001cfbe4751211d7e753bab093e5d63de1fa947cf20714a0e727"), + }, }; // getchaintxstats 17280 000000000000000346a1804da4832b0b69dd9a7f96b14c7cb54585a9ac6ae98f @@ -546,8 +552,14 @@ class CTestNetParams : public CChainParams { } }; - m_assumeutxo_data = MapAssumeutxo{ - // TODO to be specified in a future patch. + m_assumeutxo_data = { + { + .height = 1599687, + .hash_serialized = AssumeutxoHash{uint256S("0x4ba6fb243e38624fac1f2f434027b381c3cdf900f3da981e996d113be148d772")}, + .evo_hash = EvoSnapshotHash{uint256S("0x574ddf5486e18f81998b2a49a37b7ba9562ac4e134d14a7225bdd04b0c1b4afd")}, + .nChainTx = 9019675, + .blockhash = uint256S("0x0000006e4b85a1f38f3224ead2865de8e7f29d98229b58b00a1b1bedab624872"), + }, }; // getchaintxstats 17280 000000116cd3c11d44c88cbc0a26804bd277a5d790f684ec3a8aaa820690318c @@ -980,16 +992,31 @@ class CRegTestParams : public CChainParams { } }; - m_assumeutxo_data = MapAssumeutxo{ + m_assumeutxo_data = { { - 110, - {AssumeutxoHash{uint256S("0xffb210087e1ed14526c0c08a3ec3a7c8e288079eaa68acb87d3d4d9fd746079f")}, EvoSnapshotHash{uint256{}}, 110}, + .height = 110, + .hash_serialized = AssumeutxoHash{uint256S("0xffb210087e1ed14526c0c08a3ec3a7c8e288079eaa68acb87d3d4d9fd746079f")}, + .evo_hash = EvoSnapshotHash{uint256{}}, + .nChainTx = 111, + .blockhash = uint256S("0x729bcb1479ff9f4968439f0276bd76bcb2de0f0720b7a16f383321f6a41cb238"), }, { - 200, - {AssumeutxoHash{uint256S("0x16e00a64db4fa48dd989dce86d8677f41797d52044e5fc86021aa88cc22b665b")}, EvoSnapshotHash{uint256{}}, 200}, + .height = 200, + .hash_serialized = AssumeutxoHash{uint256S("0x16e00a64db4fa48dd989dce86d8677f41797d52044e5fc86021aa88cc22b665b")}, + .evo_hash = EvoSnapshotHash{uint256{}}, + .nChainTx = 201, + .blockhash = uint256S("0x19c1b203b5a960c7f3619e0e805b24c94e684b1aa261f3a79c84d291638a6e1f"), }, }; + for (const auto& data : opts.assumeutxo_data) { + if (std::ranges::any_of(m_assumeutxo_data, [&](const auto& entry) { + return entry.height == data.height || entry.blockhash == data.blockhash; + })) { + throw std::runtime_error(strprintf("Duplicate height or block hash in -assumeutxodata (%d:%s)", + data.height, data.blockhash.ToString())); + } + m_assumeutxo_data.push_back(data); + } chainTxData = ChainTxData{ 0, diff --git a/src/kernel/chainparams.h b/src/kernel/chainparams.h index 68b46ada1ddd..199489231d6f 100644 --- a/src/kernel/chainparams.h +++ b/src/kernel/chainparams.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -48,20 +49,24 @@ struct EvoSnapshotHash : public BaseHash { * as valid. */ struct AssumeutxoData { + int height; + //! The expected hash of the deserialized UTXO set. - const AssumeutxoHash hash_serialized; + AssumeutxoHash hash_serialized; //! The expected single-SHA256 hash of the canonical Dash evo section. - const EvoSnapshotHash evo_hash; + EvoSnapshotHash evo_hash; //! Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex(). //! //! We need to hardcode the value here because this is computed cumulatively using block data, //! which we do not necessarily have at the time of snapshot load. - const unsigned int nChainTx; -}; + unsigned int nChainTx; -using MapAssumeutxo = std::map; + //! The hash of the base block for this snapshot. Used to refer to assumeutxo data + //! prior to having a loaded blockindex. + uint256 blockhash; +}; /** * Holds various statistics on transactions within a chain. Used to estimate @@ -136,7 +141,16 @@ class CChainParams //! Get allowed assumeutxo configuration. //! @see ChainstateManager - const MapAssumeutxo& Assumeutxo() const { return m_assumeutxo_data; } + const std::vector& Assumeutxo() const { return m_assumeutxo_data; } + + std::optional AssumeutxoForHeight(int height) const + { + return FindFirst(m_assumeutxo_data, [&](const auto& d) { return d.height == height; }); + } + std::optional AssumeutxoForBlockhash(const uint256& blockhash) const + { + return FindFirst(m_assumeutxo_data, [&](const auto& d) { return d.blockhash == blockhash; }); + } const ChainTxData& TxData() const { return chainTxData; } void UpdateDIP3Parameters(int nActivationHeight, int nEnforcementHeight); @@ -233,6 +247,8 @@ class CChainParams std::unordered_map llmq_test_parameters{}; //! Name of the LLMQ to use for InstantSend (DIP0024) std::optional llmq_dip0024_instantsend{}; + //! Extra exact snapshot authorizations + std::vector assumeutxo_data{}; }; static std::unique_ptr RegTest(const RegTestOptions& options); @@ -268,7 +284,7 @@ class CChainParams bool m_is_mockable_chain; int nLLMQConnectionRetryTimeout; CCheckpointData checkpointData; - MapAssumeutxo m_assumeutxo_data; + std::vector m_assumeutxo_data; ChainTxData chainTxData; int nPoolMinParticipants; int nPoolMaxParticipants; diff --git a/src/kernel/chainstatemanager_opts.h b/src/kernel/chainstatemanager_opts.h index 4b999455ca29..968dac89d7d6 100644 --- a/src/kernel/chainstatemanager_opts.h +++ b/src/kernel/chainstatemanager_opts.h @@ -55,6 +55,12 @@ struct ChainstateManagerOpts { Notifications& notifications; //! Number of script check worker threads. Zero means no parallel verification. int worker_threads_num{0}; + //! Dash: the node runs as a masternode. It does not load UTXO snapshots. + bool masternode{false}; + //! Dash: the node keeps the -addressindex, -spentindex or -timestampindex + //! index, which is not supported with a snapshot chainstate. It does not + //! load UTXO snapshots. + bool legacy_indexes{false}; }; } // namespace kernel diff --git a/src/kernel/coinstats.cpp b/src/kernel/coinstats.cpp index 924d84983026..f2205183fd04 100644 --- a/src/kernel/coinstats.cpp +++ b/src/kernel/coinstats.cpp @@ -139,6 +139,10 @@ static bool ComputeUTXOStats(CCoinsView* view, CCoinsStats& stats, T hash_obj, c } pcursor->Next(); } + if (pcursor->HasError()) { + LogError("%s: unable to read the coins database\n", __func__); + return false; + } if (!outputs.empty()) { ApplyStats(stats, prevkey, outputs); ApplyHash(hash_obj, prevkey, outputs); diff --git a/src/kernel/notifications_interface.h b/src/kernel/notifications_interface.h index 6bd046731de6..c6e326460467 100644 --- a/src/kernel/notifications_interface.h +++ b/src/kernel/notifications_interface.h @@ -43,6 +43,7 @@ class Notifications virtual void progress(const bilingual_str& title, int progress_percent, bool resume_possible) {} virtual void warning(const bilingual_str& warning) {} virtual void masternodeListChanged(const CDeterministicMNList& list, const CBlockIndex* index) {} + virtual void evoStateWarningChanged() {} //! The flush error notification is sent to notify the user that an error //! occurred while flushing block data to disk. Kernel code may ignore flush diff --git a/src/llmq/blockprocessor.cpp b/src/llmq/blockprocessor.cpp index b6917a17cd1d..14d66ca78955 100644 --- a/src/llmq/blockprocessor.cpp +++ b/src/llmq/blockprocessor.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -49,6 +50,9 @@ static const std::string DB_MINED_COMMITMENT = "q_mc"; static const std::string DB_MINED_COMMITMENT_BY_INVERSED_HEIGHT = "q_mcih"; static const std::string DB_MINED_COMMITMENT_BY_INVERSED_HEIGHT_Q_INDEXED = "q_mcihi"; +// Written only into a snapshot generation. +static const std::string DB_SCAN_COVERAGE = "q_scov"; + bool EraseMinedCommitmentIfUnreferenced(CEvoDB& evo_db, const Chainstate& chainstate, gsl::not_null pindex, Consensus::LLMQType llmq_type, const uint256& quorum_hash) @@ -78,15 +82,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); } @@ -212,6 +222,10 @@ bool CQuorumBlockProcessor::ProcessBlock(Chainstate& chainstate, const CBlock& b { AssertLockHeld(::cs_main); + if (!chainstate.HoldsEvoTransaction()) { + throw EvoViewBindingError(strprintf("%s: outside the Evo transaction of %s", __func__, chainstate.ToString())); + } + const auto blockHash = pindex->GetBlockHash(); if (!DeploymentActiveAt(*pindex, m_chainman.GetConsensus(), Consensus::DEPLOYMENT_DIP0003)) { @@ -455,7 +469,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 +483,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 +529,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,20 +538,25 @@ 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) { AssertLockHeld(::cs_main); + if (!chainstate.HoldsEvoTransaction()) { + throw EvoViewBindingError(strprintf("%s: outside the chainstate's Evo transaction", __func__)); + } PreComputeQuorumMembers(m_dmnman, m_qsnapman, m_chainman, pindex, /*reset_cache=*/true); { 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 +588,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 +714,73 @@ 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; +} + +ScanSequenceEnd CQuorumBlockProcessor::SequenceEnd(Consensus::LLMQType llmqType, bool indexed, size_t sequence) const +{ + AssertLockNotHeld(m_evoDb.cs); + // A full view, or a snapshot view of a base no quorum can precede, holds + // every commitment mined on its chain. + if (!LacksQuorumHistory(m_evoDb.CurrentView(), m_chainman.GetConsensus())) return ScanSequenceEnd::END; + const auto llmq_params{m_chainman.GetParams().GetLLMQ(llmqType)}; + if (!llmq_params) return ScanSequenceEnd::UNKNOWN; + // A family the type never writes is empty: a type is indexed exactly when + // it rotates, and a rotating type is enabled exactly when rotation is + // (both follow DIP0024 at the cycle base). + if (llmq_params->useRotation != indexed) return ScanSequenceEnd::END; + const auto coverage{GetScanCoverage(llmqType)}; + return coverage ? coverage->End(sequence) : ScanSequenceEnd::UNKNOWN; +} + +bool CQuorumBlockProcessor::ShortScanIsComplete(Consensus::LLMQType llmqType, bool indexed, size_t sequence, + const CBlockIndex* pindex) const +{ + const auto& consensus{m_chainman.GetConsensus()}; + // A scan from below DIP3, or from genesis, is complete: no commitment can + // be mined there. + const int first_minable_height{std::max(1, consensus.DIP0003Height)}; + if (pindex->nHeight < first_minable_height) return true; + // The missing history holds a commitment of `llmqType` only if one may + // have been mined at a height up to both `pindex` and the base. 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. Callers release the EvoDB lock first: + // deployment state may read EvoDB. + if (const EvoViewToken view{m_evoDb.CurrentView()}; LacksQuorumHistory(view, consensus)) { + const int last_missing_height{std::min(pindex->nHeight, view.base_height)}; + if (last_missing_height < first_minable_height) return true; + const CBlockIndex* last_missing{pindex->GetAncestor(last_missing_height)}; + if (!m_chainman.IsQuorumTypeEnabled(llmqType, last_missing->pprev) && + !m_chainman.IsQuorumTypeEnabled(llmqType, pindex->GetAncestor(first_minable_height)->pprev)) { + return true; + } + } + // A scan running out where its sequence ends has found everything mined; + // anywhere else it would need history the view lacks, so its result is + // unknown, not short. + return SequenceEnd(llmqType, indexed, sequence) == ScanSequenceEnd::END; +} + +void CQuorumBlockProcessor::RequireSatisfiedScan(Consensus::LLMQType llmqType, bool indexed, size_t sequence, + const CBlockIndex* pindex, const char* func) const +{ + if (ShortScanIsComplete(llmqType, indexed, sequence, pindex)) 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 +790,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 +801,18 @@ 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())) { + // The snapshot view holds every commitment for a quorum above its + // base, but of the history at or below it only the newest: a miss + // there means "never mined" only where that can be proven. + const CBlockIndex* quorum_base{m_chainman.m_blockman.LookupBlockIndex(quorumHash)}; + if (quorum_base != nullptr && view.AtOrBelowSnapshotBase(quorum_base->nHeight) && + !ProvenNeverMined(llmqType, quorum_base, view)) { + throw BlockDataUnavailableError( + strprintf("%s: commitment for quorum %s at or below the snapshot base is not available", __func__, + quorumHash.ToString())); + } } } @@ -719,6 +820,84 @@ bool CQuorumBlockProcessor::HasMinedCommitment(Consensus::LLMQType llmqType, con return mined_block != nullptr && chain.Contains(mined_block); } +bool CQuorumBlockProcessor::ProvenNeverMined(Consensus::LLMQType llmqType, gsl::not_null quorum_index, + const EvoViewToken& view) const +{ + AssertLockHeld(::cs_main); + const auto llmq_params_opt{m_chainman.GetParams().GetLLMQ(llmqType)}; + if (!llmq_params_opt) return true; + const auto& llmq_params{*llmq_params_opt}; + // Only this view's chain can have mined it, only at a quorum height of an + // enabled type. + const CBlockIndex* base{m_chainman.m_blockman.LookupBlockIndex(view.base)}; + if (base == nullptr) return false; + if (base->GetAncestor(quorum_index->nHeight) != quorum_index) return true; + const int offset{quorum_index->nHeight % llmq_params.dkgInterval}; + const bool rotation{IsQuorumRotationEnabled(llmq_params, quorum_index)}; + if (offset >= (rotation ? llmq_params.signingActiveQuorumCount : 1) || + !m_chainman.IsQuorumTypeEnabled(llmqType, quorum_index->pprev)) { + return true; + } + // The carried commitments are the newest of their sequence, so a quorum no + // older than the oldest of them would be among them, and a sequence that + // ends proves there is nothing older either. A family the scans do not + // read is not carried at all. + if (rotation != llmq_params.useRotation) return false; + const size_t sequence{rotation ? static_cast(offset) : 0}; + if (SequenceEnd(llmqType, rotation, sequence) == ScanSequenceEnd::END) return true; + const auto carried{rotation ? GetMinedCommitmentsByQuorumIndexUntilBlock(llmqType, base, offset, 2) + : GetMinedCommitmentsUntilBlock(llmqType, base, + std::max(llmq_params.signingActiveQuorumCount + 1, + llmq_params.keepOldConnections))}; + return !carried.empty() && quorum_index->nHeight >= carried.back()->nHeight; +} + +bool CQuorumBlockProcessor::SeedMinedCommitment(const EvoViewToken& view, Consensus::LLMQType llmqType, + const uint256& quorum_hash, const CFinalCommitment& commitment, + const uint256& mined_block_hash) +{ + AssertLockHeld(::cs_main); + if (!Assume(m_evoDb.HasActiveTransaction())) return false; + m_evoDb.RequireTransactionView(view); + const auto llmq_params{m_chainman.GetParams().GetLLMQ(llmqType)}; + const CBlockIndex* mined_index{m_chainman.m_blockman.LookupBlockIndex(mined_block_hash)}; + const CBlockIndex* quorum_base_index{m_chainman.m_blockman.LookupBlockIndex(quorum_hash)}; + if (!llmq_params || mined_index == nullptr || quorum_base_index == nullptr) return false; + if (!m_evoDb.WriteSeed(std::make_pair(DB_MINED_COMMITMENT, std::make_pair(llmqType, quorum_hash)), + std::make_pair(commitment, mined_block_hash))) { + return false; + } + // Replay ProcessCommitment's height index exactly: it drives the scans and + // the first post-base CbTx quorum merkle root. + const bool indexed{ + IsQuorumRotationEnabled(*llmq_params, quorum_base_index) + ? m_evoDb.WriteSeed(BuildInversedHeightKeyIndexed(llmqType, mined_index->nHeight, int{commitment.quorumIndex}), + quorum_base_index->nHeight) + : m_evoDb.WriteSeed(BuildInversedHeightKey(llmqType, mined_index->nHeight), quorum_base_index->nHeight)}; + if (!indexed) return false; + DropQcHashesCache(llmqType, quorum_hash); + WITH_LOCK(minableCommitmentsCs, mapMinedCommitmentBlockCache.For(view).erase(llmqType, quorum_hash)); + return true; +} + +bool CQuorumBlockProcessor::SeedScanCoverage(const EvoViewToken& view, Consensus::LLMQType llmqType, + const ScanCoverageRecord& coverage) +{ + if (!Assume(m_evoDb.HasActiveTransaction())) return false; + m_evoDb.RequireTransactionView(view); + return m_evoDb.WriteSeed(std::make_pair(DB_SCAN_COVERAGE, llmqType), coverage); +} + +std::optional CQuorumBlockProcessor::GetScanCoverage(Consensus::LLMQType llmqType) const +{ + ScanCoverageRecord coverage; + if (!m_evoDb.Read(std::make_pair(DB_SCAN_COVERAGE, llmqType), coverage) || + coverage.schema_version != ScanCoverageRecord::SCHEMA_VERSION) { + return std::nullopt; + } + return coverage; +} + std::pair CQuorumBlockProcessor::GetMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash) const { @@ -731,10 +910,11 @@ std::pair CQuorumBlockProcessor::GetMinedCommitment(C } // The returned quorums are in reversed order, so the most recent one is at index 0 -std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilBlock(Consensus::LLMQType llmqType, gsl::not_null pindex, size_t maxCount) const +std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilBlock( + Consensus::LLMQType llmqType, gsl::not_null pindex, size_t maxCount, bool* unreadable) const { AssertLockNotHeld(m_evoDb.cs); - LOCK(m_evoDb.cs); + WAIT_LOCK(m_evoDb.cs, evodb_lock); auto dbIt = m_evoDb.GetCurTransaction().NewIteratorUniquePtr(); @@ -746,6 +926,7 @@ std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilB std::vector ret; ret.reserve(maxCount); + bool read_failed{false}; while (dbIt->Valid() && ret.size() < maxCount) { decltype(firstKey) curKey; int quorumHeight; @@ -762,6 +943,7 @@ std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilB } if (!dbIt->GetValue(quorumHeight)) { + read_failed = true; break; } @@ -772,15 +954,36 @@ std::vector CQuorumBlockProcessor::GetMinedCommitmentsUntilB dbIt->Next(); } + if (unreadable && (read_failed || dbIt->HasError())) { + *unreadable = true; + return ret; + } + if (ret.size() < maxCount) { + dbIt.reset(); + REVERSE_LOCK(evodb_lock); + RequireSatisfiedScan(llmqType, /*indexed=*/false, /*sequence=*/0, pindex, __func__); + } return ret; } -std::optional CQuorumBlockProcessor::GetLastMinedCommitmentsByQuorumIndexUntilBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex, int quorumIndex, size_t cycle) const +std::optional CQuorumBlockProcessor::GetLastMinedCommitmentsByQuorumIndexUntilBlock( + Consensus::LLMQType llmqType, const CBlockIndex* pindex, int quorumIndex, size_t cycle, bool* unreadable) const { AssertLockNotHeld(m_evoDb.cs); - LOCK(m_evoDb.cs); + WAIT_LOCK(m_evoDb.cs, evodb_lock); auto dbIt = m_evoDb.GetCurTransaction().NewIteratorUniquePtr(); + const auto not_found{[&](bool read_failed = false) -> std::optional { + if (unreadable && (read_failed || dbIt->HasError())) { + *unreadable = true; + return std::nullopt; + } + dbIt.reset(); + REVERSE_LOCK(evodb_lock); + RequireSatisfiedScan(llmqType, /*indexed=*/true, static_cast(quorumIndex), pindex, + "GetLastMinedCommitmentsByQuorumIndexUntilBlock"); + return std::nullopt; + }}; auto firstKey = BuildInversedHeightKeyIndexed(llmqType, pindex->nHeight, quorumIndex); auto lastKey = BuildInversedHeightKeyIndexed(llmqType, 0, quorumIndex); @@ -793,25 +996,26 @@ 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(/*read_failed=*/true); } const auto* pQuorumBaseBlockIndex = pindex->GetAncestor(quorumHeight); assert(pQuorumBaseBlockIndex); if (currentCycle == cycle) { + if (unreadable && dbIt->HasError()) *unreadable = true; return std::make_optional(pQuorumBaseBlockIndex); } @@ -820,18 +1024,54 @@ std::optional CQuorumBlockProcessor::GetLastMinedCommitments dbIt->Next(); } - return std::nullopt; + return not_found(); +} + +std::vector CQuorumBlockProcessor::GetMinedCommitmentsByQuorumIndexUntilBlock( + Consensus::LLMQType llmqType, const CBlockIndex* pindex, int quorumIndex, size_t maxCount, bool* unreadable) const +{ + AssertLockNotHeld(m_evoDb.cs); + LOCK(m_evoDb.cs); + + auto dbIt = m_evoDb.GetCurTransaction().NewIteratorUniquePtr(); + auto firstKey = BuildInversedHeightKeyIndexed(llmqType, pindex->nHeight, quorumIndex); + auto lastKey = BuildInversedHeightKeyIndexed(llmqType, 0, quorumIndex); + dbIt->Seek(firstKey); + + std::vector ret; + while (dbIt->Valid() && ret.size() < maxCount) { + decltype(firstKey) curKey; + int quorumHeight; + if (!dbIt->GetKey(curKey) || curKey >= lastKey || + std::get<0>(curKey) != DB_MINED_COMMITMENT_BY_INVERSED_HEIGHT_Q_INDEXED || + std::get<1>(curKey) != llmqType || std::get<2>(curKey) != quorumIndex) { + break; + } + if (std::numeric_limits::max() - be32toh_internal(std::get<3>(curKey)) > + static_cast(pindex->nHeight)) { + break; + } + if (!dbIt->GetValue(quorumHeight)) { + if (unreadable) *unreadable = true; + break; + } + ret.emplace_back(Assert(pindex->GetAncestor(quorumHeight))); + dbIt->Next(); + } + if (unreadable && dbIt->HasError()) *unreadable = true; + return ret; } std::vector CQuorumBlockProcessor::GetLastMinedCommitmentsPerQuorumIndexUntilBlock( - Consensus::LLMQType llmqType, const CBlockIndex* pindex, size_t cycle) const + Consensus::LLMQType llmqType, const CBlockIndex* pindex, size_t cycle, bool* unreadable) const { const auto& llmq_params_opt = m_chainman.GetParams().GetLLMQ(llmqType); assert(llmq_params_opt.has_value()); std::vector ret; for (const auto quorumIndex : util::irange(llmq_params_opt->signingActiveQuorumCount)) { - std::optional q = GetLastMinedCommitmentsByQuorumIndexUntilBlock(llmqType, pindex, quorumIndex, cycle); + std::optional q = GetLastMinedCommitmentsByQuorumIndexUntilBlock(llmqType, pindex, quorumIndex, + cycle, unreadable); if (q.has_value()) { ret.emplace_back(q.value()); } @@ -979,11 +1219,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 +1234,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,21 +1285,55 @@ 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); + 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); +} + +std::optional> TraverseScanSequences(bool indexed, + const std::vector& sequences, + size_t count) +{ + std::vector ret; + if (!indexed) { + if (sequences.empty()) return ret; + const auto& sequence{sequences.front()}; + if (sequence.records.size() >= count) + return std::vector{sequence.records.begin(), sequence.records.begin() + count}; + if (sequence.end == ScanSequenceEnd::UNKNOWN) return std::nullopt; + return sequence.records; + } + // GetMinedCommitmentsIndexedUntilBlock: rank by rank, each quorum index in + // ascending order, skipping exhausted indexes, until `count` or a rank at + // which every index is exhausted. + for (size_t rank{0}; ret.size() < count; ++rank) { + bool any{false}; + for (const auto& sequence : sequences) { + if (rank < sequence.records.size()) { + any = true; + ret.push_back(sequence.records[rank]); + if (ret.size() == count) return ret; + } else if (sequence.end == ScanSequenceEnd::UNKNOWN) { + return std::nullopt; + } } - m_active_quorums_block = pindex->GetBlockHash(); + if (!any) break; } - return ToQuorumBases(m_active_quorums); + return ret; } - bool CQuorumBlockProcessor::HasMineableCommitment(const uint256& hash) const { LOCK(minableCommitmentsCs); diff --git a/src/llmq/blockprocessor.h b/src/llmq/blockprocessor.h index b68768e84dbf..664ebd870652 100644 --- a/src/llmq/blockprocessor.h +++ b/src/llmq/blockprocessor.h @@ -7,6 +7,7 @@ #include #include +#include #include // IWYU pragma: export #include #include @@ -54,6 +55,51 @@ struct SigningRecord { }; using SigningRecords = Uint256HashMap>; +/** How a scan sequence of mined commitments, as a snapshot generation holds + * it, continues past its oldest record. */ +enum class ScanSequenceEnd : uint8_t { + //! No older record exists. + END = 0, + //! Older records may exist; this node does not have them. + UNKNOWN = 1, +}; + +/** One sequence a commitment scan reads: the whole history of a type without + * rotation, or of one quorum index with it. */ +struct ScanSequence { + //! Quorum base blocks of the eligible records, newest mined first. + std::vector records; + ScanSequenceEnd end{ScanSequenceEnd::END}; +}; + +/** The quorum base blocks a scan of `count` returns from `sequences`, in the + * order the ordinary scan returns them: newest first without rotation, rank + * by rank in ascending quorum index with it. nullopt when an UNKNOWN end is + * reached before the prefix is complete, so the vector cannot be proven. */ +std::optional> TraverseScanSequences(bool indexed, + const std::vector& sequences, + size_t count); + +/** Local record of how each scan sequence of a type ends in a snapshot + * generation. Never part of the snapshot wire format. */ +struct ScanCoverageRecord { + static constexpr uint16_t SCHEMA_VERSION{1}; + uint16_t schema_version{SCHEMA_VERSION}; + //! ScanSequenceEnd of each sequence: one per quorum index with rotation, + //! one otherwise. + std::vector ends; + + //! An unrecorded or unknown value never proves an end. + ScanSequenceEnd End(size_t sequence) const + { + return sequence < ends.size() && ends[sequence] == static_cast(ScanSequenceEnd::END) + ? ScanSequenceEnd::END + : ScanSequenceEnd::UNKNOWN; + } + + SERIALIZE_METHODS(ScanCoverageRecord, obj) { READWRITE(obj.schema_version, obj.ends); } +}; + /** Erase a mined commitment unless another chainstate still contains its block. */ bool EraseMinedCommitmentIfUnreferenced(CEvoDB& evo_db, const Chainstate& chainstate, gsl::not_null pindex, @@ -76,7 +122,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 +131,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 +170,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; @@ -173,6 +223,21 @@ class CQuorumBlockProcessor bool HasMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash, const CChain& chain) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !minableCommitmentsCs); std::pair GetMinedCommitment(Consensus::LLMQType llmqType, const uint256& quorumHash) const; + /** Seed how the scan sequences of a type end in `view`, inside the + * caller's open EvoDB transaction for that view. */ + bool SeedScanCoverage(const EvoViewToken& view, Consensus::LLMQType llmqType, const ScanCoverageRecord& coverage); + //! The scan coverage seeded in the calling operation's view, if any. + std::optional GetScanCoverage(Consensus::LLMQType llmqType) const; + //! How the current view's history of one scan sequence (a quorum index of + //! the `indexed` family, or the non-indexed one) ends: END where it holds + //! every commitment mined on its chain, UNKNOWN where older ones may exist + //! that it lacks. + ScanSequenceEnd SequenceEnd(Consensus::LLMQType llmqType, bool indexed, size_t sequence) const; + /** Seed a mined commitment and its height index into `view`, inside the + * caller's open EvoDB transaction for that view. */ + bool SeedMinedCommitment(const EvoViewToken& view, Consensus::LLMQType llmqType, const uint256& quorum_hash, + const CFinalCommitment& commitment, const uint256& mined_block_hash) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !minableCommitmentsCs, !m_qc_hashes_cache_mutex); /** * Serialized hashes of the commitments mined for the quorums active as of pindexPrev. @@ -183,15 +248,29 @@ class CQuorumBlockProcessor std::optional> GetQcHashes(const CBlockIndex* pindexPrev) const EXCLUSIVE_LOCKS_REQUIRED(!m_qc_hashes_cache_mutex); - std::vector GetMinedCommitmentsUntilBlock(Consensus::LLMQType llmqType, gsl::not_null pindex, size_t maxCount) const; - std::map> GetMinedAndActiveCommitmentsUntilBlock( - gsl::not_null pindex) const; + //! The walks below that take `unreadable` set it, and then return an + //! incomplete result, when they stop at an index entry they cannot read or + //! on an iterator read error instead of at the end of their range. + std::vector GetMinedCommitmentsUntilBlock(Consensus::LLMQType llmqType, + gsl::not_null pindex, + size_t maxCount, bool* unreadable = nullptr) const; + std::map> GetMinedAndActiveCommitmentsUntilBlock(gsl::not_null pindex) const; std::vector GetMinedCommitmentsIndexedUntilBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex, size_t maxCount) const; std::vector GetLastMinedCommitmentsPerQuorumIndexUntilBlock(Consensus::LLMQType llmqType, - const CBlockIndex* pindex, - size_t cycle) const; - std::optional GetLastMinedCommitmentsByQuorumIndexUntilBlock(Consensus::LLMQType llmqType, const CBlockIndex* pindex, int quorumIndex, size_t cycle) const; + const CBlockIndex* pindex, size_t cycle, + bool* unreadable = nullptr) const; + std::optional GetLastMinedCommitmentsByQuorumIndexUntilBlock(Consensus::LLMQType llmqType, + const CBlockIndex* pindex, + int quorumIndex, size_t cycle, + bool* unreadable = nullptr) const; + + //! The up to `maxCount` most recent commitments of one quorum index mined + //! at or below `pindex`, newest first. + std::vector GetMinedCommitmentsByQuorumIndexUntilBlock(Consensus::LLMQType llmqType, + const CBlockIndex* pindex, + int quorumIndex, size_t maxCount, + bool* unreadable = nullptr) const; /** * Signing records of every masternode that was a valid member of a non-null commitment mined until pindex @@ -212,11 +291,27 @@ 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); + //! Whether headers and the carried sequences of the snapshot view `view` + //! prove that the quorum at `quorum_index`, at or below its base, was + //! never mined. + bool ProvenNeverMined(Consensus::LLMQType llmqType, gsl::not_null quorum_index, + const EvoViewToken& view) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + //! Whether a scan of one sequence of `llmqType` from `pindex` that came up + //! short in the current view read everything mined: it started below DIP3, + //! or SequenceEnd() says the sequence ends there. + bool ShortScanIsComplete(Consensus::LLMQType llmqType, bool indexed, size_t sequence, + const CBlockIndex* pindex) const; + //! Raise BlockDataUnavailableError for a short scan unless + //! ShortScanIsComplete(). + void RequireSatisfiedScan(Consensus::LLMQType llmqType, bool indexed, size_t sequence, const CBlockIndex* pindex, + const char* func) const; bool GetCommitmentsFromBlock(const CBlock& block, gsl::not_null pindex, std::multimap& ret, BlockValidationState& state) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !m_commitment_payload_mutex); 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..82dfb9b738c4 100644 --- a/src/llmq/net_quorum.cpp +++ b/src/llmq/net_quorum.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -239,6 +240,12 @@ void NetQuorum::ProcessMessage(CNode& pfrom, const std::string& msg_type, DataSt LogPrint(BCLog::LLMQ, "NetQuorum::%s -- %s: Quorum not found, from peer=%d\n", __func__, msg_type, pfrom.GetId()); return; } + if (!pQuorum->HasMembers()) { + // Known by its key only: member data has nothing to attach to. + LogPrint(BCLog::LLMQ, "NetQuorum::%s -- %s: Quorum members unavailable, from peer=%d\n", __func__, msg_type, + pfrom.GetId()); + return; + } // Check if request has QUORUM_VERIFICATION_VECTOR data if (request.GetDataMask() & CQuorumDataRequest::QUORUM_VERIFICATION_VECTOR) { @@ -445,9 +452,18 @@ void NetQuorum::CheckQuorumConnections(const Consensus::LLMQParams& llmqParams, const bool watchOtherISQuorums = is_masternode && llmqParams.type == Params().GetConsensus().llmqTypeDIP0024InstantSend && - std::ranges::any_of(lastQuorums, [&proTxHash](const auto& old_quorum) { return old_quorum->IsMember(proTxHash); }); + std::ranges::any_of(lastQuorums, [&proTxHash](const auto& old_quorum) { + return old_quorum->HasMembers() && old_quorum->IsMember(proTxHash); + }); for (const auto& quorum : lastQuorums) { + if (!quorum->HasMembers()) { + LogPrint(BCLog::LLMQ, "NetQuorum::%s -- llmqType[%d] h[%d] no connections for quorum [%d:%s]: members unavailable\n", + __func__, std23::to_underlying(llmqParams.type), pindexNew->nHeight, + quorum->m_quorum_base_block_index->nHeight, + quorum->m_quorum_base_block_index->GetBlockHash().ToString()); + continue; + } if (EnsureQuorumConnections(llmqParams, m_connman, m_sporkman, {m_dmnman, m_qsnapman, m_chainman, quorum->m_quorum_base_block_index}, m_dmnman.GetListAtChainTip(), proTxHash, @@ -463,9 +479,9 @@ void NetQuorum::CheckQuorumConnections(const Consensus::LLMQParams& llmqParams, Uint256HashSet connections; const auto& cindexes = utils::CalcDeterministicWatchConnections(llmqParams.type, quorum->m_quorum_base_block_index, - quorum->members.size(), 1); + quorum->Members().size(), 1); for (auto idx : cindexes) { - connections.emplace(quorum->members[idx]->proTxHash); + connections.emplace(quorum->Members()[idx]->proTxHash); } if (!connections.empty()) { if (!m_connman.HasMasternodeQuorumNodes(llmqParams.type, quorum->m_quorum_base_block_index->GetBlockHash())) { @@ -506,6 +522,13 @@ void NetQuorum::TriggerQuorumDataRecoveryThreads(gsl::not_nullHasMembers()) return false; + LogPrint(BCLog::LLMQ, + "NetQuorum::TriggerQuorumDataRecoveryThreads -- No recovery for (%d, %s): members unavailable\n", + std23::to_underlying(pQuorum->qc->llmqType), pQuorum->qc->quorumHash.ToString()); + return true; + }); const bool fWeAreQuorumTypeMember = is_masternode && std::ranges::any_of(vecQuorums, [&proTxHash](const auto& pQuorum) { return pQuorum->IsValidMember(proTxHash); }); @@ -561,7 +584,7 @@ void NetQuorum::DataRecoveryThread(CQuorumCPtr pQuorum, uint16_t data_mask, cons } vecMemberHashes.reserve(pQuorum->qc->validMembers.size()); - for (auto& member : pQuorum->members) { + for (auto& member : pQuorum->Members()) { if (pQuorum->IsValidMember(member->proTxHash) && member->proTxHash != protx_hash) { vecMemberHashes.push_back(member->proTxHash); } @@ -644,10 +667,16 @@ 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(ContainLocalEvoErrors([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; + } + })); } void NetQuorum::TryStartVvecSyncThread(gsl::not_null block_index, CQuorumCPtr pQuorum, @@ -678,10 +707,16 @@ 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(ContainLocalEvoErrors([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; + } + })); } size_t NetQuorum::GetQuorumRecoveryStartOffset(const CQuorum& quorum, @@ -724,7 +759,7 @@ void NetQuorum::StartCleanupOldQuorumDataThread(gsl::not_nullpprev; } for (const auto& pQuorum : m_qman.ScanQuorums(params.type, pIndex, params.keepOldKeys - quorum_keys.size())) { + // A quorum known by its key only never reads stored contributions. + if (!pQuorum->HasMembers()) continue; const uint256 quorum_key = MakeQuorumKey(*pQuorum); quorum_keys.insert(quorum_key); cleanupQuorumsCache.insert(params.type, pQuorum->m_quorum_base_block_index->GetBlockHash(), @@ -759,7 +796,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,57 @@ 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(ContainLocalEvoErrors([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(ContainLocalEvoErrors( + [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; + } } - - ++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/quorums.cpp b/src/llmq/quorums.cpp index 25d35c10e45c..311e2ca030dd 100644 --- a/src/llmq/quorums.cpp +++ b/src/llmq/quorums.cpp @@ -22,7 +22,7 @@ uint256 MakeQuorumKey(const CQuorum& q) HashWriter hw{}; hw << q.params.type; hw << q.qc->quorumHash; - for (const auto& dmn : q.members) { + for (const auto& dmn : q.Members()) { hw << dmn->proTxHash; } return hw.GetHash(); @@ -107,13 +107,34 @@ CQuorum::CQuorum(const Consensus::LLMQParams& _params, CBLSWorker& _blsWorker, qc{std::move(_qc)}, m_quorum_base_block_index{_pQuorumBaseBlockIndex}, minedBlockHash{_minedBlockHash}, - members{_members.begin(), _members.end()}, + m_members{std::in_place, _members.begin(), _members.end()}, blsCache{_blsWorker} { assert(qc != nullptr); assert(m_quorum_base_block_index != nullptr); } +CQuorum::CQuorum(const Consensus::LLMQParams& _params, CBLSWorker& _blsWorker, CFinalCommitmentPtr _qc, + const CBlockIndex* _pQuorumBaseBlockIndex, const uint256& _minedBlockHash) : + params{_params}, + qc{std::move(_qc)}, + m_quorum_base_block_index{_pQuorumBaseBlockIndex}, + minedBlockHash{_minedBlockHash}, + blsCache{_blsWorker} +{ + assert(qc != nullptr); + assert(m_quorum_base_block_index != nullptr); +} + +const std::vector& CQuorum::Members() const +{ + if (!m_members) { + throw BlockDataUnavailableError(strprintf("members of quorum %s %s", qc->quorumHash.ToString(), + BLOCK_DATA_UNAVAILABLE_SUFFIX)); + } + return *m_members; +} + CQuorum::~CQuorum() = default; bool CQuorum::SetVerificationVector(const std::vector& quorumVecIn) @@ -140,11 +161,12 @@ bool CQuorum::SetSecretKeyShare(const CBLSSecretKey& secretKeyShare, const uint2 bool CQuorum::IsMember(const uint256& proTxHash) const { - return std::ranges::any_of(members, [&proTxHash](const auto& dmn) { return dmn->proTxHash == proTxHash; }); + return std::ranges::any_of(Members(), [&proTxHash](const auto& dmn) { return dmn->proTxHash == proTxHash; }); } bool CQuorum::IsValidMember(const uint256& proTxHash) const { + const auto& members{Members()}; for (const auto i : util::irange(members.size())) { // cppcheck-suppress useStlAlgorithm if (members[i]->proTxHash == proTxHash) { @@ -157,10 +179,10 @@ bool CQuorum::IsValidMember(const uint256& proTxHash) const CBLSPublicKey CQuorum::GetPubKeyShare(size_t memberIdx) const { LOCK(cs_vvec_shShare); - if (!HasVerificationVectorInternal() || memberIdx >= members.size() || !qc->validMembers[memberIdx]) { + if (!HasVerificationVectorInternal() || memberIdx >= Members().size() || !qc->validMembers[memberIdx]) { return CBLSPublicKey(); } - const auto& m = members[memberIdx]; + const auto& m = Members()[memberIdx]; return blsCache.BuildPubKeyShare(m->proTxHash, quorumVvec, CBLSId(m->proTxHash)); } @@ -182,6 +204,7 @@ CBLSSecretKey CQuorum::GetSkShare() const int CQuorum::GetMemberIndex(const uint256& proTxHash) const { + const auto& members{Members()}; for (const auto i : util::irange(members.size())) { // cppcheck-suppress useStlAlgorithm if (members[i]->proTxHash == proTxHash) { diff --git a/src/llmq/quorums.h b/src/llmq/quorums.h index 6f6d403da91b..b65748903cea 100644 --- a/src/llmq/quorums.h +++ b/src/llmq/quorums.h @@ -159,8 +159,9 @@ class CQuorumDataRequest /** * An object of this class represents a quorum which was mined on-chain (through a quorum commitment) - * It at least contains information about the members and the quorum public key which is needed to verify recovered - * signatures from this quorum. + * It at least contains the quorum public key which is needed to verify recovered signatures from this quorum, and + * its members unless this node cannot compute them exactly (the work block's score modifier needs a block body it + * pruned); Members() then raises BlockDataUnavailableError instead of returning a guess. * * In case the local node is a member of the same quorum and successfully participated in the DKG, the quorum object * will also contain the secret key share and the quorum verification vector. The quorum vvec is then used to recover @@ -175,9 +176,9 @@ class CQuorum const CFinalCommitmentPtr qc; const CBlockIndex* m_quorum_base_block_index; const uint256 minedBlockHash; - const std::vector members; private: + const std::optional> m_members; // Recovery of public key shares is very slow, so we start a background thread that pre-populates a cache so that // the public key shares are ready when needed later mutable CBLSWorkerCache blsCache; @@ -191,6 +192,9 @@ class CQuorum public: CQuorum(const Consensus::LLMQParams& _params, CBLSWorker& _blsWorker, CFinalCommitmentPtr _qc, const CBlockIndex* _pQuorumBaseBlockIndex, const uint256& _minedBlockHash, Span _members); + //! A quorum known from its commitment only, without its members. + CQuorum(const Consensus::LLMQParams& _params, CBLSWorker& _blsWorker, CFinalCommitmentPtr _qc, + const CBlockIndex* _pQuorumBaseBlockIndex, const uint256& _minedBlockHash); ~CQuorum(); @@ -209,6 +213,9 @@ class CQuorum LOCK(cs_vvec_shShare); return quorumVvec; } + bool HasMembers() const { return m_members.has_value(); } + //! The members; BlockDataUnavailableError for a quorum known by its key only. + const std::vector& Members() const; bool IsMember(const uint256& proTxHash) const; bool IsValidMember(const uint256& proTxHash) const; int GetMemberIndex(const uint256& proTxHash) const; diff --git a/src/llmq/quorumsman.cpp b/src/llmq/quorumsman.cpp index 14e2a8d2a0f6..7117aff76113 100644 --- a/src/llmq/quorumsman.cpp +++ b/src/llmq/quorumsman.cpp @@ -27,6 +27,7 @@ #include +#include #include namespace llmq { @@ -38,10 +39,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 +76,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) { @@ -78,13 +87,29 @@ CQuorumPtr CQuorumManager::BuildQuorumFromCommitment(const Consensus::LLMQType l const auto& llmq_params_opt = m_chainman.GetParams().GetLLMQ(llmqType); assert(llmq_params_opt.has_value()); - auto members = utils::GetAllQuorumMembers(qc.llmqType, {m_dmnman, m_qsnapman, m_chainman, pQuorumBaseBlockIndex}); - - auto quorum = std::make_shared(llmq_params_opt.value(), blsWorker, - std::make_unique(std::move(qc)), pQuorumBaseBlockIndex, minedBlockHash, members); - + std::optional> members; + try { + members = utils::GetAllQuorumMembers(qc.llmqType, {m_dmnman, m_qsnapman, m_chainman, pQuorumBaseBlockIndex}); + } catch (const utils::WorkBlockModifierUnavailableError& e) { + // NORMAL cannot compute the members without the work block that fixes + // their score modifier, which it pruned. The mined commitment still + // proves the quorum and its key. + if (view.identity != EvoDbIdentity::NORMAL) throw; + LogPrint(BCLog::LLMQ, "CQuorumManager::%s -- llmqType[%d] quorumHash[%s] without members: %s\n", __func__, + std23::to_underlying(llmqType), quorumHash.ToString(), e.what()); + } + + auto commitment{std::make_unique(std::move(qc))}; + auto quorum = members ? std::make_shared(llmq_params_opt.value(), blsWorker, std::move(commitment), + pQuorumBaseBlockIndex, minedBlockHash, *members) + : std::make_shared(llmq_params_opt.value(), blsWorker, std::move(commitment), + pQuorumBaseBlockIndex, minedBlockHash); + + // A quorum known by its key only is not cached: once its pruned work block + // is downloaded again, the next lookup computes its members. + if (!members) return quorum; 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 +133,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; } @@ -156,6 +181,76 @@ bool CQuorumManager::HasQuorum(Consensus::LLMQType llmqType, const CQuorumBlockP return quorum_block_processor.HasMinedCommitment(llmqType, quorumHash, chain); } +std::optional NormalizeScanStart(const Consensus::LLMQParams& llmq_params, + gsl::not_null start) +{ + // Quorum sets can only change during the mining phase of DKG. + // Find the closest known block index. + const int quorumCycleStartHeight = start->nHeight - (start->nHeight % llmq_params.dkgInterval); + const int quorumCycleMiningStartHeight = quorumCycleStartHeight + llmq_params.dkgMiningWindowStart; + const int quorumCycleMiningEndHeight = quorumCycleStartHeight + llmq_params.dkgMiningWindowEnd; + + if (start->nHeight < quorumCycleMiningStartHeight) { + // too early for this cycle, use the previous one + // bail out if it's below genesis block + if (quorumCycleMiningEndHeight < llmq_params.dkgInterval) return std::nullopt; + return start->GetAncestor(quorumCycleMiningEndHeight - llmq_params.dkgInterval); + } + if (start->nHeight > quorumCycleMiningEndHeight) { + // we are past the mining phase of this cycle, use it + return start->GetAncestor(quorumCycleMiningEndHeight); + } + // everything else is inside the mining phase of this cycle, no adjustment needed + return start.get(); +} + +std::vector CQuorumManager::ProveScan(Consensus::LLMQType llmqType, + gsl::not_null start, size_t count) const +{ + const auto& llmq_params_opt = m_chainman.GetParams().GetLLMQ(llmqType); + if (count == 0 || !llmq_params_opt || !m_chainman.IsQuorumTypeEnabled(llmqType, start)) return {}; + const auto cutoff{NormalizeScanStart(*llmq_params_opt, start)}; + if (!cutoff) return {}; + return ProveScanFromCutoff(llmqType, *cutoff, count); +} + +std::vector CQuorumManager::ProveScanFromCutoff(Consensus::LLMQType llmqType, + gsl::not_null cutoff, + size_t count) const +{ + const auto llmq_params_opt{m_chainman.GetParams().GetLLMQ(llmqType)}; + assert(llmq_params_opt.has_value()); + const auto& llmq_params{*llmq_params_opt}; + const auto end_of = [&](size_t sequence) { + return quorumBlockProcessor.SequenceEnd(llmqType, llmq_params.useRotation, sequence); + }; + std::vector sequences; + bool unreadable{false}; + if (llmq_params.useRotation) { + for (int quorum_index{0}; quorum_index < llmq_params.signingActiveQuorumCount; ++quorum_index) { + sequences.push_back({quorumBlockProcessor.GetMinedCommitmentsByQuorumIndexUntilBlock(llmqType, cutoff, + quorum_index, count, + &unreadable), + end_of(quorum_index)}); + } + } else { + sequences.push_back( + {quorumBlockProcessor.GetMinedCommitmentsUntilBlock(llmqType, cutoff, count, &unreadable), end_of(0)}); + } + // A sequence cut short by a read error is not one the seeded END marker + // describes. + if (unreadable) { + throw BlockDataReadError(strprintf("the llmqType=%d mined commitment index is unreadable", + std23::to_underlying(llmqType))); + } + auto proven{TraverseScanSequences(llmq_params.useRotation, sequences, count)}; + if (!proven) { + throw BlockDataUnavailableError(strprintf("quorum scan of %d for llmqType=%d from block %s is not covered", count, + std23::to_underlying(llmqType), cutoff->GetBlockHash().ToString())); + } + return std::move(*proven); +} + std::vector CQuorumManager::ScanQuorums(Consensus::LLMQType llmqType, size_t nCountRequested) const { const CBlockIndex* pindex = WITH_LOCK(::cs_main, return m_chainman.ActiveTip()); @@ -177,15 +272,49 @@ 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 EvoViewToken& view) const +{ + // cppcheck-suppress constVariableReference + auto& caches{m_view_caches.For(view)}; + auto& cache = [&]() -> PerLlmqTypeCache>& { + if constexpr (std::is_same_v) { + return caches.scanQuorumsCache; + } else { + static_assert(std::is_same_v); + return caches.scanCommitmentsCache; + } + }(); + 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. + // And we only do this for max_cycles() of the most recent quorums + // because signing by old quorums requires the exact quorum hash to be specified + // and quorum scanning isn't needed there. + cache.Init(m_chainman.GetConsensus(), [](const Consensus::LLMQParams& llmq) { + return llmq.max_cycles(llmq.keepOldConnections) * (llmq.dkgMiningWindowEnd - llmq.dkgMiningWindowStart); + }); + } + return cache; +} + +//! Whether the first `count` entries of a scan result can be cached: not +//! while a quorum in them is known by its key only. template -PerLlmqTypeCache>& CQuorumManager::ScanCache() const +static bool IsCacheableScan(const std::vector& entries, size_t count) { if constexpr (std::is_same_v) { - return scanQuorumsCache; - } else { - static_assert(std::is_same_v); - return scanCommitmentsCache; + return std::all_of(entries.begin(), entries.begin() + count, + [](const CQuorumCPtr& quorum) { return quorum->HasMembers(); }); } + return true; } template @@ -197,46 +326,76 @@ std::vector CQuorumManager::ScanMined(Consensus::LLMQType llmqType, gsl::not_ return {}; } - gsl::not_null pindexStore{pindexStart}; const auto& llmq_params_opt = m_chainman.GetParams().GetLLMQ(llmqType); assert(llmq_params_opt.has_value()); - - // Quorum sets can only change during the mining phase of DKG. - // Find the closest known block index. - const int quorumCycleStartHeight = pindexStart->nHeight - (pindexStart->nHeight % llmq_params_opt->dkgInterval); - const int quorumCycleMiningStartHeight = quorumCycleStartHeight + llmq_params_opt->dkgMiningWindowStart; - const int quorumCycleMiningEndHeight = quorumCycleStartHeight + llmq_params_opt->dkgMiningWindowEnd; - - if (pindexStart->nHeight < quorumCycleMiningStartHeight) { - // too early for this cycle, use the previous one - // bail out if it's below genesis block - if (quorumCycleMiningEndHeight < llmq_params_opt->dkgInterval) return {}; - pindexStore = pindexStart->GetAncestor(quorumCycleMiningEndHeight - llmq_params_opt->dkgInterval); - } else if (pindexStart->nHeight > quorumCycleMiningEndHeight) { - // we are past the mining phase of this cycle, use it - pindexStore = pindexStart->GetAncestor(quorumCycleMiningEndHeight); - } - // everything else is inside the mining phase of this cycle, no pindexStore adjustment needed + const auto cutoff{NormalizeScanStart(*llmq_params_opt, pindexStart)}; + if (!cutoff) return {}; + gsl::not_null pindexStore{*cutoff}; gsl::not_null pIndexScanCommitments{pindexStore}; size_t nScanCommitments{nCountRequested}; std::vector vecResult; bool resume{false}; + const EvoViewToken view{m_evoDb.CurrentView()}; + if (view.identity == EvoDbIdentity::SNAPSHOT) { + // Only the carried history exists at or below the base: prove the + // requested prefix from the original cutoff, never continue a shorter + // cached one, and cache only proven prefixes. + if (use_cache) { + LOCK(m_cs_maps); + if (ScanCache(view).get(llmqType, pindexStore->GetBlockHash(), vecResult) && + vecResult.size() >= nCountRequested) { + return {vecResult.begin(), vecResult.begin() + nCountRequested}; + } + vecResult.clear(); + } + // Like the scan below, read under cs_main and cache only a proof read + // from the view's chain. + // The view's index describes its own chain only, so a cutoff on + // another branch (a tip notification processed after a reorg, or a + // lookup racing one) has nothing to prove it from. Returns whether the + // view has a chain the result can be cached for. + const auto require_on_view_chain{[&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { + const CChain* chain{m_chainman.EvoChain(view.identity)}; + if (chain && !chain->Contains(pindexStore)) { + throw BlockDataUnavailableError(strprintf("quorum scan for llmqType=%d from block %s off the view's chain", + std23::to_underlying(llmqType), + pindexStore->GetBlockHash().ToString())); + } + return chain != nullptr; + }}; + std::vector proven; + { + LOCK(::cs_main); + require_on_view_chain(); + proven = ProveScan(llmqType, pindexStart, nCountRequested); + } + for (const CBlockIndex* pQuorumBaseBlockIndex : proven) { + const bool populate_cache{vecResult.size() < static_cast(llmq_params_opt->keepOldConnections)}; + std::optional entry = build(pQuorumBaseBlockIndex, populate_cache); + // The scan proved this quorum is mined: failing to build it is + // this node's state, never an empty (quorum-less) answer. + if (!entry) { + throw BlockDataUnavailableError(strprintf("quorum llmqType=%d at block %s is not available", + std23::to_underlying(llmqType), + pQuorumBaseBlockIndex->GetBlockHash().ToString())); + } + vecResult.emplace_back(std::move(*entry)); + } + // build() read the commitments by quorum hash without cs_main: they + // are this chain's only if the cutoff is still on it. + LOCK2(::cs_main, m_cs_maps); + if (require_on_view_chain() && !vecResult.empty() && use_cache) { + const size_t cached{std::min(vecResult.size(), static_cast(llmq_params_opt->keepOldConnections))}; + ScanCache(view).emplace(llmqType, pindexStore->GetBlockHash(), + {vecResult.begin(), vecResult.begin() + cached}); + } + return vecResult; + } if (use_cache) { LOCK(m_cs_maps); - auto& cache = ScanCache(); - 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. - // And we only do this for max_cycles() of the most recent quorums - // because signing by old quorums requires the exact quorum hash to be specified - // and quorum scanning isn't needed there. - cache.Init(m_chainman.GetConsensus(), [](const Consensus::LLMQParams& llmq) { - return llmq.max_cycles(llmq.keepOldConnections) * (llmq.dkgMiningWindowEnd - llmq.dkgMiningWindowStart); - }); - } - bool fCacheExists = cache.get(llmqType, pindexStore->GetBlockHash(), vecResult); + bool fCacheExists = ScanCache(view).get(llmqType, pindexStore->GetBlockHash(), vecResult); if (fCacheExists) { // We have exactly what requested so just return it if (vecResult.size() == nCountRequested) { @@ -270,15 +429,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 +463,19 @@ 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}); + if (IsCacheableScan(vecResult, nCacheEndIndex)) { + ScanCache(view).emplace(llmqType, pindexStore->GetBlockHash(), + {vecResult.begin(), vecResult.begin() + nCacheEndIndex}); + } } } // Don't return more than nCountRequested elements @@ -501,8 +662,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 +684,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 +746,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; } @@ -617,7 +781,7 @@ void CQuorumManager::CacheWarmingThreadMain() const pQuorum->m_quorum_base_block_index->GetBlockHash().ToString()); // when then later some other thread tries to get keys, it will be much faster - for (const auto i : util::irange(pQuorum->members.size())) { + for (const auto i : util::irange(pQuorum->Members().size())) { if (m_cache_interrupt) { break; } @@ -634,7 +798,7 @@ void CQuorumManager::CacheWarmingThreadMain() const void CQuorumManager::QueueQuorumForWarming(CQuorumCPtr pQuorum) const { - if (pQuorum->HasVerificationVector()) { + if (pQuorum->HasMembers() && pQuorum->HasVerificationVector()) { LOCK(m_cache_cs); m_cache_queue.push_back(std::move(pQuorum)); } diff --git a/src/llmq/quorumsman.h b/src/llmq/quorumsman.h index 47248d6189cd..91ef1ddbcdd8 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,11 @@ 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(); } + //! 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 EXCLUSIVE_LOCKS_REQUIRED(!cs_db, !m_cs_maps, !m_cache_cs); @@ -156,6 +166,14 @@ class CQuorumManager final size_t nCountRequested) const EXCLUSIVE_LOCKS_REQUIRED(!cs_db, !m_cs_maps); + /** The quorum base blocks a scan of `count` from `start` returns, proven + * in the calling view: ScanQuorums' normalization and index-family + * dispatch over this view's commitment index, whose carried sequences + * end as recorded when its snapshot was seeded. Throws + * BlockDataUnavailableError when the prefix is not covered. */ + std::vector ProveScan(Consensus::LLMQType llmqType, gsl::not_null start, + size_t count) const; + bool IsMasternode() const; bool IsWatching() const; @@ -189,15 +207,23 @@ class CQuorumManager final size_t nCountRequested, const CChain* chain) const EXCLUSIVE_LOCKS_REQUIRED(!cs_db, !m_cs_maps, !m_cache_cs); //! 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. + //! element for each. resume_block maps the last cached element to the block to continue below. In a + //! snapshot view the requested prefix is proven from the carried history instead (ProveScanFromCutoff). //! 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 initialized 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); + std::vector ProveScanFromCutoff(Consensus::LLMQType llmqType, + gsl::not_null cutoff, size_t count) const; bool BuildQuorumContributions(const CFinalCommitmentPtr& fqc, const std::shared_ptr& quorum) const; CQuorumPtr BuildQuorumFromCommitment(Consensus::LLMQType llmqType, @@ -216,6 +242,12 @@ class CQuorumManager final void MigrateOldQuorumDB(CEvoDB& evoDb) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_db); }; +/** The block a scan from `start` reads up to: inside a DKG mining window the + * start itself, past it the window's end, before it the previous cycle's + * window end. nullopt when that precedes genesis. */ +std::optional NormalizeScanStart(const Consensus::LLMQParams& llmq_params, + gsl::not_null start); + // when selecting a quorum for signing and verification, we use CQuorumManager::SelectQuorum with this offset as // starting height for scanning. This is because otherwise the resulting signatures would not be verifiable by nodes // which are not 100% at the chain tip. 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/llmq/signing_shares.cpp b/src/llmq/signing_shares.cpp index 1f3ddb6413a9..c41a344ada8b 100644 --- a/src/llmq/signing_shares.cpp +++ b/src/llmq/signing_shares.cpp @@ -391,7 +391,7 @@ bool PreVerifyBatchedSigShares(const CSigSharesNodeState::SessionInfo& session, return false; } - if (quorumMember >= session.quorum->members.size()) { + if (quorumMember >= session.quorum->Members().size()) { LogPrint(BCLog::LLMQ_SIGS, "%s -- quorumMember out of bounds\n", __func__); return false; } @@ -477,7 +477,7 @@ bool CSigSharesManager::ProcessMessageSigShare(NodeId fromId, const CSigShare& s return true; } - if (sigShare.getQuorumMember() >= quorum->members.size()) { + if (sigShare.getQuorumMember() >= quorum->Members().size()) { LogPrint(BCLog::LLMQ_SIGS, "CSigSharesManager::%s -- quorumMember out of bounds\n", __func__); return false; } @@ -742,7 +742,7 @@ std::shared_ptr CSigSharesManager::TryRecoverSig(const CQuorum& q for (auto it = sigSharesForSignHash->begin(); it != sigSharesForSignHash->end() && sigSharesForRecovery.size() < static_cast(quorum.params.threshold); ++it) { const auto& sigShare = it->second; sigSharesForRecovery.emplace_back(sigShare.sigShare.Get()); - idsForRecovery.emplace_back(quorum.members[sigShare.getQuorumMember()]->proTxHash); + idsForRecovery.emplace_back(quorum.Members()[sigShare.getQuorumMember()]->proTxHash); } // check if we can recover the final signature @@ -787,8 +787,8 @@ std::shared_ptr CSigSharesManager::TryRecoverSig(const CQuorum& q std::vector CSigSharesManager::GetRecoveryMemberOrder(const CQuorum& quorum, const uint256& id) { std::vector> v; - v.reserve(quorum.members.size()); - for (const auto& dmn : quorum.members) { + v.reserve(quorum.Members().size()); + for (const auto& dmn : quorum.Members()) { auto h = ::SerializeHash(std::make_pair(dmn->proTxHash, id)); v.emplace_back(h, dmn); } @@ -1434,9 +1434,9 @@ void CSigSharesManager::Cleanup() if (LogAcceptDebug(BCLog::LLMQ_SIGS)) { if (const auto quorumIt = quorums.find(std::make_pair(oneSigShare.getLlmqType(), oneSigShare.getQuorumHash())); quorumIt != quorums.end()) { const auto& quorum = quorumIt->second; - for (const auto i : util::irange(quorum->members.size())) { + for (const auto i : util::irange(quorum->Members().size())) { if (m->count(static_cast(i)) == 0) { - const auto& dmn = quorum->members[i]; + const auto& dmn = quorum->Members()[i]; strMissingMembers += strprintf("\n %s", dmn->proTxHash.ToString()); } } diff --git a/src/llmq/snapshot.cpp b/src/llmq/snapshot.cpp index d01c9a8d94c0..56048f7336c7 100644 --- a/src/llmq/snapshot.cpp +++ b/src/llmq/snapshot.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -23,6 +24,7 @@ using node::CBlockIndexHeightOnlyComparator; namespace { constexpr std::string_view DB_QUORUM_SNAPSHOT{"llmq_S"}; +constexpr std::string_view DB_QUORUM_MODIFIER{"llmq_M3"}; bool CheckBlockDataAvailable(gsl::not_null pindex, std::string& error) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) @@ -83,7 +85,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 +306,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 +318,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 +357,37 @@ 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); +} + +bool CQuorumSnapshotManager::SeedSnapshotForBlock(const EvoViewToken& view, const Consensus::LLMQType llmqType, + const CBlockIndex* pindex, const CQuorumSnapshot& snapshot) +{ + if (!Assume(pindex != nullptr) || !Assume(m_evoDb.HasActiveTransaction())) return false; + m_evoDb.RequireTransactionView(view); + const auto snapshot_hash{::SerializeHash(std::make_pair(llmqType, pindex->GetBlockHash()))}; + if (!m_evoDb.WriteSeed(std::make_pair(DB_QUORUM_SNAPSHOT, snapshot_hash), snapshot)) { + return false; + } + LOCK(snapshotCacheCs); + quorumSnapshotCache.For(view).erase(snapshot_hash); + return true; +} + +bool CQuorumSnapshotManager::SeedQuorumModifier(const EvoViewToken& view, Consensus::LLMQType llmq_type, + const uint256& work_block_hash, const uint256& modifier) +{ + if (!Assume(m_evoDb.HasActiveTransaction())) return false; + m_evoDb.RequireTransactionView(view); + return m_evoDb.WriteSeed(std::make_tuple(DB_QUORUM_MODIFIER, llmq_type, work_block_hash), modifier); +} + +std::optional CQuorumSnapshotManager::GetSeededQuorumModifier(Consensus::LLMQType llmq_type, + const uint256& work_block_hash) const +{ + uint256 modifier; + if (!m_evoDb.Read(std::make_tuple(DB_QUORUM_MODIFIER, llmq_type, work_block_hash), modifier)) return std::nullopt; + return modifier; } } // namespace llmq diff --git a/src/llmq/snapshot.h b/src/llmq/snapshot.h index 12bafc2bf9a8..9359ee84d1f9 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,11 +248,30 @@ 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; + + /** Seed a carried rotation quarter into `view`, inside the caller's open + * EvoDB transaction for that view. */ + bool SeedSnapshotForBlock(const EvoViewToken& view, Consensus::LLMQType llmqType, const CBlockIndex* pindex, + const CQuorumSnapshot& snapshot); + /** Seed the exact score modifier of a work block into `view`, inside the + * caller's open EvoDB transaction for that view. */ + bool SeedQuorumModifier(const EvoViewToken& view, Consensus::LLMQType llmq_type, const uint256& work_block_hash, + const uint256& modifier); + //! The modifier seeded for a work block in the calling operation's view. + std::optional GetSeededQuorumModifier(Consensus::LLMQType llmq_type, const uint256& work_block_hash) const; }; } // namespace llmq diff --git a/src/llmq/utils.cpp b/src/llmq/utils.cpp index ba7a69a36e82..187ba23e02e3 100644 --- a/src/llmq/utils.cpp +++ b/src/llmq/utils.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -17,6 +18,7 @@ #include #include +#include #include #include #include @@ -29,7 +31,7 @@ /** * Forward declarations */ -std::optional> GetNonNullCoinbaseChainlock(const node::BlockManager& blockman, const CBlockIndex* pindex); +std::optional> GetNonNullCoinbaseChainlock(const CBlock& block, const CBlockIndex& index); namespace { using QuorumMembers = std::vector; @@ -86,36 +88,63 @@ arith_uint256 calculateQuorumScore(const CDeterministicMNCPtr& dmn, const uint25 return UintToArith256(h); } -uint256 GetHashModifierFromWorkBlock(const Consensus::LLMQParams& llmqParams, const node::BlockManager& blockman, const CBlockIndex* pWorkBlockIndex) -{ - auto cbcl = GetNonNullCoinbaseChainlock(blockman, pWorkBlockIndex); - if (cbcl.has_value()) { - // We have a non-null CL signature: calculate modifier using this CL signature - auto& [bestCLSignature, bestCLHeightDiff] = cbcl.value(); - return ::SerializeHash(std::make_tuple(llmqParams.type, pWorkBlockIndex->nHeight, bestCLSignature)); - } - // No non-null CL signature found in coinbase: calculate modifier using block hash only - return ::SerializeHash(std::make_pair(llmqParams.type, pWorkBlockIndex->GetBlockHash())); -} - -uint256 GetHashModifier(const Consensus::LLMQParams& llmqParams, const Consensus::Params& consensus_params, - const node::BlockManager& blockman, gsl::not_null pCycleQuorumBaseBlockIndex) +//! The modifier of a cycle whose work block precedes v20. +uint256 CalculateHashModifier(const Consensus::LLMQParams& llmqParams, const Consensus::Params& consensus_params, + gsl::not_null pCycleQuorumBaseBlockIndex) { ASSERT_IF_DEBUG(pCycleQuorumBaseBlockIndex->nHeight % llmqParams.dkgInterval == 0); const CBlockIndex* pWorkBlockIndex = pCycleQuorumBaseBlockIndex->GetAncestor(pCycleQuorumBaseBlockIndex->nHeight - llmq::WORK_DIFF_DEPTH); + Assume(!DeploymentActiveAfter(pWorkBlockIndex, consensus_params, Consensus::DEPLOYMENT_V20)); - if (DeploymentActiveAfter(pWorkBlockIndex, consensus_params, Consensus::DEPLOYMENT_V20)) { - // v20 is active: calculate modifier using the new way. - return GetHashModifierFromWorkBlock(llmqParams, blockman, pWorkBlockIndex); - } - - // v20 isn't active yet: calculate modifier using the usual way if (llmqParams.useRotation) { return ::SerializeHash(std::make_pair(llmqParams.type, pWorkBlockIndex->GetBlockHash())); } return ::SerializeHash(std::make_pair(llmqParams.type, pCycleQuorumBaseBlockIndex->GetBlockHash())); } +//! The ChainLock-derived modifier of a v20 work block from its own data. +uint256 ModifierFromBlock(const Consensus::LLMQParams& llmq_params, const CBlock& block, const CBlockIndex& work_index) +{ + if (const auto chainlock{GetNonNullCoinbaseChainlock(block, work_index)}) { + return ::SerializeHash(std::make_tuple(llmq_params.type, work_index.nHeight, chainlock->first)); + } + return ::SerializeHash(std::make_pair(llmq_params.type, work_index.GetBlockHash())); +} + +//! The modifier from the work block's own data, or nullopt when this node +//! does not have the block. One it has but cannot read raises +//! BlockDataReadError. +std::optional ModifierFromWorkBlockData(const Consensus::LLMQParams& llmq_params, + const node::BlockManager& blockman, + gsl::not_null work_index) +{ + const auto [have_data, block_pos]{WITH_LOCK(::cs_main, return std::make_pair( + (work_index->nStatus & BLOCK_HAVE_DATA) != 0, work_index->GetBlockPos()))}; + if (!have_data) return std::nullopt; + CBlock block; + if (blockman.ReadBlockFromDisk(block, block_pos) != work_index->GetBlockHash()) { + // A caller without cs_main can race pruning, which removes the block + // after its status was read: then the node does not have it. + if (WITH_LOCK(::cs_main, return (work_index->nStatus & BLOCK_HAVE_DATA) == 0)) return std::nullopt; + throw BlockDataReadError( + strprintf("quorum work block %s cannot be read", work_index->GetBlockHash().ToString())); + } + return ModifierFromBlock(llmq_params, block, *work_index); +} + +//! The modifier of a cycle, through the exact work-block resolver once v20 is +//! active at its work block. +uint256 GetHashModifier(const Consensus::LLMQParams& llmq_params, const Consensus::Params& consensus_params, + const node::BlockManager& blockman, gsl::not_null cycle_index, + const llmq::CQuorumSnapshotManager& qsnapman) +{ + const CBlockIndex* work_index{cycle_index->GetAncestor(cycle_index->nHeight - llmq::WORK_DIFF_DEPTH)}; + if (DeploymentActiveAfter(work_index, consensus_params, Consensus::DEPLOYMENT_V20)) { + return llmq::utils::GetQuorumModifierForWorkBlock(llmq_params, blockman, Assert(work_index), qsnapman); + } + return CalculateHashModifier(llmq_params, consensus_params, cycle_index); +} + std::vector CalculateScoresForQuorum(QuorumMembers&& dmns, const uint256& modifier, const bool onlyEvoNodes) { std::vector scores; @@ -189,6 +218,7 @@ QuorumMembers CalculateQuorum(List&& mn_list, const uint256& modifier, size_t ma std::vector GetQuorumQuarterMembersBySnapshot(const Consensus::LLMQParams& llmqParams, CDeterministicMNManager& dmnman, + const llmq::CQuorumSnapshotManager& qsnapman, const Consensus::Params& consensus_params, const node::BlockManager& blockman, const CBlockIndex* pCycleQuorumBaseBlockIndex, @@ -204,7 +234,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, pCycleQuorumBaseBlockIndex, qsnapman); auto sortedAllMns = CalculateQuorum(mn_list, modifier); std::vector usedMNs; @@ -292,7 +322,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 CDeterministicMNList& mn_list, const CBlockIndex* pQuorumBaseBlockIndex, + const llmq::CQuorumSnapshotManager& qsnapman) { bool EvoOnly = (chainparams.GetConsensus().llmqTypePlatform == llmqType) && DeploymentActiveAfter(pQuorumBaseBlockIndex, chainparams.GetConsensus(), Consensus::DEPLOYMENT_V19); @@ -303,14 +334,14 @@ 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, pQuorumBaseBlockIndex, + qsnapman); 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, - llmq::CQuorumSnapshot& quorumSnapshot, std::vector& skipList, - const CBlockIndex* pCycleQuorumBaseBlockIndex) +void BuildQuorumSnapshot(const Consensus::LLMQParams& llmqParams, const CDeterministicMNList& allMns, + const CDeterministicMNList& mnUsedAtH, llmq::CQuorumSnapshot& quorumSnapshot, + std::vector& skipList, const CBlockIndex* pCycleQuorumBaseBlockIndex, const uint256& modifier) { if (!llmqParams.useRotation || pCycleQuorumBaseBlockIndex->nHeight % llmqParams.dkgInterval != 0) { ASSERT_IF_DEBUG(false); @@ -319,7 +350,6 @@ 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); auto sortedAllMns = CalculateQuorum(allMns, modifier); LogPrint(BCLog::LLMQ, "BuildQuorumSnapshot h[%d] numMns[%d]\n", pCycleQuorumBaseBlockIndex->nHeight, @@ -345,6 +375,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 +491,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, - MnsUsedAtH, quorumSnapshot, skipList, util_params.m_base_index); - util_params.m_qsnapman.StoreSnapshotForBlock(llmqParams.type, util_params.m_base_index, quorumSnapshot); + // Index the bitset in member-selection order, including when the + // modifier came from a seeded value. + BuildQuorumSnapshot(llmqParams, allMns, MnsUsedAtH, quorumSnapshot, skipList, util_params.m_base_index, modifier); + util_params.m_qsnapman.StoreSnapshotForBlock(view, llmqParams.type, util_params.m_base_index, quorumSnapshot); } return quarterQuorumMembers; @@ -470,9 +502,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) @@ -502,9 +536,12 @@ std::vector ComputeQuorumMembersByQuarterRotation(const Consensus } else { // Below a snapshot base only carried quarters exist. Computing or // predicting from fewer quarters, or reporting them as not yet - // available, would misstate the result, so report the input as - // unavailable instead. - if (util_params.m_qsnapman.IsCarriedOnly(prev_cycles[idx]->m_cycle_index)) { + // available, would misstate the result, so report a missing + // applicable quarter as unavailable instead. A cycle that never + // had one (before rotation or the type) keeps the legacy break. + const CBlockIndex* missing{prev_cycles[idx]->m_cycle_index}; + if (util_params.m_qsnapman.IsCarriedOnly(missing) && llmq::IsQuorumRotationEnabled(llmqParams, missing) && + util_params.m_chainman.IsQuorumTypeEnabled(llmqParams.type, missing->pprev)) { throw BlockDataUnavailableError(strprintf("Quorum snapshot for block %s %s", prev_cycles[idx]->m_cycle_index->GetBlockHash().ToString(), BLOCK_DATA_UNAVAILABLE_SUFFIX)); @@ -515,14 +552,14 @@ std::vector ComputeQuorumMembersByQuarterRotation(const Consensus break; } prev_cycles[idx]->m_members = GetQuorumQuarterMembersBySnapshot(llmqParams, util_params.m_dmnman, + util_params.m_qsnapman, util_params.m_chainman.GetConsensus(), util_params.m_chainman.m_blockman, prev_cycles[idx]->m_cycle_index, - prev_cycles[idx]->m_snap, - cycleBaseHeight); + 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()); @@ -623,6 +660,26 @@ std::vector> GetEnabledQuoru } namespace utils { +uint256 GetQuorumModifierForWorkBlock(const Consensus::LLMQParams& llmq_params, const node::BlockManager& blockman, + gsl::not_null work_index, const CQuorumSnapshotManager& qsnapman) +{ + const auto seeded{qsnapman.GetSeededQuorumModifier(llmq_params.type, work_index->GetBlockHash())}; + const auto from_block{ModifierFromWorkBlockData(llmq_params, blockman, work_index)}; + if (seeded && from_block && *seeded != *from_block) { + throw evo::SnapshotStateMismatchError( + strprintf("seeded quorum score modifier for work block %s differs", work_index->GetBlockHash().ToString())); + } + if (from_block) return *from_block; + if (seeded) return *seeded; + throw llmq::utils::WorkBlockModifierUnavailableError( + strprintf("quorum score modifier of work block %s is not available", work_index->GetBlockHash().ToString())); +} + +uint256 GetWorkBlockModifier(const Consensus::LLMQParams& llmq_params, const CBlock& block, const CBlockIndex& work_index) +{ + return ModifierFromBlock(llmq_params, block, work_index); +} + BlsCheck::BlsCheck() = default; BlsCheck::BlsCheck(CBLSSignature sig, std::vector pubkeys, uint256 msg_hash, std::string id_string, @@ -691,7 +748,8 @@ std::optional> ComputeQuorumMembersFromWorkBlo return std::nullopt; } - const auto modifier = GetHashModifierFromWorkBlock(llmq_params, util_params.m_chainman.m_blockman, pWorkBlockIndex.get()); + const auto modifier = GetQuorumModifierForWorkBlock(llmq_params, util_params.m_chainman.m_blockman, pWorkBlockIndex, + util_params.m_qsnapman); if (!llmq_params.useRotation) { // Canonical member selection gates EvoOnly on V19 at the future quorum base block; V19 @@ -703,7 +761,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 +773,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 +790,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 +806,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 +832,26 @@ 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, pCycleQuorumBaseBlockIndex, + util_params.m_qsnapman); 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 +865,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); + mn_list, util_params.m_base_index, util_params.m_qsnapman); } 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/llmq/utils.h b/src/llmq/utils.h index fadad5b54c25..71877f37e10b 100644 --- a/src/llmq/utils.h +++ b/src/llmq/utils.h @@ -6,6 +6,7 @@ #define BITCOIN_LLMQ_UTILS_H #include +#include #include #include #include @@ -21,6 +22,7 @@ #include #include +class CBlock; class CBlockIndex; class CDeterministicMNManager; class ChainstateManager; @@ -28,6 +30,9 @@ class CSporkManager; namespace llmq { class CQuorumSnapshotManager; } // namespace llmq +namespace node { +class BlockManager; +} // namespace node namespace llmq { struct UtilParameters { @@ -54,6 +59,24 @@ std::vector> GetEnabledQuoru const ChainstateManager& chainman, gsl::not_null pindex); namespace utils { +//! The exact score modifier of a v20 work block is not known: nothing was +//! seeded for it and this node does not have the block. +class WorkBlockModifierUnavailableError : public BlockDataUnavailableError +{ +public: + using BlockDataUnavailableError::BlockDataUnavailableError; +}; + +/** The exact score modifier of a v20 work block: its seeded value or the one + * its coinbase ChainLock gives, checked against each other when both exist. + * Without either it raises WorkBlockModifierUnavailableError in every view. + * A work block this node has but cannot read raises BlockDataReadError. */ +uint256 GetQuorumModifierForWorkBlock(const Consensus::LLMQParams& llmq_params, const node::BlockManager& blockman, + gsl::not_null work_index, const CQuorumSnapshotManager& qsnapman); +/** The score modifier `block`, a v20 work block whose index is `work_index`, + * gives from its coinbase ChainLock. */ +uint256 GetWorkBlockModifier(const Consensus::LLMQParams& llmq_params, const CBlock& block, const CBlockIndex& work_index); + struct BlsCheck { CBLSSignature m_sig; std::vector m_pubkeys; diff --git a/src/net.cpp b/src/net.cpp index 6ae8aa234292..cf296cb2e93b 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 @@ -1998,7 +2000,8 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr&& sock, // The V2Transport transparently falls back to V1 behavior when an incoming V1 connection is // detected, so use it whenever we signal NODE_P2P_V2. - const bool use_v2transport(nLocalServices & NODE_P2P_V2); + ServiceFlags local_services = GetLocalServices(); + const bool use_v2transport(local_services & NODE_P2P_V2); CNode* pnode = new CNode(id, std::move(sock), @@ -2016,7 +2019,7 @@ void CConnman::CreateNodeFromAcceptedSocket(std::unique_ptr&& sock, .use_v2transport = use_v2transport, }); pnode->AddRef(); - m_msgproc->InitializeNode(*pnode, nLocalServices); + m_msgproc->InitializeNode(*pnode, local_services); { LOCK(m_nodes_mutex); m_nodes.push_back(pnode); @@ -2955,6 +2958,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 +3202,9 @@ void CConnman::ThreadOpenConnections(const std::vector connect, CDe addrman.ResolveCollisions(); - auto mnList = dmnman.GetListAtChainTip(); + // Without the masternode list, connected masternodes cannot be + // skipped below; a duplicate connection costs less than none. + const auto mnList{ListForConnectedMasternodes(dmnman, setConnectedMasternodes).value_or(CDeterministicMNList{})}; const auto current_time{NodeClock::now()}; int nTries = 0; @@ -3467,7 +3481,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,6 +3723,25 @@ void CConnman::OpenMasternodeConnection(const CAddress &addrConnect, bool use_v2 Mutex NetEventsInterface::g_msgproc_mutex; +bool CConnman::ServicePeer(CNode& node, bool send) +{ + bool more_work{false}; + try { + 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 { + 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() { LOCK(NetEventsInterface::g_msgproc_mutex); @@ -3732,16 +3768,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(*pnode, send)}; fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend); - if (flagInterruptMsgProc) - return; - // Send messages - if (!fSkipSendMessagesForMasternodes || !pnode->m_masternode_connection) { - m_msgproc->SendMessages(pnode); - } - if (flagInterruptMsgProc) return; } diff --git a/src/net.h b/src/net.h index d0319cfd4b34..2ea0ebb72d33 100644 --- a/src/net.h +++ b/src/net.h @@ -48,6 +48,7 @@ #include #include #include +#include #include #include #include @@ -1540,6 +1541,11 @@ friend class CNode; //! that peer during `net_processing.cpp:PushNodeVersion()`. ServiceFlags GetLocalServices() const; + //! Updates the local services that this node advertises to other peers + //! during connection handshake. + void AddLocalServices(ServiceFlags services) { nLocalServices = ServiceFlags(nLocalServices | services); }; + void RemoveLocalServices(ServiceFlags services) { nLocalServices = ServiceFlags(nLocalServices & ~services); } + uint64_t GetMaxOutboundTarget() const EXCLUSIVE_LOCKS_REQUIRED(!m_total_bytes_sent_mutex); std::chrono::seconds GetMaxOutboundTimeframe() const; @@ -1617,10 +1623,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); + /** One message-handler turn for a peer: receive (its queued requests, + * orphans to reconsider, then its next message) and, if `send`, send. + * 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(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); @@ -1878,11 +1896,12 @@ friend class CNode; * This data is replicated in each Peer instance we create. * * This data is not marked const, but after being set it should not - * change. + * change. Unless AssumeUTXO is started, in which case, the peer + * will be limited until the background chain sync finishes. * * \sa Peer::our_services */ - ServiceFlags nLocalServices; + std::atomic nLocalServices; std::unique_ptr semOutbound; std::unique_ptr semAddnode; diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 2f9ae78e150d..a417e9cc493f 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -53,6 +54,7 @@ #include #include #include +#include #include #include #include @@ -591,7 +593,7 @@ class PeerManagerImpl final : public PeerManager } /** Overridden from CValidationInterface. */ - void BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindexConnected) override + void BlockConnected(ChainstateRole role, const std::shared_ptr& pblock, const CBlockIndex* pindexConnected) override EXCLUSIVE_LOCKS_REQUIRED(!m_object_request_mutex, !m_peer_mutex, !m_recent_confirmed_transactions_mutex); void BlockDisconnected(const std::shared_ptr &block, const CBlockIndex* pindex) override EXCLUSIVE_LOCKS_REQUIRED(!m_recent_confirmed_transactions_mutex); @@ -1114,6 +1116,38 @@ class PeerManagerImpl final : public PeerManager */ void FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector& vBlocks, NodeId& nodeStaller) EXCLUSIVE_LOCKS_REQUIRED(cs_main); + /** Request blocks for the background chainstate, if one is in use. */ + void TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector& vBlocks, const CBlockIndex* from_tip, const CBlockIndex* target_block) EXCLUSIVE_LOCKS_REQUIRED(cs_main); + + /** + * \brief Find next blocks to download from a peer after a starting block. + * + * \param vBlocks Vector of blocks to download which will be appended to. + * \param peer Peer which blocks will be downloaded from. + * \param state Pointer to the state of the peer. + * \param pindexWalk Pointer to the starting block to add to vBlocks. + * \param count Maximum number of blocks to allow in vBlocks. No more + * blocks will be added if it reaches this size. + * \param nWindowEnd Maximum height of blocks to allow in vBlocks. No + * blocks will be added above this height. + * \param activeChain Optional pointer to a chain to compare against. If + * provided, any next blocks which are already contained + * in this chain will not be appended to vBlocks, but + * instead will be used to update the + * state->pindexLastCommonBlock pointer. + * \param nodeStaller Optional pointer to a NodeId variable that will receive + * the ID of another peer that might be causing this peer + * to stall. This is set to the ID of the peer which + * first requested the first in-flight block in the + * download window. It is only set if vBlocks is empty at + * the end of this function call and if increasing + * nWindowEnd by 1 would cause it to be non-empty (which + * indicates the download might be stalled because every + * block in the window is in flight and no other peer is + * trying to download the next block). + */ + void FindNextBlocks(std::vector& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain=nullptr, NodeId* nodeStaller=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main); + /* Multimap used to preserve insertion order */ typedef std::multimap::iterator>> BlockDownloadMap; BlockDownloadMap mapBlocksInFlight GUARDED_BY(cs_main); @@ -1128,6 +1162,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); @@ -1518,6 +1557,7 @@ void PeerManagerImpl::UpdateBlockAvailability(NodeId nodeid, const uint256 &hash } } +// Logic for calculating which blocks to download from a given peer, given our current tip. void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int count, std::vector& vBlocks, NodeId& nodeStaller) { if (count == 0) @@ -1535,9 +1575,20 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co return; } - if (state->pindexLastCommonBlock == nullptr) { - // Bootstrap quickly by guessing a parent of our best tip is the forking point. - // Guessing wrong in either direction is not a problem. + // When we sync with AssumeUtxo and discover the snapshot is not in the peer's best chain, abort: + // We can't reorg to this chain due to missing undo data until the background sync has finished, + // so downloading blocks from it would be futile. + const CBlockIndex* snap_base{m_chainman.GetSnapshotBaseBlock()}; + if (snap_base && state->pindexBestKnownBlock->GetAncestor(snap_base->nHeight) != snap_base) { + LogDebug(BCLog::NET, "Not downloading blocks from peer=%d, which doesn't have the snapshot block in its best chain.\n", peer.m_id); + return; + } + + // Bootstrap quickly by guessing a parent of our best tip is the forking point. + // Guessing wrong in either direction is not a problem. + // Also reset pindexLastCommonBlock after a snapshot was loaded, so that blocks after the snapshot will be prioritised for download. + if (state->pindexLastCommonBlock == nullptr || + (snap_base && state->pindexLastCommonBlock->nHeight < snap_base->nHeight)) { state->pindexLastCommonBlock = m_chainman.ActiveChain()[std::min(state->pindexBestKnownBlock->nHeight, m_chainman.ActiveChain().Height())]; } @@ -1547,12 +1598,47 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) return; - std::vector vToFetch; const CBlockIndex *pindexWalk = state->pindexLastCommonBlock; // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; + + FindNextBlocks(vBlocks, peer, state, pindexWalk, count, nWindowEnd, &m_chainman.ActiveChain(), &nodeStaller); +} + +void PeerManagerImpl::TryDownloadingHistoricalBlocks(const Peer& peer, unsigned int count, std::vector& vBlocks, const CBlockIndex *from_tip, const CBlockIndex* target_block) +{ + Assert(from_tip); + Assert(target_block); + + if (vBlocks.size() >= count) { + return; + } + + vBlocks.reserve(count); + CNodeState *state = Assert(State(peer.m_id)); + + if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->GetAncestor(target_block->nHeight) != target_block) { + // This peer can't provide us the complete series of blocks leading up to the + // assumeutxo snapshot base. + // + // Presumably this peer's chain has less work than our ActiveChain()'s tip, or else we + // will eventually crash when we try to reorg to it. Let other logic + // deal with whether we disconnect this peer. + // + // TODO at some point in the future, we might choose to request what blocks + // this peer does have from the historical chain, despite it not having a + // complete history beneath the snapshot base. + return; + } + + FindNextBlocks(vBlocks, peer, state, from_tip, count, std::min(from_tip->nHeight + BLOCK_DOWNLOAD_WINDOW, target_block->nHeight)); +} + +void PeerManagerImpl::FindNextBlocks(std::vector& vBlocks, const Peer& peer, CNodeState *state, const CBlockIndex *pindexWalk, unsigned int count, int nWindowEnd, const CChain* activeChain, NodeId* nodeStaller) +{ + std::vector vToFetch; int nMaxHeight = std::min(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); NodeId waitingfor = -1; while (pindexWalk->nHeight < nMaxHeight) { @@ -1576,8 +1662,8 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co // We consider the chain that this peer is on invalid. return; } - if (pindex->nStatus & BLOCK_HAVE_DATA || m_chainman.ActiveChain().Contains(pindex)) { - if (pindex->HaveTxsDownloaded()) + if (pindex->nStatus & BLOCK_HAVE_DATA || (activeChain && activeChain->Contains(pindex))) { + if (activeChain && pindex->HaveNumChainTxs()) state->pindexLastCommonBlock = pindex; } else if (!IsBlockRequested(pindex->GetBlockHash())) { // The block is not already downloaded, and not yet in flight. @@ -1585,7 +1671,7 @@ void PeerManagerImpl::FindNextBlocksToDownload(const Peer& peer, unsigned int co // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != peer.m_id) { // We aren't able to fetch anything, but we would be if the download window was one larger. - nodeStaller = waitingfor; + if (nodeStaller) *nodeStaller = waitingfor; } return; } @@ -2233,8 +2319,31 @@ void PeerManagerImpl::StartScheduledTasks(CScheduler& scheduler) * block. Also save the time of the last tip update and * possibly reduce dynamic block stalling timeout. */ -void PeerManagerImpl::BlockConnected(const std::shared_ptr& pblock, const CBlockIndex* pindex) +void PeerManagerImpl::BlockConnected( + ChainstateRole role, + const std::shared_ptr& pblock, + const CBlockIndex* pindex) { + // Update this for all chainstate roles so that we don't mistakenly see peers + // helping us do background IBD as having a stale tip. + m_last_tip_update = GetTime(); + + // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value + auto stalling_timeout = m_block_stalling_timeout.load(); + Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT); + if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) { + const auto new_timeout = std::max(std::chrono::duration_cast(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT); + if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { + LogPrint(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout)); + } + } + + // The following tasks can be skipped since we don't maintain a mempool, or + // follow ChainLocks, for the ibd/background chainstate. + if (role == ChainstateRole::BACKGROUND) { + return; + } + PostProcessMessage(m_clhandler.ProcessCoinbaseChainLock(*pblock, pindex, *m_llmq_ctx.qman), /*node=*/-1); // Orphans included in or conflicted by the block can never be accepted, so drop them before @@ -2256,8 +2365,6 @@ void PeerManagerImpl::BlockConnected(const std::shared_ptr& pblock } } - m_last_tip_update = GetTime(); - { LOCK(m_recent_confirmed_transactions_mutex); for (const auto& ptx : pblock->vtx) { @@ -2269,16 +2376,6 @@ void PeerManagerImpl::BlockConnected(const std::shared_ptr& pblock } } } - - // In case the dynamic timeout was doubled once or more, reduce it slowly back to its default value - auto stalling_timeout = m_block_stalling_timeout.load(); - Assume(stalling_timeout >= BLOCK_STALLING_TIMEOUT_DEFAULT); - if (stalling_timeout != BLOCK_STALLING_TIMEOUT_DEFAULT) { - const auto new_timeout = std::max(std::chrono::duration_cast(stalling_timeout * 0.85), BLOCK_STALLING_TIMEOUT_DEFAULT); - if (m_block_stalling_timeout.compare_exchange_strong(stalling_timeout, new_timeout)) { - LogPrint(BCLog::NET, "Decreased stalling timeout to %d seconds\n", count_seconds(new_timeout)); - } - } } void PeerManagerImpl::BlockDisconnected(const std::shared_ptr &block, const CBlockIndex* pindex) @@ -2834,7 +2931,7 @@ void PeerManagerImpl::ProcessGetBlockData(CNode& pfrom, Peer& peer, const CInv& LOCK(cs_main); const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash); if (pindex) { - if (pindex->HaveTxsDownloaded() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) && + if (pindex->HaveNumChainTxs() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) && pindex->IsValid(BLOCK_VALID_TREE)) { // If we have the block and all of its parents, but have not yet validated it, // we might be in the middle of connecting it (ie in the unlock of cs_main @@ -3009,14 +3106,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 @@ -3029,12 +3126,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 @@ -3043,6 +3142,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); @@ -3120,23 +3221,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 @@ -3155,6 +3269,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) { @@ -5668,6 +5783,11 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, CGetSimplifiedMNListDiff cmd; vRecv >> cmd; + if (m_chainman.IsSnapshotActiveAndUnvalidated()) { + LogPrint(BCLog::NET, "%s not served before snapshot background validation completes, peer=%d\n", msg_type, pfrom.GetId()); + return; + } + if (!ConsumeMNListRequestToken(pfrom, *peer)) { LogPrint(BCLog::NET, "%s rate limited, ignoring request, peer=%d\n", msg_type, pfrom.GetId()); return; @@ -5729,6 +5849,11 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, return; } + if (m_chainman.IsSnapshotActiveAndUnvalidated()) { + LogPrint(BCLog::NET, "%s not served before snapshot background validation completes, peer=%d\n", msg_type, pfrom.GetId()); + return; + } + if (!ConsumeMNListRequestToken(pfrom, *peer)) { LogPrint(BCLog::NET, "%s rate limited, ignoring request, peer=%d\n", msg_type, pfrom.GetId()); return; @@ -5739,9 +5864,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 @@ -6019,6 +6151,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); } @@ -6897,7 +7032,23 @@ bool PeerManagerImpl::SendMessages(CNode* pto) if (CanServeBlocks(*peer) && pto->CanRelay() && ((sync_blocks_and_headers_from_peer && !IsLimitedPeer(*peer)) || !m_chainman.IsInitialBlockDownload()) && state.vBlocksInFlight.size() < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { std::vector vToDownload; NodeId staller = -1; - FindNextBlocksToDownload(*peer, MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.vBlocksInFlight.size(), vToDownload, staller); + auto get_inflight_budget = [&state]() { + return std::max(0, MAX_BLOCKS_IN_TRANSIT_PER_PEER - static_cast(state.vBlocksInFlight.size())); + }; + + // If a snapshot chainstate is in use, we want to find its next blocks + // before the background chainstate to prioritize getting to network tip. + FindNextBlocksToDownload(*peer, get_inflight_budget(), vToDownload, staller); + if (m_chainman.BackgroundSyncInProgress() && !IsLimitedPeer(*peer)) { + // If the background tip is not an ancestor of the snapshot block, + // we need to start requesting blocks from their last common ancestor. + const CBlockIndex *from_tip = LastCommonAncestor(m_chainman.GetBackgroundSyncTip(), m_chainman.GetSnapshotBaseBlock()); + TryDownloadingHistoricalBlocks( + *peer, + get_inflight_budget(), + vToDownload, from_tip, + Assert(m_chainman.GetSnapshotBaseBlock())); + } for (const CBlockIndex *pindex : vToDownload) { vGetData.emplace_back(MSG_BLOCK, pindex->GetBlockHash()); BlockRequested(pto->GetId(), *pindex); diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp index 8bc79bc873c6..5ee2a9b424d0 100644 --- a/src/node/blockstorage.cpp +++ b/src/node/blockstorage.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -604,41 +605,58 @@ void BlockManager::PruneOneBlockFile(const int fileNumber) m_dirty_fileinfo.insert(fileNumber); } -void BlockManager::FindFilesToPruneManual(std::set& setFilesToPrune, int nManualPruneHeight, int chain_tip_height) +void BlockManager::FindFilesToPruneManual( + std::set& setFilesToPrune, + int nManualPruneHeight, + const Chainstate& chain, + ChainstateManager& chainman) { assert(IsPruneMode() && nManualPruneHeight > 0); LOCK2(cs_main, cs_LastBlockFile); - if (chain_tip_height < 0) { + if (chain.m_chain.Height() < 0) { return; } - // last block to prune is the lesser of (user-specified height, MinBlocksToKeep() from the tip) - unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, - static_cast(chain_tip_height - GetParams().MinBlocksToKeep())); + const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, nManualPruneHeight); + int count = 0; for (int fileNumber = 0; fileNumber < m_last_blockfile; fileNumber++) { - if (m_blockfile_info[fileNumber].nSize == 0 || m_blockfile_info[fileNumber].nHeightLast > nLastBlockWeCanPrune) { + const auto& fileinfo = m_blockfile_info[fileNumber]; + if (fileinfo.nSize == 0 || fileinfo.nHeightLast > (unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) { continue; } + PruneOneBlockFile(fileNumber); setFilesToPrune.insert(fileNumber); count++; } - LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count); + LogPrintf("[%s] Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", + chain.GetRole(), last_block_can_prune, count); } -void BlockManager::FindFilesToPrune(std::set& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd, uint64_t target_sync_height) +void BlockManager::FindFilesToPrune( + std::set& setFilesToPrune, + int last_prune, + const Chainstate& chain, + ChainstateManager& chainman) { LOCK2(cs_main, cs_LastBlockFile); - if (chain_tip_height < 0 || GetPruneTarget() == 0) { + // Distribute our -prune budget over all chainstates. The floor of a share is capped + // at the budget itself, because regtest allows -prune below MIN_DISK_SPACE_FOR_BLOCK_FILES. + const auto target = std::max( + std::min(GetPruneTarget(), MIN_DISK_SPACE_FOR_BLOCK_FILES), GetPruneTarget() / chainman.GetAll().size()); + const uint64_t target_sync_height = chainman.m_best_header->nHeight; + + if (chain.m_chain.Height() < 0 || target == 0) { return; } - if ((uint64_t)chain_tip_height <= nPruneAfterHeight) { + if (static_cast(chain.m_chain.Height()) <= chainman.GetParams().PruneAfterHeight()) { return; } - unsigned int nLastBlockWeCanPrune{(unsigned)std::min(prune_height, chain_tip_height - GetParams().MinBlocksToKeep())}; + const auto [min_block_to_prune, last_block_can_prune] = chainman.GetPruneRange(chain, last_prune); + uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files // So we should leave a buffer under our target to account for another allocation @@ -647,12 +665,13 @@ void BlockManager::FindFilesToPrune(std::set& setFilesToPrune, uint64_t nPr uint64_t nBytesToPrune; int count = 0; - if (nCurrentUsage + nBuffer >= GetPruneTarget()) { + if (nCurrentUsage + nBuffer >= target) { // On a prune event, the chainstate DB is flushed. // To avoid excessive prune events negating the benefit of high dbcache // values, we should not prune too rapidly. // So when pruning in IBD, increase the buffer to avoid a re-prune too soon. - if (is_ibd && target_sync_height > (uint64_t)chain_tip_height) { + const auto chain_tip_height = chain.m_chain.Height(); + if (chainman.IsInitialBlockDownload() && target_sync_height > (uint64_t)chain_tip_height) { // Since this is only relevant during IBD, we assume blocks are at least 1 MB on average static constexpr uint64_t average_block_size = 1000000; /* 1 MB */ const uint64_t remaining_blocks = target_sync_height - chain_tip_height; @@ -660,18 +679,20 @@ void BlockManager::FindFilesToPrune(std::set& setFilesToPrune, uint64_t nPr } for (int fileNumber = 0; fileNumber < m_last_blockfile; fileNumber++) { - nBytesToPrune = m_blockfile_info[fileNumber].nSize + m_blockfile_info[fileNumber].nUndoSize; + const auto& fileinfo = m_blockfile_info[fileNumber]; + nBytesToPrune = fileinfo.nSize + fileinfo.nUndoSize; - if (m_blockfile_info[fileNumber].nSize == 0) { + if (fileinfo.nSize == 0) { continue; } - if (nCurrentUsage + nBuffer < GetPruneTarget()) { // are we below our target? + if (nCurrentUsage + nBuffer < target) { // are we below our target? break; } - // don't prune files that could have a block within MinBlocksToKeep() of the main chain's tip but keep scanning - if (m_blockfile_info[fileNumber].nHeightLast > nLastBlockWeCanPrune) { + // don't prune files that could have a block that's not within the allowable + // prune range for the chain being pruned. + if (fileinfo.nHeightLast > (unsigned)last_block_can_prune || fileinfo.nHeightFirst < (unsigned)min_block_to_prune) { continue; } @@ -683,10 +704,10 @@ void BlockManager::FindFilesToPrune(std::set& setFilesToPrune, uint64_t nPr } } - LogPrint(BCLog::PRUNE, "target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n", - GetPruneTarget() / 1024 / 1024, nCurrentUsage / 1024 / 1024, - (int64_t(GetPruneTarget()) - int64_t(nCurrentUsage)) / 1024 / 1024, - nLastBlockWeCanPrune, count); + LogPrint(BCLog::PRUNE, "[%s] target=%dMiB actual=%dMiB diff=%dMiB min_height=%d max_prune_height=%d removed %d blk/rev pairs\n", + chain.GetRole(), target / 1024 / 1024, nCurrentUsage / 1024 / 1024, + (int64_t(target) - int64_t(nCurrentUsage)) / 1024 / 1024, + min_block_to_prune, last_block_can_prune, count); } void BlockManager::UpdatePruneLock(const std::string& name, const PruneLockInfo& lock_info) { @@ -710,7 +731,7 @@ CBlockIndex* BlockManager::InsertBlockIndex(const uint256& hash) return pindex; } -bool BlockManager::LoadBlockIndex() +bool BlockManager::LoadBlockIndex(const std::optional& snapshot_blockhash) { // Snapshot promotion reloads the block index a second time in the same // process (see node::LoadChainstate), and both containers below are rebuilt @@ -731,6 +752,25 @@ bool BlockManager::LoadBlockIndex() } } + int snapshot_height = -1; + if (snapshot_blockhash) { + const std::optional maybe_au_data = GetParams().AssumeutxoForBlockhash(*snapshot_blockhash); + if (!maybe_au_data) { + m_opts.notifications.fatalError(strprintf("Assumeutxo data not found for the given blockhash '%s'.", snapshot_blockhash->ToString())); + return false; + } + const AssumeutxoData& au_data = *Assert(maybe_au_data); + snapshot_height = au_data.height; + // A base the block index lacks is reported by ChainstateManager::LoadBlockIndex(). + if (CBlockIndex* base{LookupBlockIndex(*snapshot_blockhash)}) { + // Since nChainTx (responsible for estimated progress) isn't persisted + // to disk, we must bootstrap the value for assumedvalid chainstates + // from the hardcoded assumeutxo chainparams. + base->nChainTx = au_data.nChainTx; + LogPrintf("[snapshot] set nChainTx=%d for %s\n", au_data.nChainTx, snapshot_blockhash->ToString()); + } + } + // Calculate nChainWork std::vector vSortedByHeight{GetAllBlockIndices()}; std::sort(vSortedByHeight.begin(), vSortedByHeight.end(), @@ -753,7 +793,11 @@ bool BlockManager::LoadBlockIndex() // Pruned nodes may have deleted the block. if (pindex->nTx > 0) { if (pindex->pprev) { - if (pindex->pprev->nChainTx > 0) { + if (snapshot_blockhash && pindex->nHeight == snapshot_height && + pindex->GetBlockHash() == *snapshot_blockhash) { + // Should have been set above; don't disturb it with code below. + Assert(pindex->nChainTx > 0); + } else if (pindex->pprev->nChainTx > 0) { pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx; } else { pindex->nChainTx = 0; @@ -799,9 +843,9 @@ bool BlockManager::WriteBlockIndexDB() return true; } -bool BlockManager::LoadBlockIndexDB() +bool BlockManager::LoadBlockIndexDB(const std::optional& snapshot_blockhash) { - if (!LoadBlockIndex()) { + if (!LoadBlockIndex(snapshot_blockhash)) { return false; } @@ -1527,6 +1571,12 @@ void ImportBlocks(ChainstateManager& chainman, std::vector vImportFile for (Chainstate* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) { BlockValidationState state; if (!chainstate->ActivateBestChain(state, nullptr)) { + if (IsLocalEvoStateError(state)) { + // The chainstate stays eligible; the other chainstates + // and the rest of startup proceed without it. + LogPrintf("Chainstate cannot advance yet (%s), continuing\n", state.ToString()); + continue; + } chainman.GetNotifications().fatalError(strprintf("Failed to connect best block (%s)", state.ToString())); return; } diff --git a/src/node/blockstorage.h b/src/node/blockstorage.h index d2f9d8d299af..7b4fd3757134 100644 --- a/src/node/blockstorage.h +++ b/src/node/blockstorage.h @@ -36,6 +36,7 @@ class CBlockUndo; class Chainstate; struct IndexMigrationOptions; class ChainstateManager; +enum class ChainstateRole; namespace Consensus { struct Params; } @@ -129,7 +130,7 @@ class BlockManager * per index entry (nStatus, nChainWork, nTimeMax, etc.) as well as peripheral * collections like m_dirty_blockindex. */ - bool LoadBlockIndex() + bool LoadBlockIndex(const std::optional& snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(cs_main); /** Return false if block file or undo file flushing fails. */ @@ -152,7 +153,11 @@ class BlockManager bool UndoWriteToDisk(const CBlockUndo& blockundo, const std::optional>& compressed, uint32_t size_field, FlatFilePos& pos, const uint256& hashBlock) const; /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */ - void FindFilesToPruneManual(std::set& setFilesToPrune, int nManualPruneHeight, int chain_tip_height); + void FindFilesToPruneManual( + std::set& setFilesToPrune, + int nManualPruneHeight, + const Chainstate& chain, + ChainstateManager& chainman); /** * Prune block and undo files (blk???.dat and rev???.dat) so that the disk space used is less than a user-defined target. @@ -168,8 +173,13 @@ class BlockManager * A db flag records the fact that at least some block files have been pruned. * * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned + * @param last_prune The last height we're able to prune, according to the prune locks */ - void FindFilesToPrune(std::set& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd, uint64_t target_sync_height); + void FindFilesToPrune( + std::set& setFilesToPrune, + int last_prune, + const Chainstate& chain, + ChainstateManager& chainman); RecursiveMutex cs_LastBlockFile; std::vector m_blockfile_info; @@ -233,7 +243,8 @@ class BlockManager std::unique_ptr m_block_tree_db GUARDED_BY(::cs_main); bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); - bool LoadBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); + bool LoadBlockIndexDB(const std::optional& snapshot_blockhash) + EXCLUSIVE_LOCKS_REQUIRED(::cs_main); /** * Remove any pruned block & undo files that are still on disk. diff --git a/src/node/chainstate.cpp b/src/node/chainstate.cpp index 42fc24fba26a..d554c9d20a39 100644 --- a/src/node/chainstate.cpp +++ b/src/node/chainstate.cpp @@ -6,13 +6,15 @@ #include #include -#include #include +#include +#include #include #include #include #include #include +#include #include #include #include @@ -27,6 +29,7 @@ #include #include #include +#include #include #include @@ -52,6 +55,18 @@ static bool RecoverSnapshotCleanup(CEvoDB& evodb, const fs::path& data_dir, bool fs::path invalid{snapshot}; invalid += SNAPSHOT_INVALID_SUFFIX; + // Left behind only by a deletion that SetAsideInvalidSnapshotDir() did not + // finish; nothing reads it. + try { + const fs::path discarded{DiscardedSnapshotDir(snapshot)}; + if (fs::exists(discarded)) { + LogPrintf("[snapshot] removing discarded snapshot chainstate directory %s\n", fs::PathToString(discarded)); + RemoveAllDurably(discarded); + } + } catch (const fs::filesystem_error& e) { + LogPrintf("[snapshot] unable to remove discarded snapshot chainstate directory: %s\n", e.what()); + } + // A persisted rejection whose coins directory was not invalidated yet: // finish the invalidation, then drop the rejected generation. A live // generation owns the snapshot directory, so the rejected one's is gone. @@ -59,15 +74,7 @@ static bool RecoverSnapshotCleanup(CEvoDB& evodb, const fs::path& data_dir, bool if (fs::exists(snapshot) && !evodb.GetSnapshotGeneration()) { LogPrintf("[snapshot] completing interrupted invalid-snapshot coins invalidation\n"); try { - // An earlier rejection's directory keeps its place: it may be - // the one the user was asked to report. - if (fs::exists(invalid)) { - LogPrintf("[snapshot] %s already exists; deleting %s instead\n", fs::PathToString(invalid), - fs::PathToString(snapshot)); - RemoveAllDurably(snapshot); - } else { - RenameDurably(snapshot, invalid); - } + SetAsideInvalidSnapshotDir(snapshot); } catch (const fs::filesystem_error& e) { error = strprintf(_("Failed to finish interrupted invalid snapshot cleanup: %s"), e.what()); return false; @@ -108,6 +115,15 @@ static bool RecoverSnapshotCleanup(CEvoDB& evodb, const fs::path& data_dir, bool // journaled cleanup may promote; anything else is an interrupted // invalid-snapshot cleanup. if (journal) { + // The swap keeps the background directory until the promotion + // completes. Without it, the snapshot directory is gone because + // the journaled snapshot was rejected, and it must never be + // promoted. An _INVALID directory may be an earlier snapshot's. + if (!fs::exists(to_delete)) { + error = _("Interrupted snapshot cleanup found a snapshot journaled for promotion that was rejected. " + "Restart with -reindex-chainstate."); + return false; + } uint256 coins_tip; try { CCoinsViewDB coins_db{DBParams{.path = normal, .cache_bytes = 1 << 20, .obfuscate = true}, @@ -163,7 +179,8 @@ static bool FinishRecoveredPromotion(CEvoDB& evodb, const fs::path& data_dir, bi const auto journal{evodb.ReadPromotionJournal()}; LogPrintf("[snapshot] completing interrupted snapshot EvoDB promotion\n"); if (!journal || !evodb.PromoteSnapshotMarkers(journal->tip)) { - error = _("Failed to finish interrupted snapshot marker promotion."); + error = _("Failed to finish interrupted snapshot marker promotion. Restart to retry; if it keeps " + "failing, restart with -reindex-chainstate."); return false; } fs::path to_delete{data_dir / "chainstate"}; @@ -337,7 +354,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")}; } @@ -354,6 +371,46 @@ static ChainstateLoadResult CompleteChainstateInitialization(ChainstateManager& return {ChainstateLoadStatus::SUCCESS, {}}; } +//! The live generation's retained evo section must still match the pin its +//! base is authorized by: the seeded state is only as good as that match. +static util::Result RevalidateRetainedEvoSection(const ChainstateManager& chainman, const CEvoDB& evodb) +{ + const auto generation{evodb.GetSnapshotGeneration()}; + if (!generation) return {}; + const auto refuse = [](const std::string& reason) -> util::Result { + LogPrintf("[snapshot] %s\n", reason); + return util::Error{_("The assumeutxo snapshot's Evo state no longer matches its authorization. Restart with " + "-reindex-chainstate to discard the snapshot.")}; + }; + const auto au_data{chainman.GetParams().AssumeutxoForBlockhash(generation->base)}; + if (!au_data || au_data->height != generation->base_height) { + return refuse("no assumeutxo authorization for the snapshot base"); + } + const bool dip3_base{generation->base_height >= + chainman.GetConsensus().DeploymentHeight(Consensus::DEPLOYMENT_DIP0003)}; + const auto retained{evodb.ReadRetainedEvoSection()}; + if (!retained) { + if (dip3_base || au_data->evo_hash != EvoSnapshotHash{uint256::ZERO}) { + return refuse("the retained evo section is missing"); + } + return {}; + } + evo::EvoSnapshot snapshot; + try { + DataStream stream{*retained}; + stream >> snapshot; + if (!stream.empty()) return refuse("trailing data after the retained evo section"); + } catch (const std::ios_base::failure& e) { + return refuse(strprintf("the retained evo section does not decode: %s", e.what())); + } + if (snapshot.base_block_hash != generation->base) return refuse("the retained evo section is for another base"); + if ((dip3_base || au_data->evo_hash != EvoSnapshotHash{uint256::ZERO}) && + EvoSnapshotHash{evo::GetEvoSnapshotHash(snapshot)} != au_data->evo_hash) { + return refuse("the retained evo section does not match its pin"); + } + return {}; +} + ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSizes& cache_sizes, const ChainstateLoadOptions& options, CEvoDB& evodb, CDeterministicMNManager& dmnman, CSpecialTxProcessor& special_tx) @@ -382,6 +439,12 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize return {ChainstateLoadStatus::FAILURE, util::ErrorString(result)}; } } + // Evo inputs captured for a snapshot that never got published, e.g. after + // a crash, are of no use. + if (!evodb.GetSnapshotGeneration() && !evo::EraseAllEvoSnapshotCaptures(evodb)) { + return {ChainstateLoadStatus::FAILURE, + _("Error removing stale assumeutxo snapshot state from the Evo database")}; + } bool promotion_pending{false}; if (!options.dash_dbs_in_memory && !options.reindex && !options.reindex_chainstate) { bilingual_str recovery_error; @@ -407,9 +470,14 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize // Load a chain created from a UTXO snapshot, if any exist. bilingual_str snapshot_error; - if (!chainman.DetectSnapshotChainstate(options.mempool, snapshot_error)) { + if (!chainman.DetectSnapshotChainstate(snapshot_error)) { return {ChainstateLoadStatus::FAILURE, snapshot_error}; } + if (chainman.IsSnapshotActive()) { + if (auto result{RevalidateRetainedEvoSection(chainman, evodb)}; !result) { + return {ChainstateLoadStatus::FAILURE, util::ErrorString(result)}; + } + } // A crash between publishing a generation and persisting the snapshot // directory's base block leaves a generation that no chainstate uses. if (evodb.GetSnapshotGeneration() && !chainman.IsSnapshotActive() && !promotion_pending) { @@ -418,6 +486,18 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize _("Snapshot EvoDB state has no snapshot chainstate. Reindex is required.")}; } LogPrintf("[snapshot] discarded a snapshot EvoDB generation that never activated\n"); + if (!evo::EraseAllEvoSnapshotCaptures(evodb)) { + return {ChainstateLoadStatus::FAILURE, + _("Error removing stale assumeutxo snapshot state from the Evo database")}; + } + } + // Nor does any chainstate use the coins of a load that never recorded its + // base block: a later load would open them and add its own. + if (const auto snapshot_dir{FindSnapshotChainstateDir(chainman.m_options.datadir)}; + snapshot_dir && !chainman.IsSnapshotActive() && !fs::exists(*snapshot_dir / SNAPSHOT_BLOCKHASH_FILENAME) && + !DeleteSnapshotChainstateFromDisk(chainman.m_options.datadir)) { + return {ChainstateLoadStatus::FAILURE, + _("Failed to remove an unused snapshot chainstate directory. Remove it manually before restarting.")}; } auto [init_status, init_error] = CompleteChainstateInitialization(chainman, cache_sizes, options, evodb, dmnman, @@ -436,8 +516,9 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize // too risky to do in the middle of normal runtime. const auto snapshot_completion = chainman.MaybeCompleteSnapshotValidation(); - if (snapshot_completion == SnapshotCompletionResult::SKIPPED) { - // Do nothing; expected case. + if (snapshot_completion == SnapshotCompletionResult::SKIPPED || + snapshot_completion == SnapshotCompletionResult::EVO_DATA_UNAVAILABLE) { + // Do nothing; expected case, or completion is retried once the data is there. } else if (snapshot_completion == SnapshotCompletionResult::SUCCESS) { LogPrintf("[snapshot] cleaning up unneeded background chainstate, then reinitializing\n"); if (!chainman.ValidatedSnapshotCleanup()) { @@ -463,6 +544,9 @@ ChainstateLoadResult LoadChainstate(ChainstateManager& chainman, const CacheSize if (init_status != ChainstateLoadStatus::SUCCESS) { return {init_status, init_error}; } + } else if (snapshot_completion == SnapshotCompletionResult::EVO_LOCAL_FAILURE || + snapshot_completion == SnapshotCompletionResult::EVO_INTERNAL_ERROR) { + return {ChainstateLoadStatus::FAILURE, SnapshotCompletionStopMessage(snapshot_completion, "see debug.log")}; } else { // The UTXO hashing inside completion takes minutes and aborts with // STATS_FAILED when shutdown is requested mid-way. That says nothing diff --git a/src/node/chainstatemanager_args.cpp b/src/node/chainstatemanager_args.cpp index 862f5a932eac..e0dd476c3d7c 100644 --- a/src/node/chainstatemanager_args.cpp +++ b/src/node/chainstatemanager_args.cpp @@ -7,6 +7,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -22,6 +25,12 @@ #include namespace node { +bool LegacyIndexesEnabled(const ArgsManager& args) +{ + return args.GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX) || args.GetBoolArg("-spentindex", DEFAULT_SPENTINDEX) || + args.GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX); +} + std::optional ApplyArgsManOptions(const ArgsManager& args, ChainstateManager::Options& opts) { if (auto value{args.GetIntArg("-checkblockindex")}) { @@ -42,6 +51,9 @@ std::optional ApplyArgsManOptions(const ArgsManager& args, Chains if (auto value{args.GetIntArg("-maxtipage")}) opts.max_tip_age = std::chrono::seconds{*value}; + opts.masternode = args.IsArgSet("-masternodeblsprivkey"); + opts.legacy_indexes = LegacyIndexesEnabled(args); + ReadDatabaseArgs(args, opts.block_tree_db); ReadDatabaseArgs(args, opts.coins_db); ReadCoinsViewArgs(args, opts.coins_view); diff --git a/src/node/chainstatemanager_args.h b/src/node/chainstatemanager_args.h index e4d9c9b0b56b..3dbd166c005c 100644 --- a/src/node/chainstatemanager_args.h +++ b/src/node/chainstatemanager_args.h @@ -18,6 +18,9 @@ static constexpr int MAX_SCRIPTCHECK_THREADS{15}; static constexpr int DEFAULT_SCRIPTCHECK_THREADS{0}; namespace node { +//! Whether -addressindex, -spentindex or -timestampindex is enabled. +bool LegacyIndexesEnabled(const ArgsManager& args); + [[nodiscard]] std::optional ApplyArgsManOptions(const ArgsManager& args, ChainstateManager::Options& opts); } // namespace node diff --git a/src/node/context.h b/src/node/context.h index ee9db1292479..d19c4ff61126 100644 --- a/src/node/context.h +++ b/src/node/context.h @@ -6,6 +6,7 @@ #define BITCOIN_NODE_CONTEXT_H #include +#include #include #include @@ -96,6 +97,10 @@ struct NodeContext { std::unique_ptr banman; ArgsManager* args{nullptr}; // Currently a raw pointer because the memory is not managed by this struct std::vector indexes; // raw pointers because memory is not managed by this struct + //! Startup starts the index threads after the block import. A snapshot + //! completion before then rebinds the indexes and leaves starting them to it. + Mutex index_start_mutex; + bool index_threads_started GUARDED_BY(index_start_mutex){false}; std::unique_ptr chain; //! List of all chain clients (wallet processes or other client) connected to node. std::vector> chain_clients; diff --git a/src/node/interfaces.cpp b/src/node/interfaces.cpp index 251c2d4b6a0e..86ad6ffa6c6a 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,66 @@ 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()}; +} + +std::string EvoStateWarningSource(std::string_view operation) { return strprintf("interfaces:%s", operation); } + +//! Set the operation's warning, which notifies the GUI only when it changes, +//! and log `e` once per operation and active Evo view: GUI models poll these +//! operations. +void ReportEvoStateUnavailable(const CEvoDB* evodb, std::string_view operation, const evo::LocalStateError& e) +{ + // 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}; + if (WarnLocalEvoStateUnavailable(EvoStateWarningSource(operation), strprintf("%s could not read it", operation), + reason)) { + uiInterface.NotifyAlertChanged(); + } + static Mutex mutex; + static std::set> logged; + const EvoViewToken view{evodb ? evodb->ActiveView() : EvoViewToken{}}; + if (WITH_LOCK(mutex, return logged.emplace(operation, view.db, view.identity, view.generation).second)) { + 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 auto read_again = [&] { + if (SetEvoStateWarning(EvoStateWarningSource(operation), std::nullopt)) uiInterface.NotifyAlertChanged(); + }; + if constexpr (std::is_void_v>) { + fn(); + read_again(); + } else { + auto result{fn()}; + read_again(); + return result; + } + } catch (const evo::LocalStateError& e) { + ReportEvoStateUnavailable(evodb, operation, e); + return on_unavailable(); + } +} + class MnEntryImpl : public MnEntry { private: @@ -273,83 +338,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 +483,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 +552,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 +611,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 +660,49 @@ 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"; + if (!context().gov_collateral_index->IsCollateralSynced()) { + error = "This node's governance collateral index follows the background chainstate until assumeutxo " + "snapshot validation completes, so it can't submit proposals yet"; 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 +711,60 @@ 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; } + if (!context().gov_collateral_index->IsCollateralSynced()) { + error = "This node's governance collateral index follows the background chainstate until assumeutxo " + "snapshot validation completes, so it can't submit proposals yet"; + 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 +781,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 +841,68 @@ 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) { + // A quorum known by its key only counts its commitment's member slots. + const size_t numMembers{q->HasMembers() ? q->Members().size() : q->qc->validMembers.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 + { + // 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 active Evo view. + 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 +914,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 @@ -717,6 +927,7 @@ class LLMQImpl : public LLMQ best_cl_height = chainlocks->GetBestChainLockHeight(); } + // The active chain and its Evo view change together, under cs_main. LOCK(::cs_main); const CChain& active{context().chainman->ActiveChain()}; const CBlockIndex* tip{active.Tip()}; @@ -755,6 +966,8 @@ class LLMQImpl : public LLMQ } return {PlatformQuorumStatus::FOUND, qc.quorumPublicKey.ToByteVector()}; } + +public: std::vector getInstantSendLock(const uint256& txid) override { if (!context().isman) { @@ -1169,10 +1382,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 { @@ -1346,9 +1564,9 @@ class NotificationsProxy : public CValidationInterface { m_notifications->transactionRemovedFromMempool(tx, reason); } - void BlockConnected(const std::shared_ptr& block, const CBlockIndex* index) override + void BlockConnected(ChainstateRole role, const std::shared_ptr& block, const CBlockIndex* index) override { - m_notifications->blockConnected(kernel::MakeBlockInfo(index, block.get())); + m_notifications->blockConnected(role, kernel::MakeBlockInfo(index, block.get())); } void BlockDisconnected(const std::shared_ptr& block, const CBlockIndex* index) override { @@ -1358,7 +1576,9 @@ class NotificationsProxy : public CValidationInterface { m_notifications->updatedBlockTip(); } - void ChainStateFlushed(const CBlockLocator& locator) override { m_notifications->chainStateFlushed(locator); } + void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override { + m_notifications->chainStateFlushed(role, locator); + } void NotifyChainLock(const CBlockIndex* pindexChainLock, const std::shared_ptr& clsig) override { m_notifications->notifyChainLock(pindexChainLock, clsig); @@ -1509,21 +1729,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 +1897,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/kernel_notifications.cpp b/src/node/kernel_notifications.cpp index 8cf06e30931a..d550697208f7 100644 --- a/src/node/kernel_notifications.cpp +++ b/src/node/kernel_notifications.cpp @@ -88,6 +88,11 @@ void KernelNotifications::masternodeListChanged(const CDeterministicMNList& list uiInterface.NotifyMasternodeListChanged(list, index); } +void KernelNotifications::evoStateWarningChanged() +{ + uiInterface.NotifyAlertChanged(); +} + void KernelNotifications::flushError(const std::string& debug_message) { AbortNode(m_exit_status, debug_message); diff --git a/src/node/kernel_notifications.h b/src/node/kernel_notifications.h index 21d458a5821b..6863c9722b1f 100644 --- a/src/node/kernel_notifications.h +++ b/src/node/kernel_notifications.h @@ -36,6 +36,8 @@ class KernelNotifications : public kernel::Notifications void masternodeListChanged(const CDeterministicMNList& list, const CBlockIndex* index) override; + void evoStateWarningChanged() override; + void flushError(const std::string& debug_message) override; void fatalError(const std::string& debug_message, const bilingual_str& user_message = {}) override; diff --git a/src/node/mempool_persist.cpp b/src/node/mempool_persist.cpp index f69678b5b43f..aaaf292713f2 100644 --- a/src/node/mempool_persist.cpp +++ b/src/node/mempool_persist.cpp @@ -91,6 +91,11 @@ bool LoadMempool(CTxMemPool& pool, const fs::path& load_path, Chainstate& active } if (nTime > TicksSinceEpoch(now - pool.m_expiry)) { LOCK(cs_main); + // A snapshot activation or rejection moves the mempool to another chainstate, or detaches it. + if (active_chainstate.GetMempool() != &pool) { + LogPrintf("Stopping the mempool load: the chainstate no longer holds this mempool\n"); + return false; + } const auto& accepted = AcceptToMemoryPool(active_chainstate, tx, nTime, /*bypass_limits=*/false, /*test_accept=*/false); if (accepted.m_result_type == MempoolAcceptResult::ResultType::VALID) { ++count; diff --git a/src/node/miner.cpp b/src/node/miner.cpp index 27c045c9c729..0914ba9b8b08 100644 --- a/src/node/miner.cpp +++ b/src/node/miner.cpp @@ -26,13 +26,14 @@ #include #include -#include #include #include +#include #include #include -#include #include +#include +#include #include #include #include @@ -104,8 +105,8 @@ void BlockAssembler::resetBlock() } // Helper to calculate best chainlock -static bool CalcCbTxBestChainlock(const chainlock::Chainlocks& chainlocks, const node::BlockManager& blockman, const CBlockIndex* pindexPrev, - uint32_t& bestCLHeightDiff, CBLSSignature& bestCLSignature) +static bool CalcCbTxBestChainlock(const chainlock::Chainlocks& chainlocks, const CSpecialTxProcessor& special_tx, + const CBlockIndex* pindexPrev, uint32_t& bestCLHeightDiff, CBLSSignature& bestCLSignature) { auto [best_clsig, pindexCL] = chainlocks.GetBestChainlockWithPindex(); if (best_clsig.getHeight() < Params().GetConsensus().DeploymentHeight(Consensus::DEPLOYMENT_V19) || @@ -119,7 +120,17 @@ static bool CalcCbTxBestChainlock(const chainlock::Chainlocks& chainlocks, const return true; } - auto prevBlockCoinbaseChainlock = GetNonNullCoinbaseChainlock(blockman, pindexPrev); + // The same reader block validation uses, so a snapshot chainstate mining on + // its base sees the carried ChainLock rather than "none". + const CoinbaseChainlock previous{special_tx.GetCoinbaseChainlock(pindexPrev)}; + if (previous.status == CoinbaseChainlock::Status::UNAVAILABLE) { + throw BlockDataUnavailableError( + strprintf("coinbase ChainLock of block %s is not available", pindexPrev->GetBlockHash().ToString())); + } + std::optional> prevBlockCoinbaseChainlock; + if (previous.status == CoinbaseChainlock::Status::CERTIFIED) { + prevBlockCoinbaseChainlock = std::make_pair(previous.signature, previous.height_diff); + } 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 +361,8 @@ 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_chainstate.m_special_tx, 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/node/utxo_snapshot.cpp b/src/node/utxo_snapshot.cpp index 479dd6598b57..3577c04af17c 100644 --- a/src/node/utxo_snapshot.cpp +++ b/src/node/utxo_snapshot.cpp @@ -101,4 +101,37 @@ std::optional FindSnapshotChainstateDir(const fs::path& data_dir) return std::nullopt; } +fs::path DiscardedSnapshotDir(const fs::path& snapshot_dir) +{ + fs::path discarded{snapshot_dir}; + discarded += SNAPSHOT_TODELETE_SUFFIX; + return discarded; +} + +void SetAsideInvalidSnapshotDir(const fs::path& snapshot_dir) +{ + fs::path invalid{snapshot_dir}; + invalid += SNAPSHOT_INVALID_SUFFIX; + if (!fs::exists(invalid)) { + LogPrintf("[snapshot] renaming snapshot datadir %s to %s\n", fs::PathToString(snapshot_dir), + fs::PathToString(invalid)); + RenameDurably(snapshot_dir, invalid); + return; + } + // Moved aside before it is deleted: a deletion cut short in place would + // leave a partial snapshot dir for the next startup to load. + LogPrintf("[snapshot] %s already exists; deleting %s instead\n", fs::PathToString(invalid), + fs::PathToString(snapshot_dir)); + const fs::path discarded{DiscardedSnapshotDir(snapshot_dir)}; + // Nothing reads a leftover of a deletion cut short, and it would block the rename. + if (fs::exists(discarded)) RemoveAllDurably(discarded); + RenameDurably(snapshot_dir, discarded); + // Moved aside, the dir is gone for every reader; startup removes what is left. + try { + RemoveAllDurably(discarded); + } catch (const fs::filesystem_error& e) { + LogPrintf("[snapshot] unable to delete %s, retrying at startup: %s\n", fs::PathToString(discarded), e.what()); + } +} + } // namespace node diff --git a/src/node/utxo_snapshot.h b/src/node/utxo_snapshot.h index 18927452c096..ae5966d911fb 100644 --- a/src/node/utxo_snapshot.h +++ b/src/node/utxo_snapshot.h @@ -76,6 +76,16 @@ constexpr std::string_view SNAPSHOT_TODELETE_SUFFIX = "_todelete"; //! Return a path to the snapshot-based chainstate dir, if one exists. std::optional FindSnapshotChainstateDir(const fs::path& data_dir); +//! Where SetAsideInvalidSnapshotDir() moves `snapshot_dir` to delete it. +fs::path DiscardedSnapshotDir(const fs::path& snapshot_dir); + +//! Durably move a rejected snapshot chainstate dir to its SNAPSHOT_INVALID_SUFFIX +//! name. An earlier rejection's dir keeps that name, since it may be the one the +//! user was asked to report, and `snapshot_dir` is moved to +//! DiscardedSnapshotDir() and deleted instead. Throws fs::filesystem_error if +//! `snapshot_dir` could not be moved. +void SetAsideInvalidSnapshotDir(const fs::path& snapshot_dir); + } // namespace node #endif // BITCOIN_NODE_UTXO_SNAPSHOT_H 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..b956a88e1492 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,15 @@ 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; + } + if (m_error_label->text() == MasternodeWidgetUtil::masternodeStateUnavailableText()) showError(QString()); + refreshCollateralCandidates(*registered); } void RegisterMasternodeWizard::refreshCollateralCandidates(const std::set& registered_collaterals) @@ -1391,7 +1426,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 +1538,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 +1581,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..071a710d66f1 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