LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 69 78 88.5 %
Date: 2026-06-25 07:23:51 Functions: 53 59 89.8 %

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

Generated by: LCOV version 1.16