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