/Users/eugenesiegel/btc/bitcoin/src/validation.h
| Line | Count | Source (jump to first uncovered line) | 
| 1 |  | // Copyright (c) 2009-2010 Satoshi Nakamoto | 
| 2 |  | // Copyright (c) 2009-present The Bitcoin Core developers | 
| 3 |  | // Distributed under the MIT software license, see the accompanying | 
| 4 |  | // file COPYING or http://www.opensource.org/licenses/mit-license.php. | 
| 5 |  |  | 
| 6 |  | #ifndef BITCOIN_VALIDATION_H | 
| 7 |  | #define BITCOIN_VALIDATION_H | 
| 8 |  |  | 
| 9 |  | #include <arith_uint256.h> | 
| 10 |  | #include <attributes.h> | 
| 11 |  | #include <chain.h> | 
| 12 |  | #include <checkqueue.h> | 
| 13 |  | #include <consensus/amount.h> | 
| 14 |  | #include <cuckoocache.h> | 
| 15 |  | #include <deploymentstatus.h> | 
| 16 |  | #include <kernel/chain.h> | 
| 17 |  | #include <kernel/chainparams.h> | 
| 18 |  | #include <kernel/chainstatemanager_opts.h> | 
| 19 |  | #include <kernel/cs_main.h> // IWYU pragma: export | 
| 20 |  | #include <node/blockstorage.h> | 
| 21 |  | #include <policy/feerate.h> | 
| 22 |  | #include <policy/packages.h> | 
| 23 |  | #include <policy/policy.h> | 
| 24 |  | #include <script/script_error.h> | 
| 25 |  | #include <script/sigcache.h> | 
| 26 |  | #include <sync.h> | 
| 27 |  | #include <txdb.h> | 
| 28 |  | #include <txmempool.h> | 
| 29 |  | #include <uint256.h> | 
| 30 |  | #include <util/byte_units.h> | 
| 31 |  | #include <util/check.h> | 
| 32 |  | #include <util/fs.h> | 
| 33 |  | #include <util/hasher.h> | 
| 34 |  | #include <util/result.h> | 
| 35 |  | #include <util/time.h> | 
| 36 |  | #include <util/translation.h> | 
| 37 |  | #include <versionbits.h> | 
| 38 |  |  | 
| 39 |  | #include <algorithm> | 
| 40 |  | #include <atomic> | 
| 41 |  | #include <cstdint> | 
| 42 |  | #include <map> | 
| 43 |  | #include <memory> | 
| 44 |  | #include <optional> | 
| 45 |  | #include <set> | 
| 46 |  | #include <span> | 
| 47 |  | #include <string> | 
| 48 |  | #include <type_traits> | 
| 49 |  | #include <utility> | 
| 50 |  | #include <vector> | 
| 51 |  |  | 
| 52 |  | class Chainstate; | 
| 53 |  | class CTxMemPool; | 
| 54 |  | class ChainstateManager; | 
| 55 |  | struct ChainTxData; | 
| 56 |  | class DisconnectedBlockTransactions; | 
| 57 |  | struct PrecomputedTransactionData; | 
| 58 |  | struct LockPoints; | 
| 59 |  | struct AssumeutxoData; | 
| 60 |  | namespace node { | 
| 61 |  | class SnapshotMetadata; | 
| 62 |  | } // namespace node | 
| 63 |  | namespace Consensus { | 
| 64 |  | struct Params; | 
| 65 |  | } // namespace Consensus | 
| 66 |  | namespace util { | 
| 67 |  | class SignalInterrupt; | 
| 68 |  | } // namespace util | 
| 69 |  |  | 
| 70 |  | /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pruned. */ | 
| 71 |  | static const unsigned int MIN_BLOCKS_TO_KEEP = 288; | 
| 72 |  | static const signed int DEFAULT_CHECKBLOCKS = 6; | 
| 73 |  | static constexpr int DEFAULT_CHECKLEVEL{3}; | 
| 74 |  | // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat) | 
| 75 |  | // At 1MB per block, 288 blocks = 288MB. | 
| 76 |  | // Add 15% for Undo data = 331MB | 
| 77 |  | // Add 20% for Orphan block rate = 397MB | 
| 78 |  | // We want the low water mark after pruning to be at least 397 MB and since we prune in | 
| 79 |  | // full block file chunks, we need the high water mark which triggers the prune to be | 
| 80 |  | // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB | 
| 81 |  | // Setting the target to >= 550 MiB will make it likely we can respect the target. | 
| 82 |  | static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024; | 
| 83 |  |  | 
| 84 |  | /** Maximum number of dedicated script-checking threads allowed */ | 
| 85 |  | static constexpr int MAX_SCRIPTCHECK_THREADS{15}; | 
| 86 |  |  | 
| 87 |  | /** Current sync state passed to tip changed callbacks. */ | 
| 88 |  | enum class SynchronizationState { | 
| 89 |  |     INIT_REINDEX, | 
| 90 |  |     INIT_DOWNLOAD, | 
| 91 |  |     POST_INIT | 
| 92 |  | }; | 
| 93 |  |  | 
| 94 |  | /** Documentation for argument 'checklevel'. */ | 
| 95 |  | extern const std::vector<std::string> CHECKLEVEL_DOC; | 
| 96 |  |  | 
| 97 |  | CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams); | 
| 98 |  |  | 
| 99 |  | bool FatalError(kernel::Notifications& notifications, BlockValidationState& state, const bilingual_str& message); | 
| 100 |  |  | 
| 101 |  | /** Prune block files up to a given height */ | 
| 102 |  | void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight); | 
| 103 |  |  | 
| 104 |  | /** | 
| 105 |  | * Validation result for a transaction evaluated by MemPoolAccept (single or package). | 
| 106 |  | * Here are the expected fields and properties of a result depending on its ResultType, applicable to | 
| 107 |  | * results returned from package evaluation: | 
| 108 |  | *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+ | 
| 109 |  | *| Field or property         |    VALID       |                 INVALID              |  MEMPOOL_ENTRY | DIFFERENT_WITNESS | | 
| 110 |  | *|                           |                |--------------------------------------|                |                   | | 
| 111 |  | *|                           |                | TX_RECONSIDERABLE |     Other        |                |                   | | 
| 112 |  | *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+ | 
| 113 |  | *| txid in mempool?          | yes            | no                | no*              | yes            | yes               | | 
| 114 |  | *| wtxid in mempool?         | yes            | no                | no*              | yes            | no                | | 
| 115 |  | *| m_state                   | yes, IsValid() | yes, IsInvalid()  | yes, IsInvalid() | yes, IsValid() | yes, IsValid()    | | 
| 116 |  | *| m_vsize                   | yes            | no                | no               | yes            | no                | | 
| 117 |  | *| m_base_fees               | yes            | no                | no               | yes            | no                | | 
| 118 |  | *| m_effective_feerate       | yes            | yes               | no               | no             | no                | | 
| 119 |  | *| m_wtxids_fee_calculations | yes            | yes               | no               | no             | no                | | 
| 120 |  | *| m_other_wtxid             | no             | no                | no               | no             | yes               | | 
| 121 |  | *+---------------------------+----------------+-------------------+------------------+----------------+-------------------+ | 
| 122 |  | * (*) Individual transaction acceptance doesn't return MEMPOOL_ENTRY and DIFFERENT_WITNESS. It returns | 
| 123 |  | * INVALID, with the errors txn-already-in-mempool and txn-same-nonwitness-data-in-mempool | 
| 124 |  | * respectively. In those cases, the txid or wtxid may be in the mempool for a TX_CONFLICT. | 
| 125 |  | */ | 
| 126 |  | struct MempoolAcceptResult { | 
| 127 |  |     /** Used to indicate the results of mempool validation. */ | 
| 128 |  |     enum class ResultType { | 
| 129 |  |         VALID, //!> Fully validated, valid. | 
| 130 |  |         INVALID, //!> Invalid. | 
| 131 |  |         MEMPOOL_ENTRY, //!> Valid, transaction was already in the mempool. | 
| 132 |  |         DIFFERENT_WITNESS, //!> Not validated. A same-txid-different-witness tx (see m_other_wtxid) already exists in the mempool and was not replaced. | 
| 133 |  |     }; | 
| 134 |  |     /** Result type. Present in all MempoolAcceptResults. */ | 
| 135 |  |     const ResultType m_result_type; | 
| 136 |  |  | 
| 137 |  |     /** Contains information about why the transaction failed. */ | 
| 138 |  |     const TxValidationState m_state; | 
| 139 |  |  | 
| 140 |  |     /** Mempool transactions replaced by the tx. */ | 
| 141 |  |     const std::list<CTransactionRef> m_replaced_transactions; | 
| 142 |  |     /** Virtual size as used by the mempool, calculated using serialized size and sigops. */ | 
| 143 |  |     const std::optional<int64_t> m_vsize; | 
| 144 |  |     /** Raw base fees in satoshis. */ | 
| 145 |  |     const std::optional<CAmount> m_base_fees; | 
| 146 |  |     /** The feerate at which this transaction was considered. This includes any fee delta added | 
| 147 |  |      * using prioritisetransaction (i.e. modified fees). If this transaction was submitted as a | 
| 148 |  |      * package, this is the package feerate, which may also include its descendants and/or | 
| 149 |  |      * ancestors (see m_wtxids_fee_calculations below). | 
| 150 |  |      */ | 
| 151 |  |     const std::optional<CFeeRate> m_effective_feerate; | 
| 152 |  |     /** Contains the wtxids of the transactions used for fee-related checks. Includes this | 
| 153 |  |      * transaction's wtxid and may include others if this transaction was validated as part of a | 
| 154 |  |      * package. This is not necessarily equivalent to the list of transactions passed to | 
| 155 |  |      * ProcessNewPackage(). | 
| 156 |  |      * Only present when m_result_type = ResultType::VALID. */ | 
| 157 |  |     const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations; | 
| 158 |  |  | 
| 159 |  |     /** The wtxid of the transaction in the mempool which has the same txid but different witness. */ | 
| 160 |  |     const std::optional<Wtxid> m_other_wtxid; | 
| 161 |  |  | 
| 162 | 80.2k |     static MempoolAcceptResult Failure(TxValidationState state) { | 
| 163 | 80.2k |         return MempoolAcceptResult(state); | 
| 164 | 80.2k |     } | 
| 165 |  |  | 
| 166 |  |     static MempoolAcceptResult FeeFailure(TxValidationState state, | 
| 167 |  |                                           CFeeRate effective_feerate, | 
| 168 | 147k |                                           const std::vector<Wtxid>& wtxids_fee_calculations) { | 
| 169 | 147k |         return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations); | 
| 170 | 147k |     } | 
| 171 |  |  | 
| 172 |  |     static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns, | 
| 173 |  |                                        int64_t vsize, | 
| 174 |  |                                        CAmount fees, | 
| 175 |  |                                        CFeeRate effective_feerate, | 
| 176 | 491k |                                        const std::vector<Wtxid>& wtxids_fee_calculations) { | 
| 177 | 491k |         return MempoolAcceptResult(std::move(replaced_txns), vsize, fees, | 
| 178 | 491k |                                    effective_feerate, wtxids_fee_calculations); | 
| 179 | 491k |     } | 
| 180 |  |  | 
| 181 | 0 |     static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) { | 
| 182 | 0 |         return MempoolAcceptResult(vsize, fees); | 
| 183 | 0 |     } | 
| 184 |  |  | 
| 185 | 0 |     static MempoolAcceptResult MempoolTxDifferentWitness(const Wtxid& other_wtxid) { | 
| 186 | 0 |         return MempoolAcceptResult(other_wtxid); | 
| 187 | 0 |     } | 
| 188 |  |  | 
| 189 |  | // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct. | 
| 190 |  | private: | 
| 191 |  |     /** Constructor for failure case */ | 
| 192 |  |     explicit MempoolAcceptResult(TxValidationState state) | 
| 193 | 80.2k |         : m_result_type(ResultType::INVALID), m_state(state) { | 
| 194 | 80.2k |             Assume(!state.IsValid()); // Can be invalid or error | Line | Count | Source |  | 118 | 80.2k | #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 195 | 80.2k |         } | 
| 196 |  |  | 
| 197 |  |     /** Constructor for success case */ | 
| 198 |  |     explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns, | 
| 199 |  |                                  int64_t vsize, | 
| 200 |  |                                  CAmount fees, | 
| 201 |  |                                  CFeeRate effective_feerate, | 
| 202 |  |                                  const std::vector<Wtxid>& wtxids_fee_calculations) | 
| 203 | 491k |         : m_result_type(ResultType::VALID), | 
| 204 | 491k |         m_replaced_transactions(std::move(replaced_txns)), | 
| 205 | 491k |         m_vsize{vsize}, | 
| 206 | 491k |         m_base_fees(fees), | 
| 207 | 491k |         m_effective_feerate(effective_feerate), | 
| 208 | 491k |         m_wtxids_fee_calculations(wtxids_fee_calculations) {} | 
| 209 |  |  | 
| 210 |  |     /** Constructor for fee-related failure case */ | 
| 211 |  |     explicit MempoolAcceptResult(TxValidationState state, | 
| 212 |  |                                  CFeeRate effective_feerate, | 
| 213 |  |                                  const std::vector<Wtxid>& wtxids_fee_calculations) | 
| 214 | 147k |         : m_result_type(ResultType::INVALID), | 
| 215 | 147k |         m_state(state), | 
| 216 | 147k |         m_effective_feerate(effective_feerate), | 
| 217 | 147k |         m_wtxids_fee_calculations(wtxids_fee_calculations) {} | 
| 218 |  |  | 
| 219 |  |     /** Constructor for already-in-mempool case. It wouldn't replace any transactions. */ | 
| 220 |  |     explicit MempoolAcceptResult(int64_t vsize, CAmount fees) | 
| 221 | 0 |         : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {} | 
| 222 |  |  | 
| 223 |  |     /** Constructor for witness-swapped case. */ | 
| 224 |  |     explicit MempoolAcceptResult(const Wtxid& other_wtxid) | 
| 225 | 0 |         : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {} | 
| 226 |  | }; | 
| 227 |  |  | 
| 228 |  | /** | 
| 229 |  | * Validation result for package mempool acceptance. | 
| 230 |  | */ | 
| 231 |  | struct PackageMempoolAcceptResult | 
| 232 |  | { | 
| 233 |  |     PackageValidationState m_state; | 
| 234 |  |     /** | 
| 235 |  |     * Map from wtxid to finished MempoolAcceptResults. The client is responsible | 
| 236 |  |     * for keeping track of the transaction objects themselves. If a result is not | 
| 237 |  |     * present, it means validation was unfinished for that transaction. If there | 
| 238 |  |     * was a package-wide error (see result in m_state), m_tx_results will be empty. | 
| 239 |  |     */ | 
| 240 |  |     std::map<Wtxid, MempoolAcceptResult> m_tx_results; | 
| 241 |  |  | 
| 242 |  |     explicit PackageMempoolAcceptResult(PackageValidationState state, | 
| 243 |  |                                         std::map<Wtxid, MempoolAcceptResult>&& results) | 
| 244 | 0 |         : m_state{state}, m_tx_results(std::move(results)) {} | 
| 245 |  |  | 
| 246 |  |     explicit PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, | 
| 247 |  |                                         std::map<Wtxid, MempoolAcceptResult>&& results) | 
| 248 | 0 |         : m_state{state}, m_tx_results(std::move(results)) {} | 
| 249 |  |  | 
| 250 |  |     /** Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult */ | 
| 251 |  |     explicit PackageMempoolAcceptResult(const Wtxid& wtxid, const MempoolAcceptResult& result) | 
| 252 | 0 |         : m_tx_results{ {wtxid, result} } {} | 
| 253 |  | }; | 
| 254 |  |  | 
| 255 |  | /** | 
| 256 |  |  * Try to add a transaction to the mempool. This is an internal function and is exposed only for testing. | 
| 257 |  |  * Client code should use ChainstateManager::ProcessTransaction() | 
| 258 |  |  * | 
| 259 |  |  * @param[in]  active_chainstate  Reference to the active chainstate. | 
| 260 |  |  * @param[in]  tx                 The transaction to submit for mempool acceptance. | 
| 261 |  |  * @param[in]  accept_time        The timestamp for adding the transaction to the mempool. | 
| 262 |  |  *                                It is also used to determine when the entry expires. | 
| 263 |  |  * @param[in]  bypass_limits      When true, don't enforce mempool fee and capacity limits, | 
| 264 |  |  *                                and set entry_sequence to zero. | 
| 265 |  |  * @param[in]  test_accept        When true, run validation checks but don't submit to mempool. | 
| 266 |  |  * | 
| 267 |  |  * @returns a MempoolAcceptResult indicating whether the transaction was accepted/rejected with reason. | 
| 268 |  |  */ | 
| 269 |  | MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx, | 
| 270 |  |                                        int64_t accept_time, bool bypass_limits, bool test_accept) | 
| 271 |  |     EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 272 |  |  | 
| 273 |  | /** | 
| 274 |  | * Validate (and maybe submit) a package to the mempool. See doc/policy/packages.md for full details | 
| 275 |  | * on package validation rules. | 
| 276 |  | * @param[in]    test_accept         When true, run validation checks but don't submit to mempool. | 
| 277 |  | * @param[in]    client_maxfeerate    If exceeded by an individual transaction, rest of (sub)package evaluation is aborted. | 
| 278 |  | *                                   Only for sanity checks against local submission of transactions. | 
| 279 |  | * @returns a PackageMempoolAcceptResult which includes a MempoolAcceptResult for each transaction. | 
| 280 |  | * If a transaction fails, validation will exit early and some results may be missing. It is also | 
| 281 |  | * possible for the package to be partially submitted. | 
| 282 |  | */ | 
| 283 |  | PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool, | 
| 284 |  |                                                    const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate) | 
| 285 |  |                                                    EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 286 |  |  | 
| 287 |  | /* Mempool validation helper functions */ | 
| 288 |  |  | 
| 289 |  | /** | 
| 290 |  |  * Check if transaction will be final in the next block to be created. | 
| 291 |  |  */ | 
| 292 |  | bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 293 |  |  | 
| 294 |  | /** | 
| 295 |  |  * Calculate LockPoints required to check if transaction will be BIP68 final in the next block | 
| 296 |  |  * to be created on top of tip. | 
| 297 |  |  * | 
| 298 |  |  * @param[in]   tip             Chain tip for which tx sequence locks are calculated. For | 
| 299 |  |  *                              example, the tip of the current active chain. | 
| 300 |  |  * @param[in]   coins_view      Any CCoinsView that provides access to the relevant coins for | 
| 301 |  |  *                              checking sequence locks. For example, it can be a CCoinsViewCache | 
| 302 |  |  *                              that isn't connected to anything but contains all the relevant | 
| 303 |  |  *                              coins, or a CCoinsViewMemPool that is connected to the | 
| 304 |  |  *                              mempool and chainstate UTXO set. In the latter case, the caller | 
| 305 |  |  *                              is responsible for holding the appropriate locks to ensure that | 
| 306 |  |  *                              calls to GetCoin() return correct coins. | 
| 307 |  |  * @param[in]   tx              The transaction being evaluated. | 
| 308 |  |  * | 
| 309 |  |  * @returns The resulting height and time calculated and the hash of the block needed for | 
| 310 |  |  *          calculation, or std::nullopt if there is an error. | 
| 311 |  |  */ | 
| 312 |  | std::optional<LockPoints> CalculateLockPointsAtTip( | 
| 313 |  |     CBlockIndex* tip, | 
| 314 |  |     const CCoinsView& coins_view, | 
| 315 |  |     const CTransaction& tx); | 
| 316 |  |  | 
| 317 |  | /** | 
| 318 |  |  * Check if transaction will be BIP68 final in the next block to be created on top of tip. | 
| 319 |  |  * @param[in]   tip             Chain tip to check tx sequence locks against. For example, | 
| 320 |  |  *                              the tip of the current active chain. | 
| 321 |  |  * @param[in]   lock_points     LockPoints containing the height and time at which this | 
| 322 |  |  *                              transaction is final. | 
| 323 |  |  * Simulates calling SequenceLocks() with data from the tip passed in. | 
| 324 |  |  * The LockPoints should not be considered valid if CheckSequenceLocksAtTip returns false. | 
| 325 |  |  */ | 
| 326 |  | bool CheckSequenceLocksAtTip(CBlockIndex* tip, | 
| 327 |  |                              const LockPoints& lock_points); | 
| 328 |  |  | 
| 329 |  | /** | 
| 330 |  |  * Closure representing one script verification | 
| 331 |  |  * Note that this stores references to the spending transaction | 
| 332 |  |  */ | 
| 333 |  | class CScriptCheck | 
| 334 |  | { | 
| 335 |  | private: | 
| 336 |  |     CTxOut m_tx_out; | 
| 337 |  |     const CTransaction *ptxTo; | 
| 338 |  |     unsigned int nIn; | 
| 339 |  |     unsigned int nFlags; | 
| 340 |  |     bool cacheStore; | 
| 341 |  |     PrecomputedTransactionData *txdata; | 
| 342 |  |     SignatureCache* m_signature_cache; | 
| 343 |  |  | 
| 344 |  | public: | 
| 345 |  |     CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, SignatureCache& signature_cache, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) : | 
| 346 | 998k |         m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), txdata(txdataIn), m_signature_cache(&signature_cache) { } | 
| 347 |  |  | 
| 348 |  |     CScriptCheck(const CScriptCheck&) = delete; | 
| 349 |  |     CScriptCheck& operator=(const CScriptCheck&) = delete; | 
| 350 | 0 |     CScriptCheck(CScriptCheck&&) = default; | 
| 351 | 0 |     CScriptCheck& operator=(CScriptCheck&&) = default; | 
| 352 |  |  | 
| 353 |  |     std::optional<std::pair<ScriptError, std::string>> operator()(); | 
| 354 |  | }; | 
| 355 |  |  | 
| 356 |  | // CScriptCheck is used a lot in std::vector, make sure that's efficient | 
| 357 |  | static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>); | 
| 358 |  | static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>); | 
| 359 |  | static_assert(std::is_nothrow_destructible_v<CScriptCheck>); | 
| 360 |  |  | 
| 361 |  | /** | 
| 362 |  |  * Convenience class for initializing and passing the script execution cache | 
| 363 |  |  * and signature cache. | 
| 364 |  |  */ | 
| 365 |  | class ValidationCache | 
| 366 |  | { | 
| 367 |  | private: | 
| 368 |  |     //! Pre-initialized hasher to avoid having to recreate it for every hash calculation. | 
| 369 |  |     CSHA256 m_script_execution_cache_hasher; | 
| 370 |  |  | 
| 371 |  | public: | 
| 372 |  |     CuckooCache::cache<uint256, SignatureCacheHasher> m_script_execution_cache; | 
| 373 |  |     SignatureCache m_signature_cache; | 
| 374 |  |  | 
| 375 |  |     ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes); | 
| 376 |  |  | 
| 377 |  |     ValidationCache(const ValidationCache&) = delete; | 
| 378 |  |     ValidationCache& operator=(const ValidationCache&) = delete; | 
| 379 |  |  | 
| 380 |  |     //! Return a copy of the pre-initialized hasher. | 
| 381 | 1.09M |     CSHA256 ScriptExecutionCacheHasher() const { return m_script_execution_cache_hasher; } | 
| 382 |  | }; | 
| 383 |  |  | 
| 384 |  | /** Functions for validating blocks and updating the block tree */ | 
| 385 |  |  | 
| 386 |  | /** Context-independent validity checks */ | 
| 387 |  | bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true); | 
| 388 |  |  | 
| 389 |  | /** | 
| 390 |  |  * Verify a block, including transactions. | 
| 391 |  |  * | 
| 392 |  |  * @param[in]   block       The block we want to process. Must connect to the | 
| 393 |  |  *                          current tip. | 
| 394 |  |  * @param[in]   chainstate  The chainstate to connect to. | 
| 395 |  |  * @param[in]   check_pow   perform proof-of-work check, nBits in the header | 
| 396 |  |  *                          is always checked | 
| 397 |  |  * @param[in]   check_merkle_root check the merkle root | 
| 398 |  |  * | 
| 399 |  |  * @return Valid or Invalid state. This doesn't currently return an Error state, | 
| 400 |  |  *         and shouldn't unless there is something wrong with the existing | 
| 401 |  |  *         chainstate. (This is different from functions like AcceptBlock which | 
| 402 |  |  *         can fail trying to save new data.) | 
| 403 |  |  * | 
| 404 |  |  * For signets the challenge verification is skipped when check_pow is false. | 
| 405 |  |  */ | 
| 406 |  | BlockValidationState TestBlockValidity( | 
| 407 |  |     Chainstate& chainstate, | 
| 408 |  |     const CBlock& block, | 
| 409 |  |     bool check_pow, | 
| 410 |  |     bool check_merkle_root) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 411 |  |  | 
| 412 |  | /** Check with the proof of work on each blockheader matches the value in nBits */ | 
| 413 |  | bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams); | 
| 414 |  |  | 
| 415 |  | /** Check if a block has been mutated (with respect to its merkle root and witness commitments). */ | 
| 416 |  | bool IsBlockMutated(const CBlock& block, bool check_witness_root); | 
| 417 |  |  | 
| 418 |  | /** Return the sum of the claimed work on a given set of headers. No verification of PoW is done. */ | 
| 419 |  | arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers); | 
| 420 |  |  | 
| 421 |  | enum class VerifyDBResult { | 
| 422 |  |     SUCCESS, | 
| 423 |  |     CORRUPTED_BLOCK_DB, | 
| 424 |  |     INTERRUPTED, | 
| 425 |  |     SKIPPED_L3_CHECKS, | 
| 426 |  |     SKIPPED_MISSING_BLOCKS, | 
| 427 |  | }; | 
| 428 |  |  | 
| 429 |  | /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */ | 
| 430 |  | class CVerifyDB | 
| 431 |  | { | 
| 432 |  | private: | 
| 433 |  |     kernel::Notifications& m_notifications; | 
| 434 |  |  | 
| 435 |  | public: | 
| 436 |  |     explicit CVerifyDB(kernel::Notifications& notifications); | 
| 437 |  |     ~CVerifyDB(); | 
| 438 |  |     [[nodiscard]] VerifyDBResult VerifyDB( | 
| 439 |  |         Chainstate& chainstate, | 
| 440 |  |         const Consensus::Params& consensus_params, | 
| 441 |  |         CCoinsView& coinsview, | 
| 442 |  |         int nCheckLevel, | 
| 443 |  |         int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 444 |  | }; | 
| 445 |  |  | 
| 446 |  | enum DisconnectResult | 
| 447 |  | { | 
| 448 |  |     DISCONNECT_OK,      // All good. | 
| 449 |  |     DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block. | 
| 450 |  |     DISCONNECT_FAILED   // Something else went wrong. | 
| 451 |  | }; | 
| 452 |  |  | 
| 453 |  | class ConnectTrace; | 
| 454 |  |  | 
| 455 |  | /** @see Chainstate::FlushStateToDisk */ | 
| 456 |  | inline constexpr std::array FlushStateModeNames{"NONE", "IF_NEEDED", "PERIODIC", "ALWAYS"}; | 
| 457 |  | enum class FlushStateMode: uint8_t { | 
| 458 |  |     NONE, | 
| 459 |  |     IF_NEEDED, | 
| 460 |  |     PERIODIC, | 
| 461 |  |     ALWAYS | 
| 462 |  | }; | 
| 463 |  |  | 
| 464 |  | /** | 
| 465 |  |  * A convenience class for constructing the CCoinsView* hierarchy used | 
| 466 |  |  * to facilitate access to the UTXO set. | 
| 467 |  |  * | 
| 468 |  |  * This class consists of an arrangement of layered CCoinsView objects, | 
| 469 |  |  * preferring to store and retrieve coins in memory via `m_cacheview` but | 
| 470 |  |  * ultimately falling back on cache misses to the canonical store of UTXOs on | 
| 471 |  |  * disk, `m_dbview`. | 
| 472 |  |  */ | 
| 473 |  | class CoinsViews { | 
| 474 |  |  | 
| 475 |  | public: | 
| 476 |  |     //! The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk. | 
| 477 |  |     //! All unspent coins reside in this store. | 
| 478 |  |     CCoinsViewDB m_dbview GUARDED_BY(cs_main); | 
| 479 |  |  | 
| 480 |  |     //! This view wraps access to the leveldb instance and handles read errors gracefully. | 
| 481 |  |     CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main); | 
| 482 |  |  | 
| 483 |  |     //! This is the top layer of the cache hierarchy - it keeps as many coins in memory as | 
| 484 |  |     //! can fit per the dbcache setting. | 
| 485 |  |     std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main); | 
| 486 |  |  | 
| 487 |  |     //! This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it | 
| 488 |  |     //! *does not* create a CCoinsViewCache instance by default. This is done separately because the | 
| 489 |  |     //! presence of the cache has implications on whether or not we're allowed to flush the cache's | 
| 490 |  |     //! state to disk, which should not be done until the health of the database is verified. | 
| 491 |  |     //! | 
| 492 |  |     //! All arguments forwarded onto CCoinsViewDB. | 
| 493 |  |     CoinsViews(DBParams db_params, CoinsViewOptions options); | 
| 494 |  |  | 
| 495 |  |     //! Initialize the CCoinsViewCache member. | 
| 496 |  |     void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 497 |  | }; | 
| 498 |  |  | 
| 499 |  | enum class CoinsCacheSizeState | 
| 500 |  | { | 
| 501 |  |     //! The coins cache is in immediate need of a flush. | 
| 502 |  |     CRITICAL = 2, | 
| 503 |  |     //! The cache is at >= 90% capacity. | 
| 504 |  |     LARGE = 1, | 
| 505 |  |     OK = 0 | 
| 506 |  | }; | 
| 507 |  |  | 
| 508 |  | constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept | 
| 509 | 790k | { | 
| 510 |  |     // No periodic flush needed if at least this much space is free | 
| 511 | 790k |     constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES{int64_t(10_MiB)}; | 
| 512 | 790k |     return std::max((total_space * 9) / 10, | 
| 513 | 790k |                     total_space - MAX_BLOCK_COINSDB_USAGE_BYTES); | 
| 514 | 790k | } | 
| 515 |  |  | 
| 516 |  | /** | 
| 517 |  |  * Chainstate stores and provides an API to update our local knowledge of the | 
| 518 |  |  * current best chain. | 
| 519 |  |  * | 
| 520 |  |  * Eventually, the API here is targeted at being exposed externally as a | 
| 521 |  |  * consumable library, so any functions added must only call | 
| 522 |  |  * other class member functions, pure functions in other parts of the consensus | 
| 523 |  |  * library, callbacks via the validation interface, or read/write-to-disk | 
| 524 |  |  * functions (eventually this will also be via callbacks). | 
| 525 |  |  * | 
| 526 |  |  * Anything that is contingent on the current tip of the chain is stored here, | 
| 527 |  |  * whereas block information and metadata independent of the current tip is | 
| 528 |  |  * kept in `BlockManager`. | 
| 529 |  |  */ | 
| 530 |  | class Chainstate | 
| 531 |  | { | 
| 532 |  | protected: | 
| 533 |  |     /** | 
| 534 |  |      * The ChainState Mutex | 
| 535 |  |      * A lock that must be held when modifying this ChainState - held in ActivateBestChain() and | 
| 536 |  |      * InvalidateBlock() | 
| 537 |  |      */ | 
| 538 |  |     Mutex m_chainstate_mutex; | 
| 539 |  |  | 
| 540 |  |     //! Optional mempool that is kept in sync with the chain. | 
| 541 |  |     //! Only the active chainstate has a mempool. | 
| 542 |  |     CTxMemPool* m_mempool; | 
| 543 |  |  | 
| 544 |  |     //! Manages the UTXO set, which is a reflection of the contents of `m_chain`. | 
| 545 |  |     std::unique_ptr<CoinsViews> m_coins_views; | 
| 546 |  |  | 
| 547 |  |     //! This toggle exists for use when doing background validation for UTXO | 
| 548 |  |     //! snapshots. | 
| 549 |  |     //! | 
| 550 |  |     //! In the expected case, it is set once the background validation chain reaches the | 
| 551 |  |     //! same height as the base of the snapshot and its UTXO set is found to hash to | 
| 552 |  |     //! the expected assumeutxo value. It signals that we should no longer connect | 
| 553 |  |     //! blocks to the background chainstate. When set on the background validation | 
| 554 |  |     //! chainstate, it signifies that we have fully validated the snapshot chainstate. | 
| 555 |  |     //! | 
| 556 |  |     //! In the unlikely case that the snapshot chainstate is found to be invalid, this | 
| 557 |  |     //! is set to true on the snapshot chainstate. | 
| 558 |  |     bool m_disabled GUARDED_BY(::cs_main) {false}; | 
| 559 |  |  | 
| 560 |  |     //! Cached result of LookupBlockIndex(*m_from_snapshot_blockhash) | 
| 561 |  |     mutable const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr}; | 
| 562 |  |  | 
| 563 |  |     std::atomic_bool m_prev_script_checks_logged{true}; | 
| 564 |  |  | 
| 565 |  | public: | 
| 566 |  |     //! Reference to a BlockManager instance which itself is shared across all | 
| 567 |  |     //! Chainstate instances. | 
| 568 |  |     node::BlockManager& m_blockman; | 
| 569 |  |  | 
| 570 |  |     //! The chainstate manager that owns this chainstate. The reference is | 
| 571 |  |     //! necessary so that this instance can check whether it is the active | 
| 572 |  |     //! chainstate within deeply nested method calls. | 
| 573 |  |     ChainstateManager& m_chainman; | 
| 574 |  |  | 
| 575 |  |     explicit Chainstate( | 
| 576 |  |         CTxMemPool* mempool, | 
| 577 |  |         node::BlockManager& blockman, | 
| 578 |  |         ChainstateManager& chainman, | 
| 579 |  |         std::optional<uint256> from_snapshot_blockhash = std::nullopt); | 
| 580 |  |  | 
| 581 |  |     //! Return the current role of the chainstate. See `ChainstateManager` | 
| 582 |  |     //! documentation for a description of the different types of chainstates. | 
| 583 |  |     //! | 
| 584 |  |     //! @sa ChainstateRole | 
| 585 |  |     ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 586 |  |  | 
| 587 |  |     /** | 
| 588 |  |      * Initialize the CoinsViews UTXO set database management data structures. The in-memory | 
| 589 |  |      * cache is initialized separately. | 
| 590 |  |      * | 
| 591 |  |      * All parameters forwarded to CoinsViews. | 
| 592 |  |      */ | 
| 593 |  |     void InitCoinsDB( | 
| 594 |  |         size_t cache_size_bytes, | 
| 595 |  |         bool in_memory, | 
| 596 |  |         bool should_wipe, | 
| 597 |  |         fs::path leveldb_name = "chainstate"); | 
| 598 |  |  | 
| 599 |  |     //! Initialize the in-memory coins cache (to be done after the health of the on-disk database | 
| 600 |  |     //! is verified). | 
| 601 |  |     void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 602 |  |  | 
| 603 |  |     //! @returns whether or not the CoinsViews object has been fully initialized and we can | 
| 604 |  |     //!          safely flush this object to disk. | 
| 605 |  |     bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 606 | 842k |     { | 
| 607 | 842k |         AssertLockHeld(::cs_main); | Line | Count | Source |  | 137 | 842k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) | 
 | 
