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