LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 0 95 0.0 %
Date: 2024-01-03 14:57:27 Functions: 0 51 0.0 %
Branches: 0 32 0.0 %

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

Generated by: LCOV version 1.14