| 608 | 842k |         return m_coins_views && m_coins_views->m_cacheview; | 
| 609 | 842k |     } | 
| 610 |  |  | 
| 611 |  |     //! The current chain of blockheaders we consult and build on. | 
| 612 |  |     //! @see CChain, CBlockIndex. | 
| 613 |  |     CChain m_chain; | 
| 614 |  |  | 
| 615 |  |     /** | 
| 616 |  |      * The blockhash which is the base of the snapshot this chainstate was created from. | 
| 617 |  |      * | 
| 618 |  |      * std::nullopt if this chainstate was not created from a snapshot. | 
| 619 |  |      */ | 
| 620 |  |     const std::optional<uint256> m_from_snapshot_blockhash; | 
| 621 |  |  | 
| 622 |  |     /** | 
| 623 |  |      * The base of the snapshot this chainstate was created from. | 
| 624 |  |      * | 
| 625 |  |      * nullptr if this chainstate was not created from a snapshot. | 
| 626 |  |      */ | 
| 627 |  |     const CBlockIndex* SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 628 |  |  | 
| 629 |  |     /** | 
| 630 |  |      * The set of all CBlockIndex entries that have as much work as our current | 
| 631 |  |      * tip or more, and transaction data needed to be validated (with | 
| 632 |  |      * BLOCK_VALID_TRANSACTIONS for each block and its parents back to the | 
| 633 |  |      * genesis block or an assumeutxo snapshot block). Entries may be failed, | 
| 634 |  |      * though, and pruning nodes may be missing the data for the block. | 
| 635 |  |      */ | 
| 636 |  |     std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates; | 
| 637 |  |  | 
| 638 |  |     //! @returns A reference to the in-memory cache of the UTXO set. | 
| 639 |  |     CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 640 | 6.20M |     { | 
| 641 | 6.20M |         AssertLockHeld(::cs_main); | Line | Count | Source |  | 137 | 6.20M | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) | 
 | 
