LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 59 78 75.6 %
Date: 2023-09-26 12:08:55 Functions: 34 46 73.9 %

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

Generated by: LCOV version 1.14