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