| 642 | 6.20M |         Assert(m_coins_views); | Line | Count | Source |  | 106 | 6.20M | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 643 | 6.20M |         return *Assert(m_coins_views->m_cacheview); | Line | Count | Source |  | 106 | 6.20M | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 644 | 6.20M |     } | 
| 645 |  |  | 
| 646 |  |     //! @returns A reference to the on-disk UTXO set database. | 
| 647 |  |     CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 648 | 153k |     { | 
| 649 | 153k |         AssertLockHeld(::cs_main); | Line | Count | Source |  | 137 | 153k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) | 
 | 
| 650 | 153k |         return Assert(m_coins_views)->m_dbview; | Line | Count | Source |  | 106 | 307k | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 651 | 153k |     } | 
| 652 |  |  | 
| 653 |  |     //! @returns A pointer to the mempool. | 
| 654 |  |     CTxMemPool* GetMempool() | 
| 655 | 2.87M |     { | 
| 656 | 2.87M |         return m_mempool; | 
| 657 | 2.87M |     } | 
| 658 |  |  | 
| 659 |  |     //! @returns A reference to a wrapped view of the in-memory UTXO set that | 
| 660 |  |     //!     handles disk read errors gracefully. | 
| 661 |  |     CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 662 | 0 |     { | 
| 663 | 0 |         AssertLockHeld(::cs_main); | Line | Count | Source |  | 137 | 0 | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) | 
 | 
