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