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