| 664 | 0 |         return Assert(m_coins_views)->m_catcherview; | Line | Count | Source |  | 106 | 0 | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 665 | 0 |     } | 
| 666 |  |  | 
| 667 |  |     //! Destructs all objects related to accessing the UTXO set. | 
| 668 | 0 |     void ResetCoinsViews() { m_coins_views.reset(); } | 
| 669 |  |  | 
| 670 |  |     //! Does this chainstate have a UTXO set attached? | 
| 671 | 0 |     bool HasCoinsViews() const { return (bool)m_coins_views; } | 
| 672 |  |  | 
| 673 |  |     //! The cache size of the on-disk coins view. | 
| 674 |  |     size_t m_coinsdb_cache_size_bytes{0}; | 
| 675 |  |  | 
| 676 |  |     //! The cache size of the in-memory coins view. | 
| 677 |  |     size_t m_coinstip_cache_size_bytes{0}; | 
| 678 |  |  | 
| 679 |  |     //! Resize the CoinsViews caches dynamically and flush state to disk. | 
| 680 |  |     //! @returns true unless an error occurred during the flush. | 
| 681 |  |     bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) | 
| 682 |  |         EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 683 |  |  | 
| 684 |  |     /** | 
| 685 |  |      * Update the on-disk chain state. | 
| 686 |  |      * The caches and indexes are flushed depending on the mode we're called with | 
| 687 |  |      * if they're too large, if it's been a while since the last write, | 
| 688 |  |      * or always and in all cases if we're in prune mode and are deleting files. | 
| 689 |  |      * | 
| 690 |  |      * If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything | 
| 691 |  |      * besides checking if we need to prune. | 
| 692 |  |      * | 
| 693 |  |      * @returns true unless a system error occurred | 
| 694 |  |      */ | 
| 695 |  |     bool FlushStateToDisk( | 
| 696 |  |         BlockValidationState& state, | 
| 697 |  |         FlushStateMode mode, | 
| 698 |  |         int nManualPruneHeight = 0); | 
| 699 |  |  | 
| 700 |  |     //! Unconditionally flush all changes to disk. | 
| 701 |  |     void ForceFlushStateToDisk(); | 
| 702 |  |  | 
| 703 |  |     //! Prune blockfiles from the disk if necessary and then flush chainstate changes | 
| 704 |  |     //! if we pruned. | 
| 705 |  |     void PruneAndFlush(); | 
| 706 |  |  | 
| 707 |  |     /** | 
| 708 |  |      * Find the best known block, and make it the tip of the block chain. The | 
| 709 |  |      * result is either failure or an activated best chain. pblock is either | 
| 710 |  |      * nullptr or a pointer to a block that is already loaded (to avoid loading | 
| 711 |  |      * it again from disk). | 
| 712 |  |      * | 
| 713 |  |      * ActivateBestChain is split into steps (see ActivateBestChainStep) so that | 
| 714 |  |      * we avoid holding cs_main for an extended period of time; the length of this | 
| 715 |  |      * call may be quite long during reindexing or a substantial reorg. | 
| 716 |  |      * | 
| 717 |  |      * May not be called with cs_main held. May not be called in a | 
| 718 |  |      * validationinterface callback. | 
| 719 |  |      * | 
| 720 |  |      * Note that if this is called while a snapshot chainstate is active, and if | 
| 721 |  |      * it is called on a background chainstate whose tip has reached the base block | 
| 722 |  |      * of the snapshot, its execution will take *MINUTES* while it hashes the | 
| 723 |  |      * background UTXO set to verify the assumeutxo value the snapshot was activated | 
| 724 |  |      * with. `cs_main` will be held during this time. | 
| 725 |  |      * | 
| 726 |  |      * @returns true unless a system error occurred | 
| 727 |  |      */ | 
| 728 |  |     bool ActivateBestChain( | 
| 729 |  |         BlockValidationState& state, | 
| 730 |  |         std::shared_ptr<const CBlock> pblock = nullptr) | 
| 731 |  |         EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) | 
| 732 |  |         LOCKS_EXCLUDED(::cs_main); | 
| 733 |  |  | 
| 734 |  |     // Block (dis)connection on a given view: | 
| 735 |  |     DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view) | 
| 736 |  |         EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 737 |  |     bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex, | 
| 738 |  |                       CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 739 |  |  | 
| 740 |  |     // Apply the effects of a block disconnection on the UTXO set. | 
| 741 |  |     bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); | 
| 742 |  |  | 
| 743 |  |     // Manual block validity manipulation: | 
| 744 |  |     /** Mark a block as precious and reorganize. | 
| 745 |  |      * | 
| 746 |  |      * May not be called in a validationinterface callback. | 
| 747 |  |      */ | 
| 748 |  |     bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex) | 
| 749 |  |         EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) | 
| 750 |  |         LOCKS_EXCLUDED(::cs_main); | 
| 751 |  |  | 
| 752 |  |     /** Mark a block as invalid. */ | 
| 753 |  |     bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex) | 
| 754 |  |         EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex) | 
| 755 |  |         LOCKS_EXCLUDED(::cs_main); | 
| 756 |  |  | 
| 757 |  |     /** Set invalidity status to all descendants of a block */ | 
| 758 |  |     void SetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 759 |  |  | 
| 760 |  |     /** Remove invalidity status from a block, its descendants and ancestors and reconsider them for activation */ | 
| 761 |  |     void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 762 |  |  | 
| 763 |  |     /** Replay blocks that aren't fully applied to the database. */ | 
| 764 |  |     bool ReplayBlocks(); | 
| 765 |  |  | 
| 766 |  |     /** Whether the chain state needs to be redownloaded due to lack of witness data */ | 
| 767 |  |     [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 768 |  |     /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */ | 
| 769 |  |     bool LoadGenesisBlock(); | 
| 770 |  |  | 
| 771 |  |     void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 772 |  |  | 
| 773 |  |     void PruneBlockIndexCandidates(); | 
| 774 |  |  | 
| 775 |  |     void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 776 |  |  | 
| 777 |  |     /** Find the last common block of this chain and a locator. */ | 
| 778 |  |     const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 779 |  |  | 
| 780 |  |     /** Update the chain tip based on database information, i.e. CoinsTip()'s best block. */ | 
| 781 |  |     bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 782 |  |  | 
| 783 |  |     //! Dictates whether we need to flush the cache to disk or not. | 
| 784 |  |     //! | 
| 785 |  |     //! @return the state of the size of the coins cache. | 
| 786 |  |     CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 787 |  |  | 
| 788 |  |     CoinsCacheSizeState GetCoinsCacheSizeState( | 
| 789 |  |         size_t max_coins_cache_size_bytes, | 
| 790 |  |         size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 791 |  |  | 
| 792 |  |     std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 793 |  |  | 
| 794 |  |     //! Indirection necessary to make lock annotations work with an optional mempool. | 
| 795 |  |     RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs) | 
| 796 | 82.9k |     { | 
| 797 | 82.9k |         return m_mempool ? &m_mempool->cs : nullptr0; | 
| 798 | 82.9k |     } | 
| 799 |  |  | 
| 800 |  | protected: | 
| 801 |  |     bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); | 
| 802 |  |     bool ConnectTip( | 
| 803 |  |         BlockValidationState& state, | 
| 804 |  |         CBlockIndex* pindexNew, | 
| 805 |  |         std::shared_ptr<const CBlock> block_to_connect, | 
| 806 |  |         ConnectTrace& connectTrace, | 
| 807 |  |         DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); | 
| 808 |  |  | 
| 809 |  |     void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 810 |  |     CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 811 |  |  | 
| 812 |  |     bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 813 |  |  | 
| 814 |  |     void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 815 |  |     void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 816 |  |  | 
| 817 |  |     /** | 
| 818 |  |      * Make mempool consistent after a reorg, by re-adding or recursively erasing | 
| 819 |  |      * disconnected block transactions from the mempool, and also removing any | 
| 820 |  |      * other transactions from the mempool that are no longer valid given the new | 
| 821 |  |      * tip/height. | 
| 822 |  |      * | 
| 823 |  |      * Note: we assume that disconnectpool only contains transactions that are NOT | 
| 824 |  |      * confirmed in the current chain nor already in the mempool (otherwise, | 
| 825 |  |      * in-mempool descendants of such transactions would be removed). | 
| 826 |  |      * | 
| 827 |  |      * Passing fAddToMempool=false will skip trying to add the transactions back, | 
| 828 |  |      * and instead just erase from the mempool as needed. | 
| 829 |  |      */ | 
| 830 |  |     void MaybeUpdateMempoolForReorg( | 
| 831 |  |         DisconnectedBlockTransactions& disconnectpool, | 
| 832 |  |         bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs); | 
| 833 |  |  | 
| 834 |  |     /** Check warning conditions and do some notifications on new chain tip set. */ | 
| 835 |  |     void UpdateTip(const CBlockIndex* pindexNew) | 
| 836 |  |         EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 837 |  |  | 
| 838 |  |     NodeClock::time_point m_next_write{NodeClock::time_point::max()}; | 
| 839 |  |  | 
| 840 |  |     /** | 
| 841 |  |      * In case of an invalid snapshot, rename the coins leveldb directory so | 
| 842 |  |      * that it can be examined for issue diagnosis. | 
| 843 |  |      */ | 
| 844 |  |     [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 845 |  |  | 
| 846 |  |     friend ChainstateManager; | 
| 847 |  | }; | 
| 848 |  |  | 
| 849 |  | enum class SnapshotCompletionResult { | 
| 850 |  |     SUCCESS, | 
| 851 |  |     SKIPPED, | 
| 852 |  |  | 
| 853 |  |     // Expected assumeutxo configuration data is not found for the height of the | 
| 854 |  |     // base block. | 
| 855 |  |     MISSING_CHAINPARAMS, | 
| 856 |  |  | 
| 857 |  |     // Failed to generate UTXO statistics (to check UTXO set hash) for the background | 
| 858 |  |     // chainstate. | 
| 859 |  |     STATS_FAILED, | 
| 860 |  |  | 
| 861 |  |     // The UTXO set hash of the background validation chainstate does not match | 
| 862 |  |     // the one expected by assumeutxo chainparams. | 
| 863 |  |     HASH_MISMATCH, | 
| 864 |  |  | 
| 865 |  |     // The blockhash of the current tip of the background validation chainstate does | 
| 866 |  |     // not match the one expected by the snapshot chainstate. | 
| 867 |  |     BASE_BLOCKHASH_MISMATCH, | 
| 868 |  | }; | 
| 869 |  |  | 
| 870 |  | /** | 
| 871 |  |  * Provides an interface for creating and interacting with one or two | 
| 872 |  |  * chainstates: an IBD chainstate generated by downloading blocks, and | 
| 873 |  |  * an optional snapshot chainstate loaded from a UTXO snapshot. Managed | 
| 874 |  |  * chainstates can be maintained at different heights simultaneously. | 
| 875 |  |  * | 
| 876 |  |  * This class provides abstractions that allow the retrieval of the current | 
| 877 |  |  * most-work chainstate ("Active") as well as chainstates which may be in | 
| 878 |  |  * background use to validate UTXO snapshots. | 
| 879 |  |  * | 
| 880 |  |  * Definitions: | 
| 881 |  |  * | 
| 882 |  |  * *IBD chainstate*: a chainstate whose current state has been "fully" | 
| 883 |  |  *   validated by the initial block download process. | 
| 884 |  |  * | 
| 885 |  |  * *Snapshot chainstate*: a chainstate populated by loading in an | 
| 886 |  |  *    assumeutxo UTXO snapshot. | 
| 887 |  |  * | 
| 888 |  |  * *Active chainstate*: the chainstate containing the current most-work | 
| 889 |  |  *    chain. Consulted by most parts of the system (net_processing, | 
| 890 |  |  *    wallet) as a reflection of the current chain and UTXO set. | 
| 891 |  |  *    This may either be an IBD chainstate or a snapshot chainstate. | 
| 892 |  |  * | 
| 893 |  |  * *Background IBD chainstate*: an IBD chainstate for which the | 
| 894 |  |  *    IBD process is happening in the background while use of the | 
| 895 |  |  *    active (snapshot) chainstate allows the rest of the system to function. | 
| 896 |  |  */ | 
| 897 |  | class ChainstateManager | 
| 898 |  | { | 
| 899 |  | private: | 
| 900 |  |     //! The chainstate used under normal operation (i.e. "regular" IBD) or, if | 
| 901 |  |     //! a snapshot is in use, for background validation. | 
| 902 |  |     //! | 
| 903 |  |     //! Its contents (including on-disk data) will be deleted *upon shutdown* | 
| 904 |  |     //! after background validation of the snapshot has completed. We do not | 
| 905 |  |     //! free the chainstate contents immediately after it finishes validation | 
| 906 |  |     //! to cautiously avoid a case where some other part of the system is still | 
| 907 |  |     //! using this pointer (e.g. net_processing). | 
| 908 |  |     //! | 
| 909 |  |     //! Once this pointer is set to a corresponding chainstate, it will not | 
| 910 |  |     //! be reset until init.cpp:Shutdown(). | 
| 911 |  |     //! | 
| 912 |  |     //! It is important for the pointer to not be deleted until shutdown, | 
| 913 |  |     //! because cs_main is not always held when the pointer is accessed, for | 
| 914 |  |     //! example when calling ActivateBestChain, so there's no way you could | 
| 915 |  |     //! prevent code from using the pointer while deleting it. | 
| 916 |  |     std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main); | 
| 917 |  |  | 
| 918 |  |     //! A chainstate initialized on the basis of a UTXO snapshot. If this is | 
| 919 |  |     //! non-null, it is always our active chainstate. | 
| 920 |  |     //! | 
| 921 |  |     //! Once this pointer is set to a corresponding chainstate, it will not | 
| 922 |  |     //! be reset until init.cpp:Shutdown(). | 
| 923 |  |     //! | 
| 924 |  |     //! It is important for the pointer to not be deleted until shutdown, | 
| 925 |  |     //! because cs_main is not always held when the pointer is accessed, for | 
| 926 |  |     //! example when calling ActivateBestChain, so there's no way you could | 
| 927 |  |     //! prevent code from using the pointer while deleting it. | 
| 928 |  |     std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main); | 
| 929 |  |  | 
| 930 |  |     //! Points to either the ibd or snapshot chainstate; indicates our | 
| 931 |  |     //! most-work chain. | 
| 932 |  |     Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr}; | 
| 933 |  |  | 
| 934 |  |     CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr}; | 
| 935 |  |  | 
| 936 |  |     /** The last header for which a headerTip notification was issued. */ | 
| 937 |  |     CBlockIndex* m_last_notified_header GUARDED_BY(GetMutex()){nullptr}; | 
| 938 |  |  | 
| 939 |  |     bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex()); | 
| 940 |  |  | 
| 941 |  |     //! Internal helper for ActivateSnapshot(). | 
| 942 |  |     //! | 
| 943 |  |     //! De-serialization of a snapshot that is created with | 
| 944 |  |     //! the dumptxoutset RPC. | 
| 945 |  |     //! To reduce space the serialization format of the snapshot avoids | 
| 946 |  |     //! duplication of tx hashes. The code takes advantage of the guarantee by | 
| 947 |  |     //! leveldb that keys are lexicographically sorted. | 
| 948 |  |     [[nodiscard]] util::Result<void> PopulateAndValidateSnapshot( | 
| 949 |  |         Chainstate& snapshot_chainstate, | 
| 950 |  |         AutoFile& coins_file, | 
| 951 |  |         const node::SnapshotMetadata& metadata); | 
| 952 |  |  | 
| 953 |  |     /** | 
| 954 |  |      * If a block header hasn't already been seen, call CheckBlockHeader on it, ensure | 
| 955 |  |      * that it doesn't descend from an invalid block, and then add it to m_block_index. | 
| 956 |  |      * Caller must set min_pow_checked=true in order to add a new header to the | 
| 957 |  |      * block index (permanent memory storage), indicating that the header is | 
| 958 |  |      * known to be part of a sufficiently high-work chain (anti-dos check). | 
| 959 |  |      */ | 
| 960 |  |     bool AcceptBlockHeader( | 
| 961 |  |         const CBlockHeader& block, | 
| 962 |  |         BlockValidationState& state, | 
| 963 |  |         CBlockIndex** ppindex, | 
| 964 |  |         bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 965 |  |     friend Chainstate; | 
| 966 |  |  | 
| 967 |  |     /** Most recent headers presync progress update, for rate-limiting. */ | 
| 968 |  |     MockableSteadyClock::time_point m_last_presync_update GUARDED_BY(GetMutex()){}; | 
| 969 |  |  | 
| 970 |  |     //! Return true if a chainstate is considered usable. | 
| 971 |  |     //! | 
| 972 |  |     //! This is false when a background validation chainstate has completed its | 
| 973 |  |     //! validation of an assumed-valid chainstate, or when a snapshot | 
| 974 |  |     //! chainstate has been found to be invalid. | 
| 975 | 26.5M |     bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { | 
| 976 | 26.5M |         return cs && !cs->m_disabled10.6M; | 
| 977 | 26.5M |     } | 
| 978 |  |  | 
| 979 |  |     //! A queue for script verifications that have to be performed by worker threads. | 
| 980 |  |     CCheckQueue<CScriptCheck> m_script_check_queue; | 
| 981 |  |  | 
| 982 |  |     //! Timers and counters used for benchmarking validation in both background | 
| 983 |  |     //! and active chainstates. | 
| 984 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_check{}; | 
| 985 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_forks{}; | 
| 986 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_connect{}; | 
| 987 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_verify{}; | 
| 988 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_undo{}; | 
| 989 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_index{}; | 
| 990 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_total{}; | 
| 991 |  |     int64_t GUARDED_BY(::cs_main) num_blocks_total{0}; | 
| 992 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total{}; | 
| 993 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_flush{}; | 
| 994 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate{}; | 
| 995 |  |     SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect{}; | 
| 996 |  |  | 
| 997 |  | public: | 
| 998 |  |     using Options = kernel::ChainstateManagerOpts; | 
| 999 |  |  | 
| 1000 |  |     explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options); | 
| 1001 |  |  | 
| 1002 |  |     //! Function to restart active indexes; set dynamically to avoid a circular | 
| 1003 |  |     //! dependency on `base/index.cpp`. | 
| 1004 |  |     std::function<void()> snapshot_download_completed = std::function<void()>(); | 
| 1005 |  |  | 
| 1006 | 6.12M |     const CChainParams& GetParams() const { return m_options.chainparams; } | 
| 1007 | 20.4M |     const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); } | 
| 1008 |  |     bool ShouldCheckBlockIndex() const; | 
| 1009 | 7.34M |     const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }| Line | Count | Source |  | 106 | 7.34M | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 1010 | 76.3k |     const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }| Line | Count | Source |  | 106 | 76.3k | #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) | 
 | 
