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