Coverage Report

Created: 2026-07-08 14:14

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