| 1011 | 201k |     kernel::Notifications& GetNotifications() const { return m_options.notifications; }; | 
| 1012 |  |  | 
| 1013 |  |     /** | 
| 1014 |  |      * Make various assertions about the state of the block index. | 
| 1015 |  |      * | 
| 1016 |  |      * By default this only executes fully when using the Regtest chain; see: m_options.check_block_index. | 
| 1017 |  |      */ | 
| 1018 |  |     void CheckBlockIndex() const; | 
| 1019 |  |  | 
| 1020 |  |     /** | 
| 1021 |  |      * Alias for ::cs_main. | 
| 1022 |  |      * Should be used in new code to make it easier to make ::cs_main a member | 
| 1023 |  |      * of this class. | 
| 1024 |  |      * Generally, methods of this class should be annotated to require this | 
| 1025 |  |      * mutex. This will make calling code more verbose, but also help to: | 
| 1026 |  |      * - Clarify that the method will acquire a mutex that heavily affects | 
| 1027 |  |      *   overall performance. | 
| 1028 |  |      * - Force call sites to think how long they need to acquire the mutex to | 
| 1029 |  |      *   get consistent results. | 
| 1030 |  |      */ | 
| 1031 | 1.84M |     RecursiveMutex& GetMutex() const LOCK_RETURNED(::cs_main) { return ::cs_main; } | 
| 1032 |  |  | 
| 1033 |  |     const util::SignalInterrupt& m_interrupt; | 
| 1034 |  |     const Options m_options; | 
| 1035 |  |     //! A single BlockManager instance is shared across each constructed | 
| 1036 |  |     //! chainstate to avoid duplicating block metadata. | 
| 1037 |  |     node::BlockManager m_blockman; | 
| 1038 |  |  | 
| 1039 |  |     ValidationCache m_validation_cache; | 
| 1040 |  |  | 
| 1041 |  |     /** | 
| 1042 |  |      * Whether initial block download has ended and IsInitialBlockDownload | 
| 1043 |  |      * should return false from now on. | 
| 1044 |  |      * | 
| 1045 |  |      * Mutable because we need to be able to mark IsInitialBlockDownload() | 
| 1046 |  |      * const, which latches this for caching purposes. | 
| 1047 |  |      */ | 
| 1048 |  |     mutable std::atomic<bool> m_cached_finished_ibd{false}; | 
| 1049 |  |  | 
| 1050 |  |     /** | 
| 1051 |  |      * Every received block is assigned a unique and increasing identifier, so we | 
| 1052 |  |      * know which one to give priority in case of a fork. | 
| 1053 |  |      */ | 
| 1054 |  |     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ | 
| 1055 |  |     int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1; | 
| 1056 |  |     /** Decreasing counter (used by subsequent preciousblock calls). */ | 
| 1057 |  |     int32_t nBlockReverseSequenceId = -1; | 
| 1058 |  |     /** chainwork for the last block that preciousblock has been applied to. */ | 
| 1059 |  |     arith_uint256 nLastPreciousChainwork = 0; | 
| 1060 |  |  | 
| 1061 |  |     // Reset the memory-only sequence counters we use to track block arrival | 
| 1062 |  |     // (used by tests to reset state) | 
| 1063 |  |     void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 1064 | 0 |     { | 
| 1065 | 0 |         AssertLockHeld(::cs_main); | 
| 1066 | 0 |         nBlockSequenceId = 1; | 
| 1067 | 0 |         nBlockReverseSequenceId = -1; | 
| 1068 | 0 |     } | 
| 1069 |  |  | 
| 1070 |  |  | 
| 1071 |  |     /** Best header we've seen so far for which the block is not known to be invalid | 
| 1072 |  |         (used, among others, for getheaders queries' starting points). | 
| 1073 |  |         In case of multiple best headers with the same work, it could point to any | 
| 1074 |  |         because CBlockIndexWorkComparator tiebreaker rules are not applied. */ | 
| 1075 |  |     CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr}; | 
| 1076 |  |  | 
| 1077 |  |     //! The total number of bytes available for us to use across all in-memory | 
| 1078 |  |     //! coins caches. This will be split somehow across chainstates. | 
| 1079 |  |     size_t m_total_coinstip_cache{0}; | 
| 1080 |  |     // | 
| 1081 |  |     //! The total number of bytes available for us to use across all leveldb | 
| 1082 |  |     //! coins databases. This will be split somehow across chainstates. | 
| 1083 |  |     size_t m_total_coinsdb_cache{0}; | 
| 1084 |  |  | 
| 1085 |  |     //! Instantiate a new chainstate. | 
| 1086 |  |     //! | 
| 1087 |  |     //! @param[in] mempool              The mempool to pass to the chainstate | 
| 1088 |  |     //                                  constructor | 
| 1089 |  |     Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1090 |  |  | 
| 1091 |  |     //! Get all chainstates currently being used. | 
| 1092 |  |     std::vector<Chainstate*> GetAll(); | 
| 1093 |  |  | 
| 1094 |  |     //! Construct and activate a Chainstate on the basis of UTXO snapshot data. | 
| 1095 |  |     //! | 
| 1096 |  |     //! Steps: | 
| 1097 |  |     //! | 
| 1098 |  |     //! - Initialize an unused Chainstate. | 
| 1099 |  |     //! - Load its `CoinsViews` contents from `coins_file`. | 
| 1100 |  |     //! - Verify that the hash of the resulting coinsdb matches the expected hash | 
| 1101 |  |     //!   per assumeutxo chain parameters. | 
| 1102 |  |     //! - Wait for our headers chain to include the base block of the snapshot. | 
| 1103 |  |     //! - "Fast forward" the tip of the new chainstate to the base of the snapshot. | 
| 1104 |  |     //! - Move the new chainstate to `m_snapshot_chainstate` and make it our | 
| 1105 |  |     //!   ChainstateActive(). | 
| 1106 |  |     [[nodiscard]] util::Result<CBlockIndex*> ActivateSnapshot( | 
| 1107 |  |         AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory); | 
| 1108 |  |  | 
| 1109 |  |     //! Once the background validation chainstate has reached the height which | 
| 1110 |  |     //! is the base of the UTXO snapshot in use, compare its coins to ensure | 
| 1111 |  |     //! they match those expected by the snapshot. | 
| 1112 |  |     //! | 
| 1113 |  |     //! If the coins match (expected), then mark the validation chainstate for | 
| 1114 |  |     //! deletion and continue using the snapshot chainstate as active. | 
| 1115 |  |     //! Otherwise, revert to using the ibd chainstate and shutdown. | 
| 1116 |  |     SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1117 |  |  | 
| 1118 |  |     //! Returns nullptr if no snapshot has been loaded. | 
| 1119 |  |     const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1120 |  |  | 
| 1121 |  |     //! The most-work chain. | 
| 1122 |  |     Chainstate& ActiveChainstate() const; | 
| 1123 | 25.4M |     CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; } | 
| 1124 | 29.1k |     int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); } | 
| 1125 | 84.4k |     CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); } | 
| 1126 |  |  | 
| 1127 |  |     //! The state of a background sync (for net processing) | 
| 1128 | 5.16M |     bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { | 
| 1129 | 5.16M |         return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get())0; | 
| 1130 | 5.16M |     } | 
| 1131 |  |  | 
| 1132 |  |     //! The tip of the background sync chain | 
| 1133 | 0 |     const CBlockIndex* GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { | 
| 1134 | 0 |         return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() : nullptr; | 
| 1135 | 0 |     } | 
| 1136 |  |  | 
| 1137 |  |     node::BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 1138 | 51.2k |     { | 
| 1139 | 51.2k |         AssertLockHeld(::cs_main); | Line | Count | Source |  | 137 | 51.2k | #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) | 
 | 
| 1140 | 51.2k |         return m_blockman.m_block_index; | 
| 1141 | 51.2k |     } | 
| 1142 |  |  | 
| 1143 |  |     /** | 
| 1144 |  |      * Track versionbit status | 
| 1145 |  |      */ | 
| 1146 |  |     mutable VersionBitsCache m_versionbitscache; | 
| 1147 |  |  | 
| 1148 |  |     //! @returns true if a snapshot-based chainstate is in use. Also implies | 
| 1149 |  |     //!          that a background validation chainstate is also in use. | 
| 1150 |  |     bool IsSnapshotActive() const; | 
| 1151 |  |  | 
| 1152 |  |     std::optional<uint256> SnapshotBlockhash() const; | 
| 1153 |  |  | 
| 1154 |  |     //! Is there a snapshot in use and has it been fully validated? | 
| 1155 |  |     bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) | 
| 1156 | 0 |     { | 
| 1157 | 0 |         return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled; | 
| 1158 | 0 |     } | 
| 1159 |  |  | 
| 1160 |  |     /** Check whether we are doing an initial block download (synchronizing from disk or network) */ | 
| 1161 |  |     bool IsInitialBlockDownload() const; | 
| 1162 |  |  | 
| 1163 |  |     /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */ | 
| 1164 |  |     double GuessVerificationProgress(const CBlockIndex* pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()); | 
| 1165 |  |  | 
| 1166 |  |     /** | 
| 1167 |  |      * Import blocks from an external file | 
| 1168 |  |      * | 
| 1169 |  |      * During reindexing, this function is called for each block file (datadir/blocks/blk?????.dat). | 
| 1170 |  |      * It reads all blocks contained in the given file and attempts to process them (add them to the | 
| 1171 |  |      * block index). The blocks may be out of order within each file and across files. Often this | 
| 1172 |  |      * function reads a block but finds that its parent hasn't been read yet, so the block can't be | 
| 1173 |  |      * processed yet. The function will add an entry to the blocks_with_unknown_parent map (which is | 
| 1174 |  |      * passed as an argument), so that when the block's parent is later read and processed, this | 
| 1175 |  |      * function can re-read the child block from disk and process it. | 
| 1176 |  |      * | 
| 1177 |  |      * Because a block's parent may be in a later file, not just later in the same file, the | 
| 1178 |  |      * blocks_with_unknown_parent map must be passed in and out with each call. It's a multimap, | 
| 1179 |  |      * rather than just a map, because multiple blocks may have the same parent (when chain splits | 
| 1180 |  |      * or stale blocks exist). It maps from parent-hash to child-disk-position. | 
| 1181 |  |      * | 
| 1182 |  |      * This function can also be used to read blocks from user-specified block files using the | 
| 1183 |  |      * -loadblock= option. There's no unknown-parent tracking, so the last two arguments are omitted. | 
| 1184 |  |      * | 
| 1185 |  |      * | 
| 1186 |  |      * @param[in]     file_in                       File containing blocks to read | 
| 1187 |  |      * @param[in]     dbp                           (optional) Disk block position (only for reindex) | 
| 1188 |  |      * @param[in,out] blocks_with_unknown_parent    (optional) Map of disk positions for blocks with | 
| 1189 |  |      *                                              unknown parent, key is parent block hash | 
| 1190 |  |      *                                              (only used for reindex) | 
| 1191 |  |      * */ | 
| 1192 |  |     void LoadExternalBlockFile( | 
| 1193 |  |         AutoFile& file_in, | 
| 1194 |  |         FlatFilePos* dbp = nullptr, | 
| 1195 |  |         std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr); | 
| 1196 |  |  | 
| 1197 |  |     /** | 
| 1198 |  |      * Process an incoming block. This only returns after the best known valid | 
| 1199 |  |      * block is made active. Note that it does not, however, guarantee that the | 
| 1200 |  |      * specific block passed to it has been checked for validity! | 
| 1201 |  |      * | 
| 1202 |  |      * If you want to *possibly* get feedback on whether block is valid, you must | 
| 1203 |  |      * install a CValidationInterface (see validationinterface.h) - this will have | 
| 1204 |  |      * its BlockChecked method called whenever *any* block completes validation. | 
| 1205 |  |      * | 
| 1206 |  |      * Note that we guarantee that either the proof-of-work is valid on block, or | 
| 1207 |  |      * (and possibly also) BlockChecked will have been called. | 
| 1208 |  |      * | 
| 1209 |  |      * May not be called in a validationinterface callback. | 
| 1210 |  |      * | 
| 1211 |  |      * @param[in]   block The block we want to process. | 
| 1212 |  |      * @param[in]   force_processing Process this block even if unrequested; used for non-network block sources. | 
| 1213 |  |      * @param[in]   min_pow_checked  True if proof-of-work anti-DoS checks have | 
| 1214 |  |      *                               been done by caller for headers chain | 
| 1215 |  |      *                               (note: only affects headers acceptance; if | 
| 1216 |  |      *                               block header is already present in block | 
| 1217 |  |      *                               index then this parameter has no effect) | 
| 1218 |  |      * @param[out]  new_block A boolean which is set to indicate if the block was first received via this call | 
| 1219 |  |      * @returns     If the block was processed, independently of block validity | 
| 1220 |  |      */ | 
| 1221 |  |     bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main); | 
| 1222 |  |  | 
| 1223 |  |     /** | 
| 1224 |  |      * Process incoming block headers. | 
| 1225 |  |      * | 
| 1226 |  |      * May not be called in a | 
| 1227 |  |      * validationinterface callback. | 
| 1228 |  |      * | 
| 1229 |  |      * @param[in]  headers The block headers themselves | 
| 1230 |  |      * @param[in]  min_pow_checked  True if proof-of-work anti-DoS checks have been done by caller for headers chain | 
| 1231 |  |      * @param[out] state This may be set to an Error state if any error occurred processing them | 
| 1232 |  |      * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers | 
| 1233 |  |      * @returns false if AcceptBlockHeader fails on any of the headers, true otherwise (including if headers were already known) | 
| 1234 |  |      */ | 
| 1235 |  |     bool ProcessNewBlockHeaders(std::span<const CBlockHeader> headers, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main); | 
| 1236 |  |  | 
| 1237 |  |     /** | 
| 1238 |  |      * Sufficiently validate a block for disk storage (and store on disk). | 
| 1239 |  |      * | 
| 1240 |  |      * @param[in]   pblock          The block we want to process. | 
| 1241 |  |      * @param[in]   fRequested      Whether we requested this block from a | 
| 1242 |  |      *                              peer. | 
| 1243 |  |      * @param[in]   dbp             The location on disk, if we are importing | 
| 1244 |  |      *                              this block from prior storage. | 
| 1245 |  |      * @param[in]   min_pow_checked True if proof-of-work anti-DoS checks have | 
| 1246 |  |      *                              been done by caller for headers chain | 
| 1247 |  |      * | 
| 1248 |  |      * @param[out]  state       The state of the block validation. | 
| 1249 |  |      * @param[out]  ppindex     Optional return parameter to get the | 
| 1250 |  |      *                          CBlockIndex pointer for this block. | 
| 1251 |  |      * @param[out]  fNewBlock   Optional return parameter to indicate if the | 
| 1252 |  |      *                          block is new to our storage. | 
| 1253 |  |      * | 
| 1254 |  |      * @returns   False if the block or header is invalid, or if saving to disk fails (likely a fatal error); true otherwise. | 
| 1255 |  |      */ | 
| 1256 |  |     bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 1257 |  |  | 
| 1258 |  |     void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 1259 |  |  | 
| 1260 |  |     /** | 
| 1261 |  |      * Try to add a transaction to the memory pool. | 
| 1262 |  |      * | 
| 1263 |  |      * @param[in]  tx              The transaction to submit for mempool acceptance. | 
| 1264 |  |      * @param[in]  test_accept     When true, run validation checks but don't submit to mempool. | 
| 1265 |  |      */ | 
| 1266 |  |     [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false) | 
| 1267 |  |         EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 1268 |  |  | 
| 1269 |  |     //! Load the block tree and coins database from disk, initializing state if we're running with -reindex | 
| 1270 |  |     bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main); | 
| 1271 |  |  | 
| 1272 |  |     //! Check to see if caches are out of balance and if so, call | 
| 1273 |  |     //! ResizeCoinsCaches() as needed. | 
| 1274 |  |     void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1275 |  |  | 
| 1276 |  |     /** Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks. */ | 
| 1277 |  |     void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const; | 
| 1278 |  |  | 
| 1279 |  |     /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */ | 
| 1280 |  |     std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const; | 
| 1281 |  |  | 
| 1282 |  |     /** This is used by net_processing to report pre-synchronization progress of headers, as | 
| 1283 |  |      *  headers are not yet fed to validation during that time, but validation is (for now) | 
| 1284 |  |      *  responsible for logging and signalling through NotifyHeaderTip, so it needs this | 
| 1285 |  |      *  information. */ | 
| 1286 |  |     void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp); | 
| 1287 |  |  | 
| 1288 |  |     //! When starting up, search the datadir for a chainstate based on a UTXO | 
| 1289 |  |     //! snapshot that is in the process of being validated. | 
| 1290 |  |     bool DetectSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1291 |  |  | 
| 1292 |  |     void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1293 |  |  | 
| 1294 |  |     //! Remove the snapshot-based chainstate and all on-disk artifacts. | 
| 1295 |  |     //! Used when reindex{-chainstate} is called during snapshot use. | 
| 1296 |  |     [[nodiscard]] bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1297 |  |  | 
| 1298 |  |     //! Switch the active chainstate to one based on a UTXO snapshot that was loaded | 
| 1299 |  |     //! previously. | 
| 1300 |  |     Chainstate& ActivateExistingSnapshot(uint256 base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1301 |  |  | 
| 1302 |  |     //! If we have validated a snapshot chain during this runtime, copy its | 
| 1303 |  |     //! chainstate directory over to the main `chainstate` location, completing | 
| 1304 |  |     //! validation of the snapshot. | 
| 1305 |  |     //! | 
| 1306 |  |     //! If the cleanup succeeds, the caller will need to ensure chainstates are | 
| 1307 |  |     //! reinitialized, since ResetChainstates() will be called before leveldb | 
| 1308 |  |     //! directories are moved or deleted. | 
| 1309 |  |     //! | 
| 1310 |  |     //! @sa node/chainstate:LoadChainstate() | 
| 1311 |  |     bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1312 |  |  | 
| 1313 |  |     //! @returns the chainstate that indexes should consult when ensuring that an | 
| 1314 |  |     //!   index is synced with a chain where we can expect block index entries to have | 
| 1315 |  |     //!   BLOCK_HAVE_DATA beneath the tip. | 
| 1316 |  |     //! | 
| 1317 |  |     //!   In other words, give us the chainstate for which we can reasonably expect | 
| 1318 |  |     //!   that all blocks beneath the tip have been indexed. In practice this means | 
| 1319 |  |     //!   when using an assumed-valid chainstate based upon a snapshot, return only the | 
| 1320 |  |     //!   fully validated chain. | 
| 1321 |  |     Chainstate& GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1322 |  |  | 
| 1323 |  |     //! Return the [start, end] (inclusive) of block heights we can prune. | 
| 1324 |  |     //! | 
| 1325 |  |     //! start > end is possible, meaning no blocks can be pruned. | 
| 1326 |  |     std::pair<int, int> GetPruneRange( | 
| 1327 |  |         const Chainstate& chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1328 |  |  | 
| 1329 |  |     //! Return the height of the base block of the snapshot in use, if one exists, else | 
| 1330 |  |     //! nullopt. | 
| 1331 |  |     std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1332 |  |  | 
| 1333 |  |     //! If, due to invalidation / reconsideration of blocks, the previous | 
| 1334 |  |     //! best header is no longer valid / guaranteed to be the most-work | 
| 1335 |  |     //! header in our block-index not known to be invalid, recalculate it. | 
| 1336 |  |     void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main); | 
| 1337 |  |  | 
| 1338 | 25.0k |     CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; } | 
| 1339 |  |  | 
| 1340 |  |     ~ChainstateManager(); | 
| 1341 |  | }; | 
| 1342 |  |  | 
| 1343 |  | /** Deployment* info via ChainstateManager */ | 
| 1344 |  | template<typename DEP> | 
| 1345 |  | bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep) | 
| 1346 | 2.36M | { | 
| 1347 | 2.36M |     return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache); | 
| 1348 | 2.36M | } | 
| 1349 |  |  | 
| 1350 |  | template<typename DEP> | 
| 1351 |  | bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep) | 
| 1352 | 12.4M | { | 
| 1353 | 12.4M |     return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache); | 
| 1354 | 12.4M | } | 
| 1355 |  |  | 
| 1356 |  | template<typename DEP> | 
| 1357 |  | bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep) | 
| 1358 | 0 | { | 
| 1359 | 0 |     return DeploymentEnabled(chainman.GetConsensus(), dep); | 
| 1360 | 0 | } Unexecuted instantiation: _Z17DeploymentEnabledIN9Consensus16BuriedDeploymentEEbRK17ChainstateManagerT_Unexecuted instantiation: _Z17DeploymentEnabledIN9Consensus13DeploymentPosEEbRK17ChainstateManagerT_ | 
| 1361 |  |  | 
| 1362 |  | /** Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) */ | 
| 1363 |  | bool IsBIP30Repeat(const CBlockIndex& block_index); | 
| 1364 |  |  | 
| 1365 |  | /** Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) */ | 
| 1366 |  | bool IsBIP30Unspendable(const uint256& block_hash, int block_height); | 
| 1367 |  |  | 
| 1368 |  | #endif // BITCOIN_VALIDATION_H |