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