LCOV - code coverage report
Current view: top level - src - validation.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 33 86 38.4 %
Date: 2023-11-10 23:46:46 Functions: 21 48 43.8 %
Branches: 5 28 17.9 %

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

Generated by: LCOV version 1.14