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