Coverage Report

Created: 2026-09-14 20:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/validation.cpp
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
#include <bitcoin-build-config.h> // IWYU pragma: keep
7
8
#include <validation.h>
9
10
#include <arith_uint256.h>
11
#include <chain.h>
12
#include <checkqueue.h>
13
#include <clientversion.h>
14
#include <consensus/amount.h>
15
#include <consensus/consensus.h>
16
#include <consensus/merkle.h>
17
#include <consensus/tx_check.h>
18
#include <consensus/tx_verify.h>
19
#include <consensus/validation.h>
20
#include <cuckoocache.h>
21
#include <flatfile.h>
22
#include <hash.h>
23
#include <kernel/chainparams.h>
24
#include <kernel/coinstats.h>
25
#include <kernel/disconnected_transactions.h>
26
#include <kernel/mempool_entry.h>
27
#include <kernel/messagestartchars.h>
28
#include <kernel/notifications_interface.h>
29
#include <kernel/types.h>
30
#include <kernel/warning.h>
31
#include <logging/timer.h>
32
#include <node/blockstorage.h>
33
#include <node/utxo_snapshot.h>
34
#include <policy/ephemeral_policy.h>
35
#include <policy/policy.h>
36
#include <policy/rbf.h>
37
#include <policy/settings.h>
38
#include <policy/truc_policy.h>
39
#include <pow.h>
40
#include <primitives/block.h>
41
#include <primitives/transaction.h>
42
#include <random.h>
43
#include <script/script.h>
44
#include <script/sigcache.h>
45
#include <signet.h>
46
#include <tinyformat.h>
47
#include <txdb.h>
48
#include <txmempool.h>
49
#include <uint256.h>
50
#include <undo.h>
51
#include <util/byte_units.h>
52
#include <util/check.h>
53
#include <util/fs.h>
54
#include <util/fs_helpers.h>
55
#include <util/hasher.h>
56
#include <util/log.h>
57
#include <util/moneystr.h>
58
#include <util/rbf.h>
59
#include <util/result.h>
60
#include <util/signalinterrupt.h>
61
#include <util/strencodings.h>
62
#include <util/string.h>
63
#include <util/threadpool.h>
64
#include <util/time.h>
65
#include <util/trace.h>
66
#include <util/translation.h>
67
#include <validationinterface.h>
68
69
#include <algorithm>
70
#include <cassert>
71
#include <chrono>
72
#include <deque>
73
#include <numeric>
74
#include <optional>
75
#include <ranges>
76
#include <span>
77
#include <string>
78
#include <tuple>
79
#include <utility>
80
81
using kernel::CCoinsStats;
82
using kernel::ChainstateRole;
83
using kernel::CoinStatsHashType;
84
using kernel::ComputeUTXOStats;
85
using kernel::Notifications;
86
87
using fsbridge::FopenFn;
88
using node::BlockManager;
89
using node::BlockMap;
90
using node::CBlockIndexHeightOnlyComparator;
91
using node::CBlockIndexWorkComparator;
92
using node::SnapshotMetadata;
93
94
/** Time window to wait between writing blocks/block index and chainstate to disk.
95
 *  Randomize writing time inside the window to prevent a situation where the
96
 *  network over time settles into a few cohorts of synchronized writers.
97
*/
98
static constexpr auto DATABASE_WRITE_INTERVAL_MIN{50min};
99
static constexpr auto DATABASE_WRITE_INTERVAL_MAX{70min};
100
/** Maximum age of our tip for us to be considered current for fee estimation */
101
static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
102
const std::vector<std::string> CHECKLEVEL_DOC {
103
    "level 0 reads the blocks from disk",
104
    "level 1 verifies block validity",
105
    "level 2 verifies undo data",
106
    "level 3 checks disconnection of tip blocks",
107
    "level 4 tries to reconnect the blocks",
108
    "each level includes the checks of the previous levels",
109
};
110
/** The number of blocks to keep below the deepest prune lock.
111
 *  There is nothing special about this number. It is higher than what we
112
 *  expect to see in regular mainnet reorgs, but not so high that it would
113
 *  noticeably interfere with the pruning mechanism.
114
 * */
115
static constexpr int PRUNE_LOCK_BUFFER{10};
116
117
// Return whether the completed full flush should compact chainstate
118
static bool ShouldCompactChainstate(bool in_ibd)
119
1.46k
{
120
1.46k
    static constexpr uint32_t flush_ratio{320}; // Roughly every 2 weeks with hourly flushes
121
1.46k
    return !in_ibd && FastRandomContext().randrange(flush_ratio) == 0;
122
1.46k
}
123
124
TRACEPOINT_SEMAPHORE(validation, block_connected);
125
TRACEPOINT_SEMAPHORE(utxocache, flush);
126
TRACEPOINT_SEMAPHORE(mempool, replaced);
127
TRACEPOINT_SEMAPHORE(mempool, rejected);
128
129
const CBlockIndex* Chainstate::FindForkInGlobalIndex(const CBlockLocator& locator) const
130
1.95k
{
131
1.95k
    AssertLockHeld(cs_main);
132
133
    // Find the latest block common to locator and chain - we expect that
134
    // locator.vHave is sorted descending by height.
135
2.94k
    for (const uint256& hash : locator.vHave) {
136
2.94k
        const CBlockIndex* pindex{m_blockman.LookupBlockIndex(hash)};
137
2.94k
        if (pindex) {
138
2.08k
            if (m_chain.Contains(*pindex)) {
139
1.94k
                return pindex;
140
1.94k
            }
141
136
            if (pindex->GetAncestor(m_chain.Height()) == m_chain.Tip()) {
142
10
                return m_chain.Tip();
143
10
            }
144
136
        }
145
2.94k
    }
146
3
    return m_chain.Genesis();
147
1.95k
}
148
149
bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
150
                       const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
151
                       bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
152
                       ValidationCache& validation_cache,
153
                       std::vector<CScriptCheck>* pvChecks = nullptr)
154
                       EXCLUSIVE_LOCKS_REQUIRED(cs_main);
155
156
bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx)
157
50.3k
{
158
50.3k
    AssertLockHeld(cs_main);
159
160
    // CheckFinalTxAtTip() uses active_chain_tip.Height()+1 to evaluate
161
    // nLockTime because when IsFinalTx() is called within
162
    // AcceptBlock(), the height of the block *being*
163
    // evaluated is what is used. Thus if we want to know if a
164
    // transaction can be part of the *next* block, we need to call
165
    // IsFinalTx() with one more than active_chain_tip.Height().
166
50.3k
    const int nBlockHeight = active_chain_tip.nHeight + 1;
167
168
    // BIP113 requires that time-locked transactions have nLockTime set to
169
    // less than the median time of the previous block they're contained in.
170
    // When the next block is created its previous block will be the current
171
    // chain tip, so we use that to calculate the median time passed to
172
    // IsFinalTx().
173
50.3k
    const int64_t nBlockTime{active_chain_tip.GetMedianTimePast()};
174
175
50.3k
    return IsFinalTx(tx, nBlockHeight, nBlockTime);
176
50.3k
}
177
178
namespace {
179
/**
180
 * A helper which calculates heights of inputs of a given transaction.
181
 *
182
 * @param[in] tip    The current chain tip. If an input belongs to a mempool
183
 *                   transaction, we assume it will be confirmed in the next block.
184
 * @param[in] coins  Any CCoinsView that provides access to the relevant coins.
185
 * @param[in] tx     The transaction being evaluated.
186
 *
187
 * @returns A vector of input heights or nullopt, in case of an error.
188
 */
189
std::optional<std::vector<int>> CalculatePrevHeights(
190
    const CBlockIndex& tip,
191
    const CCoinsView& coins,
192
    const CTransaction& tx)
193
47.1k
{
194
47.1k
    std::vector<int> prev_heights;
195
47.1k
    prev_heights.resize(tx.vin.size());
196
117k
    for (size_t i = 0; i < tx.vin.size(); ++i) {
197
69.9k
        if (auto coin{coins.GetCoin(tx.vin[i].prevout)}) {
198
69.9k
            prev_heights[i] = coin->nHeight == MEMPOOL_HEIGHT
199
69.9k
                              ? tip.nHeight + 1 // Assume all mempool transaction confirm in the next block.
200
69.9k
                              : coin->nHeight;
201
69.9k
        } else {
202
0
            LogInfo("ERROR: %s: Missing input %d in transaction \'%s\'\n", __func__, i, tx.GetHash().GetHex());
203
0
            return std::nullopt;
204
0
        }
205
69.9k
    }
206
47.1k
    return prev_heights;
207
47.1k
}
208
} // namespace
209
210
std::optional<LockPoints> CalculateLockPointsAtTip(
211
    CBlockIndex* tip,
212
    const CCoinsView& coins_view,
213
    const CTransaction& tx)
214
47.1k
{
215
47.1k
    assert(tip);
216
217
47.1k
    auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
218
47.1k
    if (!prev_heights.has_value()) return std::nullopt;
219
220
47.1k
    CBlockIndex next_tip;
221
47.1k
    next_tip.pprev = tip;
222
    // When SequenceLocks() is called within ConnectBlock(), the height
223
    // of the block *being* evaluated is what is used.
224
    // Thus if we want to know if a transaction can be part of the
225
    // *next* block, we need to use one more than active_chainstate.m_chain.Height()
226
47.1k
    next_tip.nHeight = tip->nHeight + 1;
227
47.1k
    const auto [min_height, min_time] = CalculateSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, prev_heights.value(), next_tip);
228
229
    // Also store the hash of the block with the highest height of
230
    // all the blocks which have sequence locked prevouts.
231
    // This hash needs to still be on the chain
232
    // for these LockPoint calculations to be valid
233
    // Note: It is impossible to correctly calculate a maxInputBlock
234
    // if any of the sequence locked inputs depend on unconfirmed txs,
235
    // except in the special case where the relative lock time/height
236
    // is 0, which is equivalent to no sequence lock. Since we assume
237
    // input height of tip+1 for mempool txs and test the resulting
238
    // min_height and min_time from CalculateSequenceLocks against tip+1.
239
47.1k
    int max_input_height{0};
240
69.9k
    for (const int height : prev_heights.value()) {
241
        // Can ignore mempool inputs since we'll fail if they had non-zero locks
242
69.9k
        if (height != next_tip.nHeight) {
243
61.9k
            max_input_height = std::max(max_input_height, height);
244
61.9k
        }
245
69.9k
    }
246
247
    // tip->GetAncestor(max_input_height) should never return a nullptr
248
    // because max_input_height is always less than the tip height.
249
    // It would, however, be a bad bug to continue execution, since a
250
    // LockPoints object with the maxInputBlock member set to nullptr
251
    // signifies no relative lock time.
252
47.1k
    return LockPoints{min_height, min_time, Assert(tip->GetAncestor(max_input_height))};
253
47.1k
}
254
255
bool CheckSequenceLocksAtTip(CBlockIndex* tip,
256
                             const LockPoints& lock_points)
257
49.2k
{
258
49.2k
    assert(tip != nullptr);
259
260
49.2k
    CBlockIndex index;
261
49.2k
    index.pprev = tip;
262
    // CheckSequenceLocksAtTip() uses active_chainstate.m_chain.Height()+1 to evaluate
263
    // height based locks because when SequenceLocks() is called within
264
    // ConnectBlock(), the height of the block *being*
265
    // evaluated is what is used.
266
    // Thus if we want to know if a transaction can be part of the
267
    // *next* block, we need to use one more than active_chainstate.m_chain.Height()
268
49.2k
    index.nHeight = tip->nHeight + 1;
269
270
49.2k
    return EvaluateSequenceLocks(index, {lock_points.height, lock_points.time});
271
49.2k
}
272
273
static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache)
274
    EXCLUSIVE_LOCKS_REQUIRED(::cs_main, pool.cs)
275
28.0k
{
276
28.0k
    AssertLockHeld(::cs_main);
277
28.0k
    AssertLockHeld(pool.cs);
278
28.0k
    int expired = pool.Expire(GetTime<std::chrono::seconds>() - pool.m_opts.expiry);
279
28.0k
    if (expired != 0) {
280
12
        LogDebug(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
281
12
    }
282
283
28.0k
    std::vector<COutPoint> vNoSpendsRemaining;
284
28.0k
    pool.TrimToSize(pool.m_opts.max_size_bytes, &vNoSpendsRemaining);
285
28.0k
    for (const COutPoint& removed : vNoSpendsRemaining)
286
31
        coins_cache.Uncache(removed);
287
28.0k
}
288
289
static bool IsCurrentForFeeEstimation(Chainstate& active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
290
26.8k
{
291
26.8k
    AssertLockHeld(cs_main);
292
26.8k
    if (active_chainstate.m_chainman.IsInitialBlockDownload()) {
293
73
        return false;
294
73
    }
295
26.8k
    if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
296
223
        return false;
297
26.5k
    if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
298
64
        return false;
299
64
    }
300
26.5k
    return true;
301
26.5k
}
302
303
void Chainstate::MaybeUpdateMempoolForReorg(
304
    DisconnectedBlockTransactions& disconnectpool,
305
    bool fAddToMempool)
306
2.14k
{
307
2.14k
    if (!m_mempool) return;
308
309
2.13k
    AssertLockHeld(cs_main);
310
2.13k
    AssertLockHeld(m_mempool->cs);
311
2.13k
    std::vector<Txid> vHashUpdate;
312
2.13k
    {
313
        // disconnectpool is ordered so that the front is the most recently-confirmed
314
        // transaction (the last tx of the block at the tip) in the disconnected chain.
315
        // Iterate disconnectpool in reverse, so that we add transactions
316
        // back to the mempool starting with the earliest transaction that had
317
        // been previously seen in a block.
318
2.13k
        const auto queuedTx = disconnectpool.take();
319
2.13k
        auto it = queuedTx.rbegin();
320
15.1k
        while (it != queuedTx.rend()) {
321
            // ignore validation errors in resurrected transactions
322
12.9k
            if (!fAddToMempool || (*it)->IsCoinBase() ||
323
12.9k
                AcceptToMemoryPool(*this, *it, GetTime(),
324
4.60k
                    /*bypass_limits=*/true, /*test_accept=*/false).m_result_type !=
325
12.1k
                        MempoolAcceptResult::ResultType::VALID) {
326
                // If the transaction doesn't make it in to the mempool, remove any
327
                // transactions that depend on it (which would now be orphans).
328
12.1k
                m_mempool->removeRecursive(**it, MemPoolRemovalReason::REORG);
329
12.1k
            } else if (m_mempool->exists((*it)->GetHash())) {
330
825
                vHashUpdate.push_back((*it)->GetHash());
331
825
            }
332
12.9k
            ++it;
333
12.9k
        }
334
2.13k
    }
335
336
    // AcceptToMemoryPool/addNewTransaction all assume that new mempool entries have
337
    // no in-mempool children, which is generally not true when adding
338
    // previously-confirmed transactions back to the mempool.
339
    // UpdateTransactionsFromBlock finds descendants of any transactions in
340
    // the disconnectpool that were added back and cleans up the mempool state.
341
2.13k
    m_mempool->UpdateTransactionsFromBlock(vHashUpdate);
342
343
    // Predicate to use for filtering transactions in removeForReorg.
344
    // Checks whether the transaction is still final and, if it spends a coinbase output, mature.
345
    // Also updates valid entries' cached LockPoints if needed.
346
    // If false, the tx is still valid and its lockpoints are updated.
347
    // If true, the tx would be invalid in the next block; remove this entry and all of its descendants.
348
    // Note that TRUC rules are not applied here, so reorgs may cause violations of TRUC inheritance or
349
    // topology restrictions.
350
2.13k
    const auto filter_final_and_mature = [&](CTxMemPool::txiter it)
351
2.28k
        EXCLUSIVE_LOCKS_REQUIRED(m_mempool->cs, ::cs_main) {
352
2.28k
        AssertLockHeld(m_mempool->cs);
353
2.28k
        AssertLockHeld(::cs_main);
354
2.28k
        const CTransaction& tx = it->GetTx();
355
356
        // The transaction must be final.
357
2.28k
        if (!CheckFinalTxAtTip(*Assert(m_chain.Tip()), tx)) return true;
358
359
2.28k
        const LockPoints& lp = it->GetLockPoints();
360
        // CheckSequenceLocksAtTip checks if the transaction will be final in the next block to be
361
        // created on top of the new chain.
362
2.28k
        if (TestLockPointValidity(m_chain, lp)) {
363
2.05k
            if (!CheckSequenceLocksAtTip(m_chain.Tip(), lp)) {
364
3
                return true;
365
3
            }
366
2.05k
        } else {
367
230
            const CCoinsViewMemPool view_mempool{&CoinsTip(), *m_mempool};
368
230
            const std::optional<LockPoints> new_lock_points{CalculateLockPointsAtTip(m_chain.Tip(), view_mempool, tx)};
369
230
            if (new_lock_points.has_value() && CheckSequenceLocksAtTip(m_chain.Tip(), *new_lock_points)) {
370
                // Now update the mempool entry lockpoints as well.
371
228
                it->UpdateLockPoints(*new_lock_points);
372
228
            } else {
373
2
                return true;
374
2
            }
375
230
        }
376
377
        // If the transaction spends any coinbase outputs, it must be mature.
378
2.27k
        if (it->GetSpendsCoinbase()) {
379
570
            for (const CTxIn& txin : tx.vin) {
380
570
                if (m_mempool->exists(txin.prevout.hash)) continue;
381
566
                const Coin& coin{CoinsTip().AccessCoin(txin.prevout)};
382
566
                assert(!coin.IsSpent());
383
566
                const auto mempool_spend_height{m_chain.Tip()->nHeight + 1};
384
566
                if (coin.IsCoinBase() && mempool_spend_height - coin.nHeight < COINBASE_MATURITY) {
385
7
                    return true;
386
7
                }
387
566
            }
388
552
        }
389
        // Transaction is still valid and cached LockPoints are updated.
390
2.27k
        return false;
391
2.27k
    };
392
393
    // We also need to remove any now-immature transactions
394
2.13k
    m_mempool->removeForReorg(m_chain, filter_final_and_mature);
395
    // Re-limit mempool size, in case we added any transactions
396
2.13k
    LimitMempoolSize(*m_mempool, this->CoinsTip());
397
2.13k
}
398
399
/**
400
* Checks to avoid mempool polluting consensus critical paths since cached
401
* signature and script validity results will be reused if we validate this
402
* transaction again during block validation.
403
* */
404
static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state,
405
                const CCoinsViewCache& view, const CTxMemPool& pool,
406
                script_verify_flags flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip,
407
                ValidationCache& validation_cache)
408
                EXCLUSIVE_LOCKS_REQUIRED(cs_main, pool.cs)
409
43.4k
{
410
43.4k
    AssertLockHeld(cs_main);
411
43.4k
    AssertLockHeld(pool.cs);
412
413
43.4k
    assert(!tx.IsCoinBase());
414
59.8k
    for (const CTxIn& txin : tx.vin) {
415
59.8k
        const Coin& coin = view.AccessCoin(txin.prevout);
416
417
        // This coin was checked in PreChecks and MemPoolAccept
418
        // has been holding cs_main since then.
419
59.8k
        Assume(!coin.IsSpent());
420
59.8k
        if (coin.IsSpent()) return false;
421
422
        // If the Coin is available, there are 2 possibilities:
423
        // it is available in our current ChainstateActive UTXO set,
424
        // or it's a UTXO provided by a transaction in our mempool.
425
        // Ensure the scriptPubKeys in Coins from CoinsView are correct.
426
59.8k
        const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
427
59.8k
        if (txFrom) {
428
7.29k
            assert(txFrom->GetHash() == txin.prevout.hash);
429
7.29k
            assert(txFrom->vout.size() > txin.prevout.n);
430
7.29k
            assert(txFrom->vout[txin.prevout.n] == coin.out);
431
52.5k
        } else {
432
52.5k
            const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
433
52.5k
            assert(!coinFromUTXOSet.IsSpent());
434
52.5k
            assert(coinFromUTXOSet.out == coin.out);
435
52.5k
        }
436
59.8k
    }
437
438
    // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
439
43.4k
    return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata, validation_cache);
440
43.4k
}
441
442
namespace {
443
444
class MemPoolAccept
445
{
446
public:
447
    explicit MemPoolAccept(CTxMemPool& mempool, Chainstate& active_chainstate) :
448
52.8k
        m_pool(mempool),
449
52.8k
        m_view(&CoinsViewEmpty::Get()),
450
52.8k
        m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
451
52.8k
        m_active_chainstate(active_chainstate)
452
52.8k
    {
453
52.8k
    }
454
455
    // We put the arguments we're handed into a struct, so we can pass them
456
    // around easier.
457
    struct ATMPArgs {
458
        const int64_t m_accept_time;
459
        const bool m_bypass_limits;
460
        /*
461
         * Return any outpoints which were not previously present in the coins
462
         * cache, but were added as a result of validating the tx for mempool
463
         * acceptance. This allows the caller to optionally remove the cache
464
         * additions if the associated transaction ends up being rejected by
465
         * the mempool.
466
         */
467
        std::vector<COutPoint>& m_coins_to_uncache;
468
        /** When true, the transaction or package will not be submitted to the mempool. */
469
        const bool m_test_accept;
470
        /** Whether we allow transactions to replace mempool transactions. If false,
471
         * any transaction spending the same inputs as a transaction in the mempool is considered
472
         * a conflict. */
473
        const bool m_allow_replacement;
474
        /** When true, allow sibling eviction. This only occurs in single transaction package settings. */
475
        const bool m_allow_sibling_eviction;
476
        /** Used to skip the LimitMempoolSize() call within AcceptSingleTransaction(). This should be used when multiple
477
         * AcceptSubPackage calls are expected and the mempool will be trimmed at the end of AcceptPackage(). */
478
        const bool m_package_submission;
479
        /** When true, use package feerates instead of individual transaction feerates for fee-based
480
         * policies such as mempool min fee and min relay fee.
481
         */
482
        const bool m_package_feerates;
483
        /** Used for local submission of transactions to catch "absurd" fees
484
         * due to fee miscalculation by wallets. std:nullopt implies unset, allowing any feerates.
485
         * Any individual transaction failing this check causes immediate failure.
486
         */
487
        const std::optional<CFeeRate> m_client_maxfeerate;
488
489
        /** Parameters for single transaction mempool validation. */
490
        static ATMPArgs SingleAccept(int64_t accept_time,
491
                                     bool bypass_limits, std::vector<COutPoint>& coins_to_uncache,
492
52.5k
                                     bool test_accept) {
493
52.5k
            return ATMPArgs{/*accept_time=*/ accept_time,
494
52.5k
                            /*bypass_limits=*/ bypass_limits,
495
52.5k
                            /*coins_to_uncache=*/ coins_to_uncache,
496
52.5k
                            /*test_accept=*/ test_accept,
497
52.5k
                            /*allow_replacement=*/ true,
498
52.5k
                            /*allow_sibling_eviction=*/ true,
499
52.5k
                            /*package_submission=*/ false,
500
52.5k
                            /*package_feerates=*/ false,
501
52.5k
                            /*client_maxfeerate=*/ {}, // checked by caller
502
52.5k
            };
503
52.5k
        }
504
505
        /** Parameters for test package mempool validation through testmempoolaccept. */
506
        static ATMPArgs PackageTestAccept(int64_t accept_time,
507
78
                                          std::vector<COutPoint>& coins_to_uncache) {
508
78
            return ATMPArgs{/*accept_time=*/ accept_time,
509
78
                            /*bypass_limits=*/ false,
510
78
                            /*coins_to_uncache=*/ coins_to_uncache,
511
78
                            /*test_accept=*/ true,
512
78
                            /*allow_replacement=*/ false,
513
78
                            /*allow_sibling_eviction=*/ false,
514
78
                            /*package_submission=*/ false, // not submitting to mempool
515
78
                            /*package_feerates=*/ false,
516
78
                            /*client_maxfeerate=*/ {}, // checked by caller
517
78
            };
518
78
        }
519
520
        /** Parameters for child-with-parents package validation. */
521
        static ATMPArgs PackageChildWithParents(int64_t accept_time,
522
171
                                                std::vector<COutPoint>& coins_to_uncache, const std::optional<CFeeRate>& client_maxfeerate) {
523
171
            return ATMPArgs{/*accept_time=*/ accept_time,
524
171
                            /*bypass_limits=*/ false,
525
171
                            /*coins_to_uncache=*/ coins_to_uncache,
526
171
                            /*test_accept=*/ false,
527
171
                            /*allow_replacement=*/ true,
528
171
                            /*allow_sibling_eviction=*/ false,
529
171
                            /*package_submission=*/ true,
530
171
                            /*package_feerates=*/ true,
531
171
                            /*client_maxfeerate=*/ client_maxfeerate,
532
171
            };
533
171
        }
534
535
        /** Parameters for a single transaction within a package. */
536
378
        static ATMPArgs SingleInPackageAccept(const ATMPArgs& package_args) {
537
378
            return ATMPArgs{/*accept_time=*/ package_args.m_accept_time,
538
378
                            /*bypass_limits=*/ false,
539
378
                            /*coins_to_uncache=*/ package_args.m_coins_to_uncache,
540
378
                            /*test_accept=*/ package_args.m_test_accept,
541
378
                            /*allow_replacement=*/ true,
542
378
                            /*allow_sibling_eviction=*/ true,
543
378
                            /*package_submission=*/ true, // trim at the end of AcceptPackage()
544
378
                            /*package_feerates=*/ false, // only 1 transaction
545
378
                            /*client_maxfeerate=*/ package_args.m_client_maxfeerate,
546
378
            };
547
378
        }
548
549
    private:
550
        // Private ctor to avoid exposing details to clients and allowing the possibility of
551
        // mixing up the order of the arguments. Use static functions above instead.
552
        ATMPArgs(int64_t accept_time,
553
                 bool bypass_limits,
554
                 std::vector<COutPoint>& coins_to_uncache,
555
                 bool test_accept,
556
                 bool allow_replacement,
557
                 bool allow_sibling_eviction,
558
                 bool package_submission,
559
                 bool package_feerates,
560
                 std::optional<CFeeRate> client_maxfeerate)
561
53.1k
            : m_accept_time{accept_time},
562
53.1k
              m_bypass_limits{bypass_limits},
563
53.1k
              m_coins_to_uncache{coins_to_uncache},
564
53.1k
              m_test_accept{test_accept},
565
53.1k
              m_allow_replacement{allow_replacement},
566
53.1k
              m_allow_sibling_eviction{allow_sibling_eviction},
567
53.1k
              m_package_submission{package_submission},
568
53.1k
              m_package_feerates{package_feerates},
569
53.1k
              m_client_maxfeerate{client_maxfeerate}
570
53.1k
        {
571
            // If we are using package feerates, we must be doing package submission.
572
            // It also means sibling eviction is not permitted.
573
53.1k
            if (m_package_feerates) {
574
171
                Assume(m_package_submission);
575
171
                Assume(!m_allow_sibling_eviction);
576
171
            }
577
53.1k
            if (m_allow_sibling_eviction) Assume(m_allow_replacement);
578
53.1k
        }
579
    };
580
581
    /** Clean up all non-chainstate coins from m_view and m_viewmempool. */
582
    void CleanupTemporaryCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
583
584
    // Single transaction acceptance
585
52.5k
    MempoolAcceptResult AcceptSingleTransactionAndCleanup(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
586
52.5k
        LOCK(m_pool.cs);
587
52.5k
        MempoolAcceptResult result = AcceptSingleTransactionInternal(ptx, args);
588
52.5k
        ClearSubPackageState();
589
52.5k
        return result;
590
52.5k
    }
591
    MempoolAcceptResult AcceptSingleTransactionInternal(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
592
593
    /**
594
    * Multiple transaction acceptance. Transactions may or may not be interdependent, but must not
595
    * conflict with each other, and the transactions cannot already be in the mempool. Parents must
596
    * come before children if any dependencies exist.
597
    */
598
78
    PackageMempoolAcceptResult AcceptMultipleTransactionsAndCleanup(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
599
78
        LOCK(m_pool.cs);
600
78
        PackageMempoolAcceptResult result = AcceptMultipleTransactionsInternal(txns, args);
601
78
        ClearSubPackageState();
602
78
        return result;
603
78
    }
604
    PackageMempoolAcceptResult AcceptMultipleTransactionsInternal(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
605
606
    /**
607
     * Submission of a subpackage.
608
     * If subpackage size == 1, calls AcceptSingleTransaction() with adjusted ATMPArgs to
609
     * enable sibling eviction and creates a PackageMempoolAcceptResult
610
     * wrapping the result.
611
     *
612
     * If subpackage size > 1, calls AcceptMultipleTransactions() with the provided ATMPArgs.
613
     *
614
     * Also cleans up all non-chainstate coins from m_view at the end.
615
    */
616
    PackageMempoolAcceptResult AcceptSubPackage(const std::vector<CTransactionRef>& subpackage, ATMPArgs& args)
617
        EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
618
619
    /**
620
     * Package (more specific than just multiple transactions) acceptance. Package must be a child
621
     * with all of its unconfirmed parents, and topologically sorted.
622
     */
623
    PackageMempoolAcceptResult AcceptPackage(const Package& package, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
624
625
private:
626
    // All the intermediate state that gets passed between the various levels
627
    // of checking a given transaction.
628
    struct Workspace {
629
53.7k
        explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
630
        /** Txids of mempool transactions that this transaction directly conflicts with or may
631
         * replace via sibling eviction. */
632
        std::set<Txid> m_conflicts;
633
        /** Iterators to mempool entries that this transaction directly conflicts with or may
634
         * replace via sibling eviction. */
635
        CTxMemPool::setEntries m_iters_conflicting;
636
        /** All mempool parents of this transaction. */
637
        std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> m_parents;
638
        /* Handle to the tx in the changeset */
639
        CTxMemPool::ChangeSet::TxHandle m_tx_handle;
640
        /** Whether RBF-related data structures (m_conflicts, m_iters_conflicting,
641
         * m_replaced_transactions) include a sibling in addition to txns with conflicting inputs. */
642
        bool m_sibling_eviction{false};
643
644
        /** Virtual size of the transaction as used by the mempool, calculated using serialized size
645
         * of the transaction and sigops. */
646
        int64_t m_vsize;
647
        /** Fees paid by this transaction: total input amounts subtracted by total output amounts. */
648
        CAmount m_base_fees;
649
        /** Base fees + any fee delta set by the user with prioritisetransaction. */
650
        CAmount m_modified_fees;
651
652
        /** If we're doing package validation (i.e. m_package_feerates=true), the "effective"
653
         * package feerate of this transaction is the total fees divided by the total size of
654
         * transactions (which may include its ancestors and/or descendants). */
655
        CFeeRate m_package_feerate{0};
656
657
        const CTransactionRef& m_ptx;
658
        /** Txid. */
659
        const Txid& m_hash;
660
        TxValidationState m_state;
661
        /** A temporary cache containing serialized transaction data for signature verification.
662
         * Reused across PolicyScriptChecks and ConsensusScriptChecks. */
663
        PrecomputedTransactionData m_precomputed_txdata;
664
    };
665
666
    // Run the policy checks on a given transaction, excluding any script checks.
667
    // Looks up inputs, calculates feerate, considers replacement, evaluates
668
    // package limits, etc. As this function can be invoked for "free" by a peer,
669
    // only tests that are fast should be done here (to avoid CPU DoS).
670
    bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
671
672
    // Run checks for mempool replace-by-fee, only used in AcceptSingleTransaction.
673
    bool ReplacementChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
674
675
    bool PackageRBFChecks(const std::vector<CTransactionRef>& txns,
676
                          std::vector<Workspace>& workspaces,
677
                          PackageValidationState& package_state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
678
679
    // Run the script checks using our policy flags. As this can be slow, we should
680
    // only invoke this on transactions that have otherwise passed policy checks.
681
    bool PolicyScriptChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
682
683
    // Re-run the script checks, using consensus flags, and try to cache the
684
    // result in the scriptcache. This should be done after
685
    // PolicyScriptChecks(). This requires that all inputs either be in our
686
    // utxo set or in the mempool.
687
    bool ConsensusScriptChecks(Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
688
689
    // Try to add the transaction to the mempool, removing any conflicts first.
690
    void FinalizeSubpackage(const ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
691
692
    // Submit all transactions to the mempool and call ConsensusScriptChecks to add to the script
693
    // cache - should only be called after successful validation of all transactions in the package.
694
    // Does not call LimitMempoolSize(), so mempool max_size_bytes may be temporarily exceeded.
695
    bool SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces, PackageValidationState& package_state,
696
                       std::map<Wtxid, MempoolAcceptResult>& results)
697
         EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
698
699
    // Compare a package's feerate against minimum allowed.
700
    bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs)
701
45.1k
    {
702
45.1k
        AssertLockHeld(::cs_main);
703
45.1k
        AssertLockHeld(m_pool.cs);
704
45.1k
        CAmount mempoolRejectFee = m_pool.GetMinFee().GetFee(package_size);
705
45.1k
        if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
706
50
            return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
707
50
        }
708
709
45.0k
        if (package_fee < m_pool.m_opts.min_relay_feerate.GetFee(package_size)) {
710
101
            return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "min relay fee not met",
711
101
                                 strprintf("%d < %d", package_fee, m_pool.m_opts.min_relay_feerate.GetFee(package_size)));
712
101
        }
713
44.9k
        return true;
714
45.0k
    }
715
716
    ValidationCache& GetValidationCache()
717
89.0k
    {
718
89.0k
        return m_active_chainstate.m_chainman.m_validation_cache;
719
89.0k
    }
720
721
private:
722
    CTxMemPool& m_pool;
723
724
    /** Holds a cached view of available coins from the UTXO set, mempool, and artificial temporary coins (to enable package validation).
725
     * The view doesn't track whether a coin previously existed but has now been spent. We detect conflicts in other ways:
726
     * - conflicts within a transaction are checked in CheckTransaction (bad-txns-inputs-duplicate)
727
     * - conflicts within a package are checked in IsWellFormedPackage (conflict-in-package)
728
     * - conflicts with an existing mempool transaction are found in CTxMemPool::GetConflictTx and replacements are allowed
729
     * The temporary coins should persist between individual transaction checks so that package validation is possible,
730
     * but must be cleaned up when we finish validating a subpackage, whether accepted or rejected. The cache must also
731
     * be cleared when mempool contents change (when a changeset is applied or when the mempool trims itself) because it
732
     * can return cached coins that no longer exist in the backend. Use CleanupTemporaryCoins() anytime you are finished
733
     * with a SubPackageState or call LimitMempoolSize().
734
     */
735
    CCoinsViewCache m_view;
736
737
    // These are the two possible backends for m_view.
738
    /** When m_view is connected to m_viewmempool as its backend, it can pull coins from the mempool and from the UTXO
739
     * set. This is also where temporary coins are stored. */
740
    CCoinsViewMemPool m_viewmempool;
741
742
    Chainstate& m_active_chainstate;
743
744
    // Fields below are per *sub*package state and must be reset prior to subsequent
745
    // AcceptSingleTransaction and AcceptMultipleTransactions invocations
746
    struct SubPackageState {
747
        /** Aggregated modified fees of all transactions, used to calculate package feerate. */
748
        CAmount m_total_modified_fees{0};
749
        /** Aggregated virtual size of all transactions, used to calculate package feerate. */
750
        int64_t m_total_vsize{0};
751
752
        // RBF-related members
753
        /** Whether the transaction(s) would replace any mempool transactions and/or evict any siblings.
754
         * If so, RBF rules apply. */
755
        bool m_rbf{false};
756
        /** Mempool transactions that were replaced. */
757
        std::list<CTransactionRef> m_replaced_transactions;
758
        /* Changeset representing adding transactions and removing their conflicts. */
759
        std::unique_ptr<CTxMemPool::ChangeSet> m_changeset;
760
761
        /** Total modified fees of mempool transactions being replaced. */
762
        CAmount m_conflicting_fees{0};
763
        /** Total size (in virtual bytes) of mempool transactions being replaced. */
764
        size_t m_conflicting_size{0};
765
    };
766
767
    struct SubPackageState m_subpackage;
768
769
    /** Re-set sub-package state to not leak between evaluations */
770
    void ClearSubPackageState() EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
771
53.2k
    {
772
53.2k
        m_subpackage = SubPackageState{};
773
774
        // And clean coins while at it
775
53.2k
        CleanupTemporaryCoins();
776
53.2k
    }
777
};
778
779
bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
780
53.7k
{
781
53.7k
    AssertLockHeld(cs_main);
782
53.7k
    AssertLockHeld(m_pool.cs);
783
53.7k
    const CTransactionRef& ptx = ws.m_ptx;
784
53.7k
    const CTransaction& tx = *ws.m_ptx;
785
53.7k
    const Txid& hash = ws.m_hash;
786
787
    // Copy/alias what we need out of args
788
53.7k
    const int64_t nAcceptTime = args.m_accept_time;
789
53.7k
    const bool bypass_limits = args.m_bypass_limits;
790
53.7k
    std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
791
792
    // Alias what we need out of ws
793
53.7k
    TxValidationState& state = ws.m_state;
794
795
53.7k
    if (!CheckTransaction(tx, state)) {
796
21
        return false; // state filled in by CheckTransaction
797
21
    }
798
799
    // Coinbase is only valid in a block, not as a loose transaction
800
53.7k
    if (tx.IsCoinBase())
801
2
        return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
802
803
    // Rather not work on nonstandard transactions (unless -testnet/-regtest)
804
53.7k
    std::string reason;
805
53.7k
    if (m_pool.m_opts.require_standard && !IsStandardTx(tx, m_pool.m_opts.max_datacarrier_bytes, m_pool.m_opts.permit_bare_multisig, m_pool.m_opts.dust_relay_feerate, reason)) {
806
5.63k
        return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
807
5.63k
    }
808
809
    // Transactions smaller than 65 non-witness bytes are not relayed to mitigate CVE-2017-12842.
810
48.0k
    if (::GetSerializeSize(TX_NO_WITNESS(tx)) < MIN_STANDARD_TX_NONWITNESS_SIZE)
811
6
        return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
812
813
    // Only accept nLockTime-using transactions that can be mined in the next
814
    // block; we don't want our mempool filled up with transactions that can't
815
    // be mined yet.
816
48.0k
    if (!CheckFinalTxAtTip(*Assert(m_active_chainstate.m_chain.Tip()), tx)) {
817
25
        return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
818
25
    }
819
820
48.0k
    if (m_pool.exists(tx.GetWitnessHash())) {
821
        // Exact transaction already exists in the mempool.
822
41
        return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
823
47.9k
    } else if (m_pool.exists(tx.GetHash())) {
824
        // Transaction with the same non-witness data but different witness (same txid, different
825
        // wtxid) already exists in the mempool.
826
4
        return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
827
4
    }
828
829
    // Check for conflicts with in-memory transactions
830
47.9k
    for (const CTxIn &txin : tx.vin)
831
70.0k
    {
832
70.0k
        const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
833
70.0k
        if (ptxConflicting) {
834
2.43k
            if (!args.m_allow_replacement) {
835
                // Transaction conflicts with a mempool tx, but we're not allowing replacements in this context.
836
2
                return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
837
2
            }
838
2.43k
            ws.m_conflicts.insert(ptxConflicting->GetHash());
839
2.43k
        }
840
70.0k
    }
841
842
47.9k
    m_view.SetBackend(m_viewmempool);
843
844
47.9k
    const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
845
    // do all inputs exist?
846
69.9k
    for (const CTxIn& txin : tx.vin) {
847
69.9k
        if (!coins_cache.HaveCoinInCache(txin.prevout)) {
848
15.3k
            coins_to_uncache.push_back(txin.prevout);
849
15.3k
        }
850
851
        // Note: this call may add txin.prevout to the coins cache
852
        // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
853
        // later (via coins_to_uncache) if this tx turns out to be invalid.
854
69.9k
        if (!m_view.HaveCoin(txin.prevout)) {
855
            // Are inputs missing because we already have the tx?
856
2.44k
            for (size_t out = 0; out < tx.vout.size(); out++) {
857
                // Optimistically just do efficient check of cache for outputs
858
1.41k
                if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
859
4
                    return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
860
4
                }
861
1.41k
            }
862
            // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
863
1.03k
            return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
864
1.03k
        }
865
69.9k
    }
866
867
    // This is const, but calls into `CCoinsViewCache::GetBestBlock()` to refresh
868
    // the cached best block through `m_viewmempool` after caching inputs.
869
46.9k
    (void)m_view.GetBestBlock();
870
871
    // All required inputs are cached now, so switch m_view to the empty backend.
872
    // This keeps already-fetched cache entries for later checks and prevents new
873
    // backend lookups (which would avoid coins_to_uncache tracking).
874
46.9k
    m_view.SetBackend(CoinsViewEmpty::Get());
875
876
46.9k
    assert(m_active_chainstate.m_blockman.LookupBlockIndex(m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
877
878
    // Only accept BIP68 sequence locked transactions that can be mined in the next
879
    // block; we don't want our mempool filled up with transactions that can't
880
    // be mined yet.
881
    // Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
882
    // backend was removed, it no longer pulls coins from the mempool.
883
46.9k
    const std::optional<LockPoints> lock_points{CalculateLockPointsAtTip(m_active_chainstate.m_chain.Tip(), m_view, tx)};
884
46.9k
    if (!lock_points.has_value() || !CheckSequenceLocksAtTip(m_active_chainstate.m_chain.Tip(), *lock_points)) {
885
368
        return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
886
368
    }
887
888
    // The mempool holds txs for the next block, so pass height+1 to CheckTxInputs
889
46.5k
    if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_chain.Height() + 1, ws.m_base_fees)) {
890
6
        return false; // state filled in by CheckTxInputs
891
6
    }
892
893
46.5k
    if (m_pool.m_opts.require_standard) {
894
45.8k
        state = ValidateInputsStandardness(tx, m_view);
895
45.8k
        if (state.IsInvalid()) {
896
180
            return false;
897
180
        }
898
45.8k
    }
899
900
    // Check for non-standard witnesses.
901
46.3k
    if (tx.HasWitness() && m_pool.m_opts.require_standard && !IsWitnessStandard(tx, m_view)) {
902
218
        return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
903
218
    }
904
905
46.1k
    int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
906
907
    // Keep track of transactions that spend a coinbase, which we re-scan
908
    // during reorgs to ensure COINBASE_MATURITY is still met.
909
46.1k
    bool fSpendsCoinbase = false;
910
62.0k
    for (const CTxIn &txin : tx.vin) {
911
62.0k
        const Coin &coin = m_view.AccessCoin(txin.prevout);
912
62.0k
        if (coin.IsCoinBase()) {
913
6.58k
            fSpendsCoinbase = true;
914
6.58k
            break;
915
6.58k
        }
916
62.0k
    }
917
918
    // Set entry_sequence to 0 when bypass_limits is used; this allows txs from a block
919
    // reorg to be marked earlier than any child txs that were already in the mempool.
920
46.1k
    const uint64_t entry_sequence = bypass_limits ? 0 : m_pool.GetSequence();
921
46.1k
    if (!m_subpackage.m_changeset) {
922
45.5k
        m_subpackage.m_changeset = m_pool.GetChangeSet();
923
45.5k
    }
924
46.1k
    ws.m_tx_handle = m_subpackage.m_changeset->StageAddition(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(), entry_sequence, fSpendsCoinbase, nSigOpsCost, lock_points.value());
925
926
    // ws.m_modified_fees includes any fee deltas from PrioritiseTransaction
927
46.1k
    ws.m_modified_fees = ws.m_tx_handle->GetModifiedFee();
928
929
46.1k
    ws.m_vsize = ws.m_tx_handle->GetTxSize();
930
931
    // Enforces 0-fee for dust transactions, no incentive to be mined alone
932
46.1k
    if (m_pool.m_opts.require_standard) {
933
45.4k
        if (!PreCheckEphemeralTx(*ptx, m_pool.m_opts.dust_relay_feerate, ws.m_base_fees, ws.m_modified_fees, state)) {
934
87
            return false; // state filled in by PreCheckEphemeralTx
935
87
        }
936
45.4k
    }
937
938
46.0k
    if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
939
5
        return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
940
5
                strprintf("%d", nSigOpsCost));
941
942
    // No individual transactions are allowed below the mempool min feerate except from disconnected
943
    // blocks and transactions in a package. Package transactions will be checked using package
944
    // feerate later.
945
46.0k
    if (!bypass_limits && !args.m_package_feerates && !CheckFeeRate(ws.m_vsize, ws.m_modified_fees, state)) return false;
946
947
45.9k
    ws.m_iters_conflicting = m_pool.GetIterSet(ws.m_conflicts);
948
949
45.9k
    ws.m_parents = m_pool.GetParents(*ws.m_tx_handle);
950
951
45.9k
    if (!args.m_bypass_limits) {
952
        // Perform the TRUC checks, using the in-mempool parents.
953
45.0k
        if (const auto err{SingleTRUCChecks(m_pool, ws.m_ptx, ws.m_parents, ws.m_conflicts, ws.m_vsize)}) {
954
            // Single transaction contexts only.
955
24
            if (args.m_allow_sibling_eviction && err->second != nullptr) {
956
                // We should only be considering where replacement is considered valid as well.
957
14
                Assume(args.m_allow_replacement);
958
                // Potential sibling eviction. Add the sibling to our list of mempool conflicts to be
959
                // included in RBF checks.
960
14
                ws.m_conflicts.insert(err->second->GetHash());
961
                // Adding the sibling to m_iters_conflicting here means that it doesn't count towards
962
                // RBF Carve Out above. This is correct, since removing to-be-replaced transactions from
963
                // the descendant count is done separately in SingleTRUCChecks for TRUC transactions.
964
14
                ws.m_iters_conflicting.insert(m_pool.GetIter(err->second->GetHash()).value());
965
14
                ws.m_sibling_eviction = true;
966
                // The sibling will be treated as part of the to-be-replaced set in ReplacementChecks.
967
                // Note that we are not checking whether it opts in to replaceability via BIP125 or TRUC
968
                // (which is normally done in PreChecks). However, the only way a TRUC transaction can
969
                // have a non-TRUC and non-BIP125 descendant is due to a reorg.
970
14
            } else {
971
10
                return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "TRUC-violation", err->first);
972
10
            }
973
24
        }
974
45.0k
    }
975
976
    // We want to detect conflicts in any tx in a package to trigger package RBF logic
977
45.9k
    m_subpackage.m_rbf |= !ws.m_conflicts.empty();
978
45.9k
    return true;
979
45.9k
}
980
981
bool MemPoolAccept::ReplacementChecks(Workspace& ws)
982
1.39k
{
983
1.39k
    AssertLockHeld(cs_main);
984
1.39k
    AssertLockHeld(m_pool.cs);
985
986
1.39k
    const CTransaction& tx = *ws.m_ptx;
987
1.39k
    const Txid& hash = ws.m_hash;
988
1.39k
    TxValidationState& state = ws.m_state;
989
990
1.39k
    CTxMemPool::setEntries all_conflicts;
991
992
    // Calculate all conflicting entries and enforce Rule #5.
993
1.39k
    if (const auto err_string{GetEntriesForConflicts(tx, m_pool, ws.m_iters_conflicting, all_conflicts)}) {
994
4
        return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY,
995
4
                             strprintf("too many potential replacements%s", ws.m_sibling_eviction ? " (including sibling eviction)" : ""), *err_string);
996
4
    }
997
998
    // Check if it's economically rational to mine this transaction rather than the ones it
999
    // replaces and pays for its own relay fees. Enforce Rules #3 and #4.
1000
2.35k
    for (CTxMemPool::txiter it : all_conflicts) {
1001
2.35k
        m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1002
2.35k
        m_subpackage.m_conflicting_size += it->GetTxSize();
1003
2.35k
    }
1004
1005
1.39k
    if (const auto err_string{PaysForRBF(m_subpackage.m_conflicting_fees, ws.m_modified_fees, ws.m_vsize,
1006
1.39k
                                         m_pool.m_opts.incremental_relay_feerate, hash)}) {
1007
        // Result may change in a package context
1008
47
        return state.Invalid(TxValidationResult::TX_RECONSIDERABLE,
1009
47
                             strprintf("insufficient fee%s", ws.m_sibling_eviction ? " (including sibling eviction)" : ""), *err_string);
1010
47
    }
1011
1012
    // Add all the to-be-removed transactions to the changeset.
1013
1.79k
    for (auto it : all_conflicts) {
1014
1.79k
        m_subpackage.m_changeset->StageRemoval(it);
1015
1.79k
    }
1016
1017
    // Run cluster size limit checks and fail if we exceed them.
1018
1.34k
    if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1019
10
        return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-large-cluster", "");
1020
10
    }
1021
1022
1.33k
    if (const auto err_string{ImprovesFeerateDiagram(*m_subpackage.m_changeset)}) {
1023
        // We checked above for the cluster size limits being respected, so a
1024
        // failure here can only be due to an insufficient fee.
1025
4
        Assume(err_string->first == DiagramCheckError::FAILURE);
1026
4
        return state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "replacement-failed", err_string->second);
1027
4
    }
1028
1029
1.33k
    return true;
1030
1.33k
}
1031
1032
bool MemPoolAccept::PackageRBFChecks(const std::vector<CTransactionRef>& txns,
1033
                                     std::vector<Workspace>& workspaces,
1034
                                     PackageValidationState& package_state)
1035
18
{
1036
18
    AssertLockHeld(cs_main);
1037
18
    AssertLockHeld(m_pool.cs);
1038
1039
18
    assert(std::all_of(txns.cbegin(), txns.cend(), [this](const auto& tx)
1040
18
                       { return !m_pool.exists(tx->GetHash());}));
1041
1042
18
    assert(txns.size() == workspaces.size());
1043
1044
    // We're in package RBF context; replacement proposal must be size 2
1045
18
    if (workspaces.size() != 2 || !Assume(IsChildWithParents(txns))) {
1046
1
        return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package RBF failed: package must be 1-parent-1-child");
1047
1
    }
1048
1049
    // If the package has in-mempool parents, we won't consider a package RBF
1050
    // since it would result in a cluster larger than 2.
1051
    // N.B. To relax this constraint we will need to revisit how CCoinsViewMemPool::PackageAddTransaction
1052
    // is being used inside AcceptMultipleTransactions to track available inputs while processing a package.
1053
    // Specifically we would need to check that the ancestors of the new
1054
    // transactions don't intersect with the set of transactions to be removed
1055
    // due to RBF, which is not checked at all in the package acceptance
1056
    // context.
1057
33
    for (const auto& ws : workspaces) {
1058
33
        if (!ws.m_parents.empty()) {
1059
2
            return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package RBF failed: new transaction cannot have mempool ancestors");
1060
2
        }
1061
33
    }
1062
1063
    // Aggregate all conflicts into one set.
1064
15
    CTxMemPool::setEntries direct_conflict_iters;
1065
30
    for (Workspace& ws : workspaces) {
1066
        // Aggregate all conflicts into one set.
1067
30
        direct_conflict_iters.merge(ws.m_iters_conflicting);
1068
30
    }
1069
1070
15
    const auto& parent_ws = workspaces[0];
1071
15
    const auto& child_ws = workspaces[1];
1072
1073
    // Don't consider replacements that would cause us to remove a large number of mempool entries.
1074
    // This limit is not increased in a package RBF. Use the aggregate number of transactions.
1075
15
    CTxMemPool::setEntries all_conflicts;
1076
15
    if (const auto err_string{GetEntriesForConflicts(*child_ws.m_ptx, m_pool, direct_conflict_iters,
1077
15
                                                     all_conflicts)}) {
1078
0
        return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1079
0
                                     "package RBF failed: too many potential replacements", *err_string);
1080
0
    }
1081
1082
389
    for (CTxMemPool::txiter it : all_conflicts) {
1083
389
        m_subpackage.m_changeset->StageRemoval(it);
1084
389
        m_subpackage.m_conflicting_fees += it->GetModifiedFee();
1085
389
        m_subpackage.m_conflicting_size += it->GetTxSize();
1086
389
    }
1087
1088
    // Use the child as the transaction for attributing errors to.
1089
15
    const Txid& child_hash = child_ws.m_ptx->GetHash();
1090
15
    if (const auto err_string{PaysForRBF(/*original_fees=*/m_subpackage.m_conflicting_fees,
1091
15
                                         /*replacement_fees=*/m_subpackage.m_total_modified_fees,
1092
15
                                         /*replacement_vsize=*/m_subpackage.m_total_vsize,
1093
15
                                         m_pool.m_opts.incremental_relay_feerate, child_hash)}) {
1094
3
        return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1095
3
                                     "package RBF failed: insufficient anti-DoS fees", *err_string);
1096
3
    }
1097
1098
    // Ensure this two transaction package is a "chunk" on its own; we don't want the child
1099
    // to be only paying anti-DoS fees
1100
12
    const CFeeRate parent_feerate(parent_ws.m_modified_fees, parent_ws.m_vsize);
1101
12
    const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1102
12
    if (package_feerate <= parent_feerate) {
1103
1
        return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1104
1
                                     "package RBF failed: package feerate is less than or equal to parent feerate",
1105
1
                                     strprintf("package feerate %s <= parent feerate is %s", package_feerate.ToString(), parent_feerate.ToString()));
1106
1
    }
1107
1108
    // Run cluster size limit checks and fail if we exceed them.
1109
11
    if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1110
0
        return package_state.Invalid(PackageValidationResult::PCKG_POLICY, "too-large-cluster", "");
1111
0
    }
1112
1113
    // Check if it's economically rational to mine this package rather than the ones it replaces.
1114
11
    if (const auto err_tup{ImprovesFeerateDiagram(*m_subpackage.m_changeset)}) {
1115
1
        Assume(err_tup->first == DiagramCheckError::FAILURE);
1116
1
        return package_state.Invalid(PackageValidationResult::PCKG_POLICY,
1117
1
                                     "package RBF failed: " + err_tup.value().second, "");
1118
1
    }
1119
1120
10
    LogDebug(BCLog::TXPACKAGES, "package RBF checks passed: parent %s (wtxid=%s), child %s (wtxid=%s), package hash (%s)\n",
1121
10
        txns.front()->GetHash().ToString(), txns.front()->GetWitnessHash().ToString(),
1122
10
        txns.back()->GetHash().ToString(), txns.back()->GetWitnessHash().ToString(),
1123
10
        GetPackageHash(txns).ToString());
1124
1125
1126
10
    return true;
1127
11
}
1128
1129
bool MemPoolAccept::PolicyScriptChecks(Workspace& ws)
1130
45.6k
{
1131
45.6k
    AssertLockHeld(cs_main);
1132
45.6k
    AssertLockHeld(m_pool.cs);
1133
45.6k
    const CTransaction& tx = *ws.m_ptx;
1134
45.6k
    TxValidationState& state = ws.m_state;
1135
1136
45.6k
    constexpr script_verify_flags scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
1137
1138
    // Check input scripts and signatures.
1139
    // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1140
45.6k
    if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, ws.m_precomputed_txdata, GetValidationCache())) {
1141
        // Detect a failure due to a missing witness so that p2p code can handle rejection caching appropriately.
1142
1.66k
        if (!tx.HasWitness() && SpendsNonAnchorWitnessProg(tx, m_view)) {
1143
22
            state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
1144
22
                    state.GetRejectReason(), state.GetDebugMessage());
1145
22
        }
1146
1.66k
        return false; // state filled in by CheckInputScripts
1147
1.66k
    }
1148
1149
43.9k
    return true;
1150
45.6k
}
1151
1152
bool MemPoolAccept::ConsensusScriptChecks(Workspace& ws)
1153
43.4k
{
1154
43.4k
    AssertLockHeld(cs_main);
1155
43.4k
    AssertLockHeld(m_pool.cs);
1156
43.4k
    const CTransaction& tx = *ws.m_ptx;
1157
43.4k
    const Txid& hash = ws.m_hash;
1158
43.4k
    TxValidationState& state = ws.m_state;
1159
1160
    // Check again against the current block tip's script verification
1161
    // flags to cache our script execution flags. This is, of course,
1162
    // useless if the next block has different script flags from the
1163
    // previous one, but because the cache tracks script flags for us it
1164
    // will auto-invalidate and we'll just have a few blocks of extra
1165
    // misses on soft-fork activation.
1166
    //
1167
    // This is also useful in case of bugs in the standard flags that cause
1168
    // transactions to pass as valid when they're actually invalid. For
1169
    // instance the STRICTENC flag was incorrectly allowing certain
1170
    // CHECKSIG NOT scripts to pass, even though they were invalid.
1171
    //
1172
    // There is a similar check in CreateNewBlock() to prevent creating
1173
    // invalid blocks (using TestBlockValidity), however allowing such
1174
    // transactions into the mempool can be exploited as a DoS attack.
1175
43.4k
    script_verify_flags currentBlockScriptVerifyFlags{GetBlockScriptFlags(*m_active_chainstate.m_chain.Tip(), m_active_chainstate.m_chainman)};
1176
43.4k
    if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags,
1177
43.4k
                                        ws.m_precomputed_txdata, m_active_chainstate.CoinsTip(), GetValidationCache())) {
1178
0
        LogError("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s", hash.ToString(), state.ToString());
1179
0
        return Assume(false);
1180
0
    }
1181
1182
43.4k
    return true;
1183
43.4k
}
1184
1185
void MemPoolAccept::FinalizeSubpackage(const ATMPArgs& args)
1186
26.8k
{
1187
26.8k
    AssertLockHeld(cs_main);
1188
26.8k
    AssertLockHeld(m_pool.cs);
1189
1190
26.8k
    if (!m_subpackage.m_changeset->GetRemovals().empty()) Assume(args.m_allow_replacement);
1191
    // Remove conflicting transactions from the mempool
1192
26.8k
    for (CTxMemPool::txiter it : m_subpackage.m_changeset->GetRemovals())
1193
1.60k
    {
1194
1.60k
        std::string log_string = strprintf("replacing mempool tx %s (wtxid=%s, fees=%s, vsize=%s). ",
1195
1.60k
                                      it->GetTx().GetHash().ToString(),
1196
1.60k
                                      it->GetTx().GetWitnessHash().ToString(),
1197
1.60k
                                      it->GetFee(),
1198
1.60k
                                      it->GetTxSize());
1199
1.60k
        FeeFrac feerate{m_subpackage.m_total_modified_fees, int32_t(m_subpackage.m_total_vsize)};
1200
1.60k
        uint256 tx_or_package_hash{};
1201
1.60k
        const bool replaced_with_tx{m_subpackage.m_changeset->GetTxCount() == 1};
1202
1.60k
        if (replaced_with_tx) {
1203
1.22k
            const CTransaction& tx = m_subpackage.m_changeset->GetAddedTxn(0);
1204
1.22k
            tx_or_package_hash = tx.GetHash().ToUint256();
1205
1.22k
            log_string += strprintf("New tx %s (wtxid=%s, fees=%s, vsize=%s)",
1206
1.22k
                                    tx.GetHash().ToString(),
1207
1.22k
                                    tx.GetWitnessHash().ToString(),
1208
1.22k
                                    feerate.fee,
1209
1.22k
                                    feerate.size);
1210
1.22k
        } else {
1211
379
            tx_or_package_hash = GetPackageHash(m_subpackage.m_changeset->GetAddedTxns());
1212
379
            log_string += strprintf("New package %s with %lu txs, fees=%s, vsize=%s",
1213
379
                                    tx_or_package_hash.ToString(),
1214
379
                                    m_subpackage.m_changeset->GetTxCount(),
1215
379
                                    feerate.fee,
1216
379
                                    feerate.size);
1217
1218
379
        }
1219
1.60k
        LogDebug(BCLog::MEMPOOL, "%s\n", log_string);
1220
1.60k
        TRACEPOINT(mempool, replaced,
1221
1.60k
                it->GetTx().GetHash().data(),
1222
1.60k
                it->GetTxSize(),
1223
1.60k
                it->GetFee(),
1224
1.60k
                std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count(),
1225
1.60k
                tx_or_package_hash.data(),
1226
1.60k
                feerate.size,
1227
1.60k
                feerate.fee,
1228
1.60k
                replaced_with_tx
1229
1.60k
        );
1230
1.60k
        m_subpackage.m_replaced_transactions.push_back(it->GetSharedTx());
1231
1.60k
    }
1232
26.8k
    m_subpackage.m_changeset->Apply();
1233
26.8k
    m_subpackage.m_changeset.reset();
1234
26.8k
}
1235
1236
bool MemPoolAccept::SubmitPackage(const ATMPArgs& args, std::vector<Workspace>& workspaces,
1237
                                  PackageValidationState& package_state,
1238
                                  std::map<Wtxid, MempoolAcceptResult>& results)
1239
68
{
1240
68
    AssertLockHeld(cs_main);
1241
68
    AssertLockHeld(m_pool.cs);
1242
    // Sanity check: none of the transactions should be in the mempool, and none of the transactions
1243
    // should have a same-txid-different-witness equivalent in the mempool.
1244
68
    assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [this](const auto& ws) { return !m_pool.exists(ws.m_ptx->GetHash()); }));
1245
1246
68
    bool all_submitted = true;
1247
68
    FinalizeSubpackage(args);
1248
    // ConsensusScriptChecks adds to the script cache and is therefore consensus-critical;
1249
    // CheckInputsFromMempoolAndCache asserts that transactions only spend coins available from the
1250
    // mempool or UTXO set. Submit each transaction to the mempool immediately after calling
1251
    // ConsensusScriptChecks to make the outputs available for subsequent transactions.
1252
136
    for (Workspace& ws : workspaces) {
1253
136
        if (!ConsensusScriptChecks(ws)) {
1254
0
            results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1255
            // Since PolicyScriptChecks() passed, this should never fail.
1256
0
            Assume(false);
1257
0
            all_submitted = false;
1258
0
            package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
1259
0
                                  strprintf("BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
1260
0
                                            ws.m_ptx->GetHash().ToString()));
1261
0
        }
1262
        // Remove first failing tx and all subsequent in package
1263
136
        if (!all_submitted) {
1264
0
            if (!m_subpackage.m_changeset) m_subpackage.m_changeset = m_pool.GetChangeSet();
1265
0
            m_subpackage.m_changeset->StageRemoval(m_pool.GetIter(ws.m_ptx->GetHash()).value());
1266
0
        }
1267
136
    }
1268
68
    if (!all_submitted) {
1269
0
        Assume(m_subpackage.m_changeset);
1270
        // This code should be unreachable; it's here as belt-and-suspenders
1271
        // to try to ensure we have no consensus-invalid transactions in the
1272
        // mempool.
1273
0
        m_subpackage.m_changeset->Apply();
1274
0
        m_subpackage.m_changeset.reset();
1275
0
        return false;
1276
0
    }
1277
1278
68
    std::vector<Wtxid> all_package_wtxids;
1279
68
    all_package_wtxids.reserve(workspaces.size());
1280
68
    std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1281
136
                   [](const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1282
1283
68
    if (!m_subpackage.m_replaced_transactions.empty()) {
1284
10
        LogDebug(BCLog::MEMPOOL, "replaced %u mempool transactions with %u new one(s) for %s additional fees, %d delta bytes\n",
1285
10
                 m_subpackage.m_replaced_transactions.size(), workspaces.size(),
1286
10
                 m_subpackage.m_total_modified_fees - m_subpackage.m_conflicting_fees,
1287
10
                 m_subpackage.m_total_vsize - static_cast<int>(m_subpackage.m_conflicting_size));
1288
10
    }
1289
1290
    // Add successful results. The returned results may change later if LimitMempoolSize() evicts them.
1291
136
    for (Workspace& ws : workspaces) {
1292
136
        auto iter = m_pool.GetIter(ws.m_ptx->GetHash());
1293
136
        Assume(iter.has_value());
1294
136
        const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
1295
136
            CFeeRate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1296
136
        const auto effective_feerate_wtxids = args.m_package_feerates ? all_package_wtxids :
1297
136
            std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1298
136
        results.emplace(ws.m_ptx->GetWitnessHash(),
1299
136
                        MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize,
1300
136
                                         ws.m_base_fees, effective_feerate, effective_feerate_wtxids));
1301
136
        if (!m_pool.m_opts.signals) continue;
1302
136
        const CTransaction& tx = *ws.m_ptx;
1303
136
        const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1304
136
                                                       ws.m_vsize, (*iter)->GetHeight(),
1305
136
                                                       args.m_bypass_limits, args.m_package_submission,
1306
136
                                                       IsCurrentForFeeEstimation(m_active_chainstate),
1307
136
                                                       m_pool.HasNoInputsOf(tx));
1308
136
        m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1309
136
    }
1310
68
    return all_submitted;
1311
68
}
1312
1313
MempoolAcceptResult MemPoolAccept::AcceptSingleTransactionInternal(const CTransactionRef& ptx, ATMPArgs& args)
1314
52.9k
{
1315
52.9k
    AssertLockHeld(cs_main);
1316
52.9k
    AssertLockHeld(m_pool.cs);
1317
1318
52.9k
    Workspace ws(ptx);
1319
52.9k
    const std::vector<Wtxid> single_wtxid{ws.m_ptx->GetWitnessHash()};
1320
1321
52.9k
    if (!PreChecks(args, ws)) {
1322
7.77k
        if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
1323
            // Failed for fee reasons. Provide the effective feerate and which tx was included.
1324
138
            return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_wtxid);
1325
138
        }
1326
7.63k
        return MempoolAcceptResult::Failure(ws.m_state);
1327
7.77k
    }
1328
1329
45.1k
    if (m_subpackage.m_rbf && !ReplacementChecks(ws)) {
1330
65
        if (ws.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE) {
1331
            // Failed for incentives-based fee reasons. Provide the effective feerate and which tx was included.
1332
51
            return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_wtxid);
1333
51
        }
1334
14
        return MempoolAcceptResult::Failure(ws.m_state);
1335
65
    }
1336
1337
    // Check if the transaction would exceed the cluster size limit.
1338
45.0k
    if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1339
112
        ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-large-cluster", "");
1340
112
        return MempoolAcceptResult::Failure(ws.m_state);
1341
112
    }
1342
1343
    // Now that we've verified the cluster limit is respected, we can perform
1344
    // calculations involving the full ancestors of the tx.
1345
44.9k
    if (ws.m_conflicts.size()) {
1346
1.33k
        auto ancestors = m_subpackage.m_changeset->CalculateMemPoolAncestors(ws.m_tx_handle);
1347
1348
        // A transaction that spends outputs that would be replaced by it is invalid. Now
1349
        // that we have the set of all ancestors we can detect this
1350
        // pathological case by making sure ws.m_conflicts and this tx's ancestors don't
1351
        // intersect.
1352
1.33k
        if (const auto err_string{EntriesAndTxidsDisjoint(ancestors, ws.m_conflicts, ptx->GetHash())}) {
1353
            // We classify this as a consensus error because a transaction depending on something it
1354
            // conflicts with would be inconsistent.
1355
5
            ws.m_state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
1356
5
            return MempoolAcceptResult::Failure(ws.m_state);
1357
5
        }
1358
1.33k
    }
1359
1360
44.9k
    m_subpackage.m_total_vsize = ws.m_vsize;
1361
44.9k
    m_subpackage.m_total_modified_fees = ws.m_modified_fees;
1362
1363
    // Individual modified feerate exceeded caller-defined max; abort
1364
44.9k
    if (args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) > args.m_client_maxfeerate.value()) {
1365
1
        ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "max feerate exceeded", "");
1366
1
        return MempoolAcceptResult::Failure(ws.m_state);
1367
1
    }
1368
1369
44.9k
    if (!args.m_bypass_limits && m_pool.m_opts.require_standard) {
1370
43.4k
        Wtxid dummy_wtxid;
1371
43.4k
        if (!CheckEphemeralSpends(/*package=*/{ptx}, m_pool.m_opts.dust_relay_feerate, m_pool, ws.m_state, dummy_wtxid)) {
1372
4
            return MempoolAcceptResult::Failure(ws.m_state);
1373
4
        }
1374
43.4k
    }
1375
1376
    // Perform the inexpensive checks first and avoid hashing and signature verification unless
1377
    // those checks pass, to mitigate CPU exhaustion denial-of-service attacks.
1378
44.9k
    if (!PolicyScriptChecks(ws)) return MempoolAcceptResult::Failure(ws.m_state);
1379
1380
43.3k
    if (!ConsensusScriptChecks(ws)) return MempoolAcceptResult::Failure(ws.m_state);
1381
1382
43.3k
    const CFeeRate effective_feerate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1383
    // Tx was accepted, but not added
1384
43.3k
    if (args.m_test_accept) {
1385
16.5k
        return MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize,
1386
16.5k
                                            ws.m_base_fees, effective_feerate, single_wtxid);
1387
16.5k
    }
1388
1389
26.7k
    FinalizeSubpackage(args);
1390
1391
    // Limit the mempool, if appropriate.
1392
26.7k
    if (!args.m_package_submission && !args.m_bypass_limits) {
1393
25.7k
        LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip());
1394
        // If mempool contents change, then the m_view cache is dirty. Given this isn't a package
1395
        // submission, we won't be using the cache anymore, but clear it anyway for clarity.
1396
25.7k
        CleanupTemporaryCoins();
1397
1398
25.7k
        if (!m_pool.exists(ws.m_hash)) {
1399
            // The tx no longer meets our (new) mempool minimum feerate but could be reconsidered in a package.
1400
0
            ws.m_state.Invalid(TxValidationResult::TX_RECONSIDERABLE, "mempool full");
1401
0
            return MempoolAcceptResult::FeeFailure(ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), {ws.m_ptx->GetWitnessHash()});
1402
0
        }
1403
25.7k
    }
1404
1405
26.7k
    if (m_pool.m_opts.signals) {
1406
26.7k
        const CTransaction& tx = *ws.m_ptx;
1407
26.7k
        auto iter = m_pool.GetIter(tx.GetHash());
1408
26.7k
        Assume(iter.has_value());
1409
26.7k
        const auto tx_info = NewMempoolTransactionInfo(ws.m_ptx, ws.m_base_fees,
1410
26.7k
                                                       ws.m_vsize, (*iter)->GetHeight(),
1411
26.7k
                                                       args.m_bypass_limits, args.m_package_submission,
1412
26.7k
                                                       IsCurrentForFeeEstimation(m_active_chainstate),
1413
26.7k
                                                       m_pool.HasNoInputsOf(tx));
1414
26.7k
        m_pool.m_opts.signals->TransactionAddedToMempool(tx_info, m_pool.GetAndIncrementSequence());
1415
26.7k
    }
1416
1417
26.7k
    if (!m_subpackage.m_replaced_transactions.empty()) {
1418
949
        LogDebug(BCLog::MEMPOOL, "replaced %u mempool transactions with 1 new transaction for %s additional fees, %d delta bytes\n",
1419
949
                 m_subpackage.m_replaced_transactions.size(),
1420
949
                 ws.m_modified_fees - m_subpackage.m_conflicting_fees,
1421
949
                 ws.m_vsize - static_cast<int>(m_subpackage.m_conflicting_size));
1422
949
    }
1423
1424
26.7k
    return MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions), ws.m_vsize, ws.m_base_fees,
1425
26.7k
                                        effective_feerate, single_wtxid);
1426
26.7k
}
1427
1428
PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactionsInternal(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
1429
176
{
1430
176
    AssertLockHeld(cs_main);
1431
176
    AssertLockHeld(m_pool.cs);
1432
1433
    // These context-free package limits can be done before taking the mempool lock.
1434
176
    PackageValidationState package_state;
1435
176
    if (!IsWellFormedPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
1436
1437
170
    std::vector<Workspace> workspaces{};
1438
170
    workspaces.reserve(txns.size());
1439
170
    std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1440
826
                   [](const auto& tx) { return Workspace(tx); });
1441
170
    std::map<Wtxid, MempoolAcceptResult> results;
1442
1443
    // Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
1444
793
    for (Workspace& ws : workspaces) {
1445
793
        if (!PreChecks(args, ws)) {
1446
13
            package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1447
            // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1448
13
            results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1449
13
            return PackageMempoolAcceptResult(package_state, std::move(results));
1450
13
        }
1451
1452
        // Individual modified feerate exceeded caller-defined max; abort
1453
        // N.B. this doesn't take into account CPFPs. Chunk-aware validation may be more robust.
1454
780
        if (args.m_client_maxfeerate && CFeeRate(ws.m_modified_fees, ws.m_vsize) > args.m_client_maxfeerate.value()) {
1455
            // Need to set failure here both individually and at package level
1456
1
            ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "max feerate exceeded", "");
1457
1
            package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1458
            // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1459
1
            results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1460
1
            return PackageMempoolAcceptResult(package_state, std::move(results));
1461
1
        }
1462
1463
        // Make the coins created by this transaction available for subsequent transactions in the
1464
        // package to spend. If there are no conflicts within the package, no transaction can spend a coin
1465
        // needed by another transaction in the package. We also need to make sure that no package
1466
        // tx replaces (or replaces the ancestor of) the parent of another package tx. As long as we
1467
        // check these two things, we don't need to track the coins spent.
1468
        // If a package tx conflicts with a mempool tx, PackageRBFChecks() ensures later that any package RBF attempt
1469
        // has *no* in-mempool ancestors, so we don't have to worry about subsequent transactions in
1470
        // same package spending the same in-mempool outpoints. This needs to be revisited for general
1471
        // package RBF.
1472
779
        m_viewmempool.PackageAddTransaction(ws.m_ptx);
1473
779
    }
1474
1475
    // At this point we have all in-mempool parents, and we know every transaction's vsize.
1476
    // Run the TRUC checks on the package.
1477
765
    for (Workspace& ws : workspaces) {
1478
765
        if (auto err{PackageTRUCChecks(m_pool, ws.m_ptx, ws.m_vsize, txns, ws.m_parents)}) {
1479
10
            package_state.Invalid(PackageValidationResult::PCKG_POLICY, "TRUC-violation", err.value());
1480
10
            return PackageMempoolAcceptResult(package_state, {});
1481
10
        }
1482
765
    }
1483
1484
    // Transactions must meet two minimum feerates: the mempool minimum fee and min relay fee.
1485
    // For transactions consisting of exactly one child and its parents, it suffices to use the
1486
    // package feerate (total modified fees / total virtual size) to check this requirement.
1487
    // Note that this is an aggregate feerate; this function has not checked that there are transactions
1488
    // too low feerate to pay for themselves, or that the child transactions are higher feerate than
1489
    // their parents. Using aggregate feerate may allow "parents pay for child" behavior and permit
1490
    // a child that is below mempool minimum feerate. To avoid these behaviors, callers of
1491
    // AcceptMultipleTransactions need to restrict txns topology (e.g. to ancestor sets) and check
1492
    // the feerates of individuals and subsets.
1493
146
    m_subpackage.m_total_vsize = std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1494
746
        [](int64_t sum, auto& ws) { return sum + ws.m_vsize; });
1495
146
    m_subpackage.m_total_modified_fees = std::accumulate(workspaces.cbegin(), workspaces.cend(), CAmount{0},
1496
746
        [](CAmount sum, auto& ws) { return sum + ws.m_modified_fees; });
1497
146
    const CFeeRate package_feerate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize);
1498
146
    std::vector<Wtxid> all_package_wtxids;
1499
146
    all_package_wtxids.reserve(workspaces.size());
1500
146
    std::transform(workspaces.cbegin(), workspaces.cend(), std::back_inserter(all_package_wtxids),
1501
746
                   [](const auto& ws) { return ws.m_ptx->GetWitnessHash(); });
1502
146
    TxValidationState placeholder_state;
1503
146
    if (args.m_package_feerates &&
1504
146
        !CheckFeeRate(m_subpackage.m_total_vsize, m_subpackage.m_total_modified_fees, placeholder_state)) {
1505
12
        package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1506
12
        return PackageMempoolAcceptResult(package_state, {{workspaces.back().m_ptx->GetWitnessHash(),
1507
12
            MempoolAcceptResult::FeeFailure(placeholder_state, CFeeRate(m_subpackage.m_total_modified_fees, m_subpackage.m_total_vsize), all_package_wtxids)}});
1508
12
    }
1509
1510
    // Apply package mempool RBF checks.
1511
134
    if (m_subpackage.m_rbf && !PackageRBFChecks(txns, workspaces, package_state)) {
1512
8
        return PackageMempoolAcceptResult(package_state, std::move(results));
1513
8
    }
1514
1515
    // Check if the transactions would exceed the cluster size limit.
1516
126
    if (!m_subpackage.m_changeset->CheckMemPoolPolicyLimits()) {
1517
7
        package_state.Invalid(PackageValidationResult::PCKG_POLICY, "too-large-cluster", "");
1518
7
        return PackageMempoolAcceptResult(package_state, std::move(results));
1519
7
    }
1520
1521
    // Now that we've bounded the resulting possible ancestry count, check package for dust spends
1522
119
    if (m_pool.m_opts.require_standard) {
1523
119
        TxValidationState child_state;
1524
119
        Wtxid child_wtxid;
1525
119
        if (!CheckEphemeralSpends(txns, m_pool.m_opts.dust_relay_feerate, m_pool, child_state, child_wtxid)) {
1526
1
            package_state.Invalid(PackageValidationResult::PCKG_TX, "unspent-dust");
1527
1
            results.emplace(child_wtxid, MempoolAcceptResult::Failure(child_state));
1528
1
            return PackageMempoolAcceptResult(package_state, std::move(results));
1529
1
        }
1530
119
    }
1531
1532
656
    for (Workspace& ws : workspaces) {
1533
656
        ws.m_package_feerate = package_feerate;
1534
656
        if (!PolicyScriptChecks(ws)) {
1535
            // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
1536
2
            package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1537
2
            results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
1538
2
            return PackageMempoolAcceptResult(package_state, std::move(results));
1539
2
        }
1540
654
        if (args.m_test_accept) {
1541
517
            const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
1542
517
                CFeeRate{ws.m_modified_fees, static_cast<int32_t>(ws.m_vsize)};
1543
517
            const auto effective_feerate_wtxids = args.m_package_feerates ? all_package_wtxids :
1544
517
                std::vector<Wtxid>{ws.m_ptx->GetWitnessHash()};
1545
517
            results.emplace(ws.m_ptx->GetWitnessHash(),
1546
517
                            MempoolAcceptResult::Success(std::move(m_subpackage.m_replaced_transactions),
1547
517
                                                         ws.m_vsize, ws.m_base_fees, effective_feerate,
1548
517
                                                         effective_feerate_wtxids));
1549
517
        }
1550
654
    }
1551
1552
116
    if (args.m_test_accept) return PackageMempoolAcceptResult(package_state, std::move(results));
1553
1554
68
    if (!SubmitPackage(args, workspaces, package_state, results)) {
1555
        // PackageValidationState filled in by SubmitPackage().
1556
0
        return PackageMempoolAcceptResult(package_state, std::move(results));
1557
0
    }
1558
1559
68
    return PackageMempoolAcceptResult(package_state, std::move(results));
1560
68
}
1561
1562
void MemPoolAccept::CleanupTemporaryCoins()
1563
79.0k
{
1564
    // There are 3 kinds of coins in m_view:
1565
    // (1) Temporary coins from the transactions in subpackage, constructed by m_viewmempool.
1566
    // (2) Mempool coins from transactions in the mempool, constructed by m_viewmempool.
1567
    // (3) Confirmed coins fetched from our current UTXO set.
1568
    //
1569
    // (1) Temporary coins need to be removed, regardless of whether the transaction was submitted.
1570
    // If the transaction was submitted to the mempool, m_viewmempool will be able to fetch them from
1571
    // there. If it wasn't submitted to mempool, it is incorrect to keep them - future calls may try
1572
    // to spend those coins that don't actually exist.
1573
    // (2) Mempool coins also need to be removed. If the mempool contents have changed as a result
1574
    // of submitting or replacing transactions, coins previously fetched from mempool may now be
1575
    // spent or nonexistent. Those coins need to be deleted from m_view.
1576
    // (3) Confirmed coins don't need to be removed. The chainstate has not changed (we are
1577
    // holding cs_main and no blocks have been processed) so the confirmed tx cannot disappear like
1578
    // a mempool tx can. The coin may now be spent after we submitted a tx to mempool, but
1579
    // we have already checked that the package does not have 2 transactions spending the same coin
1580
    // and we check whether a mempool transaction spends conflicting coins (CTxMemPool::GetConflictTx).
1581
    // Keeping them in m_view is an optimization to not re-fetch confirmed coins if we later look up
1582
    // inputs for this transaction again.
1583
79.0k
    for (const auto& outpoint : m_viewmempool.GetNonBaseCoins()) {
1584
        // In addition to resetting m_viewmempool, we also need to manually delete these coins from
1585
        // m_view because it caches copies of the coins it fetched from m_viewmempool previously.
1586
8.74k
        m_view.Uncache(outpoint);
1587
8.74k
    }
1588
    // This deletes the temporary and mempool coins.
1589
79.0k
    m_viewmempool.Reset();
1590
79.0k
}
1591
1592
PackageMempoolAcceptResult MemPoolAccept::AcceptSubPackage(const std::vector<CTransactionRef>& subpackage, ATMPArgs& args)
1593
476
{
1594
476
    AssertLockHeld(::cs_main);
1595
476
    AssertLockHeld(m_pool.cs);
1596
476
    auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs) {
1597
476
        if (subpackage.size() > 1) {
1598
98
            return AcceptMultipleTransactionsInternal(subpackage, args);
1599
98
        }
1600
378
        const auto& tx = subpackage.front();
1601
378
        ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1602
378
        const auto single_res = AcceptSingleTransactionInternal(tx, single_args);
1603
378
        PackageValidationState package_state_wrapped;
1604
378
        if (single_res.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1605
231
            package_state_wrapped.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1606
231
        }
1607
378
        return PackageMempoolAcceptResult(package_state_wrapped, {{tx->GetWitnessHash(), single_res}});
1608
476
    }();
1609
1610
    // Clean up m_view and m_viewmempool so that other subpackage evaluations don't have access to
1611
    // coins they shouldn't. Keep some coins in order to minimize re-fetching coins from the UTXO set.
1612
    // Clean up package feerate and rbf calculations
1613
476
    ClearSubPackageState();
1614
1615
476
    return result;
1616
476
}
1617
1618
PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(const Package& package, ATMPArgs& args)
1619
171
{
1620
171
    Assert(!package.empty());
1621
171
    AssertLockHeld(cs_main);
1622
    // Used if returning a PackageMempoolAcceptResult directly from this function.
1623
171
    PackageValidationState package_state_quit_early;
1624
1625
    // There are two topologies we are able to handle through this function:
1626
    // (1) A single transaction
1627
    // (2) A child-with-parents package.
1628
    // Check that the package is well-formed. If it isn't, we won't try to validate any of the
1629
    // transactions and thus won't return any MempoolAcceptResults, just a package-wide error.
1630
1631
    // Context-free package checks.
1632
171
    if (!IsWellFormedPackage(package, package_state_quit_early)) {
1633
2
        return PackageMempoolAcceptResult(package_state_quit_early, {});
1634
2
    }
1635
1636
169
    if (package.size() > 1 && !IsChildWithParents(package)) {
1637
        // All transactions in the package must be a parent of the last transaction. This is just an
1638
        // opportunity for us to fail fast on a context-free check without taking the mempool lock.
1639
2
        package_state_quit_early.Invalid(PackageValidationResult::PCKG_POLICY, "package-not-child-with-parents");
1640
2
        return PackageMempoolAcceptResult(package_state_quit_early, {});
1641
2
    }
1642
1643
167
    LOCK(m_pool.cs);
1644
    // Stores results from which we will create the returned PackageMempoolAcceptResult.
1645
    // A result may be changed if a mempool transaction is evicted later due to LimitMempoolSize().
1646
167
    std::map<Wtxid, MempoolAcceptResult> results_final;
1647
    // Results from individual validation which will be returned if no other result is available for
1648
    // this transaction. "Nonfinal" because if a transaction fails by itself but succeeds later
1649
    // (i.e. when evaluated with a fee-bumping child), the result in this map may be discarded.
1650
167
    std::map<Wtxid, MempoolAcceptResult> individual_results_nonfinal;
1651
    // Tracks whether we think package submission could result in successful entry to the mempool
1652
167
    bool quit_early{false};
1653
167
    std::vector<CTransactionRef> txns_package_eval;
1654
476
    for (const auto& tx : package) {
1655
476
        const auto& wtxid = tx->GetWitnessHash();
1656
476
        const auto& txid = tx->GetHash();
1657
        // There are 3 possibilities: already in mempool, same-txid-diff-wtxid already in mempool,
1658
        // or not in mempool. An already confirmed tx is treated as one not in mempool, because all
1659
        // we know is that the inputs aren't available.
1660
476
        if (m_pool.exists(wtxid)) {
1661
            // Exact transaction already exists in the mempool.
1662
            // Node operators are free to set their mempool policies however they please, nodes may receive
1663
            // transactions in different orders, and malicious counterparties may try to take advantage of
1664
            // policy differences to pin or delay propagation of transactions. As such, it's possible for
1665
            // some package transaction(s) to already be in the mempool, and we don't want to reject the
1666
            // entire package in that case (as that could be a censorship vector). De-duplicate the
1667
            // transactions that are already in the mempool, and only call AcceptMultipleTransactions() with
1668
            // the new transactions. This ensures we don't double-count transaction counts and sizes when
1669
            // checking ancestor/descendant limits, or double-count transaction fees for fee-related policy.
1670
97
            const auto& entry{*Assert(m_pool.GetEntry(txid))};
1671
97
            results_final.emplace(wtxid, MempoolAcceptResult::MempoolTx(entry.GetTxSize(), entry.GetFee()));
1672
379
        } else if (m_pool.exists(txid)) {
1673
            // Transaction with the same non-witness data but different witness (same txid,
1674
            // different wtxid) already exists in the mempool.
1675
            //
1676
            // We don't allow replacement transactions right now, so just swap the package
1677
            // transaction for the mempool one. Note that we are ignoring the validity of the
1678
            // package transaction passed in.
1679
            // TODO: allow witness replacement in packages.
1680
3
            const auto& entry{*Assert(m_pool.GetEntry(txid))};
1681
            // Provide the wtxid of the mempool tx so that the caller can look it up in the mempool.
1682
3
            results_final.emplace(wtxid, MempoolAcceptResult::MempoolTxDifferentWitness(entry.GetTx().GetWitnessHash()));
1683
376
        } else {
1684
            // Transaction does not already exist in the mempool.
1685
            // Try submitting the transaction on its own.
1686
376
            const auto single_package_res = AcceptSubPackage({tx}, args);
1687
376
            const auto& single_res = single_package_res.m_tx_results.at(wtxid);
1688
376
            if (single_res.m_result_type == MempoolAcceptResult::ResultType::VALID) {
1689
                // The transaction succeeded on its own and is now in the mempool. Don't include it
1690
                // in package validation, because its fees should only be "used" once.
1691
147
                assert(m_pool.exists(wtxid));
1692
147
                results_final.emplace(wtxid, single_res);
1693
229
            } else if (package.size() == 1 || // If there is only one transaction, no need to retry it "as a package"
1694
229
                       (single_res.m_state.GetResult() != TxValidationResult::TX_RECONSIDERABLE &&
1695
228
                       single_res.m_state.GetResult() != TxValidationResult::TX_MISSING_INPUTS)) {
1696
                // Package validation policy only differs from individual policy in its evaluation
1697
                // of feerate. For example, if a transaction fails here due to violation of a
1698
                // consensus rule, the result will not change when it is submitted as part of a
1699
                // package. To minimize the amount of repeated work, unless the transaction fails
1700
                // due to feerate or missing inputs (its parent is a previous transaction in the
1701
                // package that failed due to feerate), don't run package validation. Note that this
1702
                // decision might not make sense if different types of packages are allowed in the
1703
                // future.  Continue individually validating the rest of the transactions, because
1704
                // some of them may still be valid.
1705
21
                quit_early = true;
1706
21
                package_state_quit_early.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1707
21
                individual_results_nonfinal.emplace(wtxid, single_res);
1708
208
            } else {
1709
208
                individual_results_nonfinal.emplace(wtxid, single_res);
1710
208
                txns_package_eval.push_back(tx);
1711
208
            }
1712
376
        }
1713
476
    }
1714
1715
167
    auto multi_submission_result = quit_early || txns_package_eval.empty() ? PackageMempoolAcceptResult(package_state_quit_early, {}) :
1716
167
        AcceptSubPackage(txns_package_eval, args);
1717
167
    PackageValidationState& package_state_final = multi_submission_result.m_state;
1718
1719
    // This is invoked by AcceptSubPackage() already, so this is just here for
1720
    // clarity (since it's not permitted to invoke LimitMempoolSize() while a
1721
    // changeset is outstanding).
1722
167
    ClearSubPackageState();
1723
1724
    // Make sure we haven't exceeded max mempool size.
1725
    // Package transactions that were submitted to mempool or already in mempool may be evicted.
1726
    // If mempool contents change, then the m_view cache is dirty. It has already been cleared above.
1727
167
    LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip());
1728
1729
476
    for (const auto& tx : package) {
1730
476
        const auto& wtxid = tx->GetWitnessHash();
1731
476
        if (multi_submission_result.m_tx_results.contains(wtxid)) {
1732
            // We shouldn't have re-submitted if the tx result was already in results_final.
1733
156
            Assume(!results_final.contains(wtxid));
1734
            // If it was submitted, check to see if the tx is still in the mempool. It could have
1735
            // been evicted due to LimitMempoolSize() above.
1736
156
            const auto& txresult = multi_submission_result.m_tx_results.at(wtxid);
1737
156
            if (txresult.m_result_type == MempoolAcceptResult::ResultType::VALID && !m_pool.exists(wtxid)) {
1738
2
                package_state_final.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1739
2
                TxValidationState mempool_full_state;
1740
2
                mempool_full_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1741
2
                results_final.emplace(wtxid, MempoolAcceptResult::Failure(mempool_full_state));
1742
154
            } else {
1743
154
                results_final.emplace(wtxid, txresult);
1744
154
            }
1745
320
        } else if (const auto it{results_final.find(wtxid)}; it != results_final.end()) {
1746
            // Already-in-mempool transaction. Check to see if it's still there, as it could have
1747
            // been evicted when LimitMempoolSize() was called.
1748
247
            Assume(it->second.m_result_type != MempoolAcceptResult::ResultType::INVALID);
1749
247
            Assume(!individual_results_nonfinal.contains(wtxid));
1750
            // Query by txid to include the same-txid-different-witness ones.
1751
247
            if (!m_pool.exists(tx->GetHash())) {
1752
0
                package_state_final.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
1753
0
                TxValidationState mempool_full_state;
1754
0
                mempool_full_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
1755
                // Replace the previous result.
1756
0
                results_final.erase(wtxid);
1757
0
                results_final.emplace(wtxid, MempoolAcceptResult::Failure(mempool_full_state));
1758
0
            }
1759
247
        } else if (const auto it{individual_results_nonfinal.find(wtxid)}; it != individual_results_nonfinal.end()) {
1760
73
            Assume(it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
1761
            // Interesting result from previous processing.
1762
73
            results_final.emplace(wtxid, it->second);
1763
73
        }
1764
476
    }
1765
167
    Assume(results_final.size() == package.size());
1766
167
    return PackageMempoolAcceptResult(package_state_final, std::move(results_final));
1767
167
}
1768
1769
} // anon namespace
1770
1771
MempoolAcceptResult AcceptToMemoryPool(Chainstate& active_chainstate, const CTransactionRef& tx,
1772
                                       int64_t accept_time, bool bypass_limits, bool test_accept)
1773
52.5k
{
1774
52.5k
    AssertLockHeld(::cs_main);
1775
52.5k
    assert(active_chainstate.GetMempool() != nullptr);
1776
52.5k
    CTxMemPool& pool{*active_chainstate.GetMempool()};
1777
1778
52.5k
    std::vector<COutPoint> coins_to_uncache;
1779
1780
52.5k
    auto args = MemPoolAccept::ATMPArgs::SingleAccept(accept_time, bypass_limits, coins_to_uncache, test_accept);
1781
52.5k
    MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransactionAndCleanup(tx, args);
1782
1783
52.5k
    if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
1784
        // Remove coins that were not present in the coins cache before calling
1785
        // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
1786
        // number of invalid transactions that attempt to overrun the in-memory coins cache
1787
        // (`CCoinsViewCache::cacheCoins`).
1788
1789
9.39k
        for (const COutPoint& hashTx : coins_to_uncache)
1790
1.65k
            active_chainstate.CoinsTip().Uncache(hashTx);
1791
9.39k
        TRACEPOINT(mempool, rejected,
1792
9.39k
                tx->GetHash().data(),
1793
9.39k
                result.m_state.GetRejectReason().c_str()
1794
9.39k
        );
1795
9.39k
    }
1796
    // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1797
52.5k
    BlockValidationState state_dummy;
1798
52.5k
    active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1799
52.5k
    return result;
1800
52.5k
}
1801
1802
PackageMempoolAcceptResult ProcessNewPackage(Chainstate& active_chainstate, CTxMemPool& pool,
1803
                                                   const Package& package, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
1804
249
{
1805
249
    AssertLockHeld(cs_main);
1806
249
    assert(!package.empty());
1807
249
    assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
1808
1809
249
    std::vector<COutPoint> coins_to_uncache;
1810
249
    auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1811
249
        AssertLockHeld(cs_main);
1812
249
        if (test_accept) {
1813
78
            auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(GetTime(), coins_to_uncache);
1814
78
            return MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactionsAndCleanup(package, args);
1815
171
        } else {
1816
171
            auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(GetTime(), coins_to_uncache, client_maxfeerate);
1817
171
            return MemPoolAccept(pool, active_chainstate).AcceptPackage(package, args);
1818
171
        }
1819
249
    }();
1820
1821
    // Uncache coins pertaining to transactions that were not submitted to the mempool.
1822
249
    if (test_accept || result.m_state.IsInvalid()) {
1823
763
        for (const COutPoint& hashTx : coins_to_uncache) {
1824
763
            active_chainstate.CoinsTip().Uncache(hashTx);
1825
763
        }
1826
136
    }
1827
    // Ensure the coins cache is still within limits.
1828
249
    BlockValidationState state_dummy;
1829
249
    active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1830
249
    return result;
1831
249
}
1832
1833
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1834
214k
{
1835
214k
    int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1836
    // Force block reward to zero when right shift is undefined.
1837
214k
    if (halvings >= 64)
1838
563
        return 0;
1839
1840
214k
    CAmount nSubsidy = 50 * COIN;
1841
    // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1842
214k
    nSubsidy >>= halvings;
1843
214k
    return nSubsidy;
1844
214k
}
1845
1846
CoinsViews::CoinsViews(DBParams db_params, CoinsViewOptions options)
1847
1.32k
    : m_dbview{std::move(db_params), std::move(options)},
1848
1.32k
      m_catcherview(&m_dbview) {}
1849
1850
void CoinsViews::InitCache(int32_t prevoutfetch_threads)
1851
1.32k
{
1852
1.32k
    AssertLockHeld(::cs_main);
1853
1.32k
    m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1854
1.32k
    auto thread_pool{std::make_shared<ThreadPool>("prevout")};
1855
1.32k
    if (prevoutfetch_threads > 0) {
1856
1.31k
        thread_pool->Start(prevoutfetch_threads);
1857
1.31k
        LogInfo("Block input prevout fetching uses %d additional threads", prevoutfetch_threads);
1858
1.31k
    }
1859
1.32k
    m_connect_block_view = std::make_unique<CoinsViewOverlay>(&*m_cacheview, std::move(thread_pool));
1860
1.32k
}
1861
1862
Chainstate::Chainstate(
1863
    CTxMemPool* mempool,
1864
    BlockManager& blockman,
1865
    ChainstateManager& chainman,
1866
    std::optional<uint256> from_snapshot_blockhash)
1867
1.36k
    : m_mempool(mempool),
1868
1.36k
      m_blockman(blockman),
1869
1.36k
      m_chainman(chainman),
1870
1.36k
      m_assumeutxo(from_snapshot_blockhash ? Assumeutxo::UNVALIDATED : Assumeutxo::VALIDATED),
1871
1.36k
      m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1872
1873
fs::path Chainstate::StoragePath() const
1874
1.34k
{
1875
1.34k
    fs::path path{m_chainman.m_options.datadir / "chainstate"};
1876
1.34k
    if (m_from_snapshot_blockhash) {
1877
66
        path += node::SNAPSHOT_CHAINSTATE_SUFFIX;
1878
66
    }
1879
1.34k
    return path;
1880
1.34k
}
1881
1882
const CBlockIndex* Chainstate::SnapshotBase() const
1883
595k
{
1884
595k
    if (!m_from_snapshot_blockhash) return nullptr;
1885
17.0k
    if (!m_cached_snapshot_base) m_cached_snapshot_base = Assert(m_chainman.m_blockman.LookupBlockIndex(*m_from_snapshot_blockhash));
1886
17.0k
    return m_cached_snapshot_base;
1887
595k
}
1888
1889
const CBlockIndex* Chainstate::TargetBlock() const
1890
3.08M
{
1891
3.08M
    if (!m_target_blockhash) return nullptr;
1892
1.88M
    if (!m_cached_target_block) m_cached_target_block = Assert(m_chainman.m_blockman.LookupBlockIndex(*m_target_blockhash));
1893
1.88M
    return m_cached_target_block;
1894
3.08M
}
1895
1896
void Chainstate::SetTargetBlock(CBlockIndex* block)
1897
4
{
1898
4
    if (block) {
1899
0
        m_target_blockhash = block->GetBlockHash();
1900
4
    } else {
1901
4
        m_target_blockhash.reset();
1902
4
    }
1903
4
    m_cached_target_block = block;
1904
4
}
1905
1906
void Chainstate::SetTargetBlockHash(uint256 block_hash)
1907
26
{
1908
26
    m_target_blockhash = block_hash;
1909
26
    m_cached_target_block = nullptr;
1910
26
}
1911
1912
void Chainstate::InitCoinsDB(
1913
    size_t cache_size_bytes,
1914
    bool in_memory,
1915
    bool should_wipe)
1916
1.32k
{
1917
1.32k
    m_coins_views = std::make_unique<CoinsViews>(
1918
1.32k
        DBParams{
1919
1.32k
            .path = StoragePath(),
1920
1.32k
            .cache_bytes = cache_size_bytes,
1921
1.32k
            .memory_only = in_memory,
1922
1.32k
            .wipe_data = should_wipe,
1923
1.32k
            .obfuscate = true,
1924
1.32k
            .options = m_chainman.m_options.coins_db},
1925
1.32k
        m_chainman.m_options.coins_view);
1926
1927
1.32k
    m_coinsdb_cache_size_bytes = cache_size_bytes;
1928
1.32k
}
1929
1930
void Chainstate::InitCoinsCache(size_t cache_size_bytes)
1931
1.32k
{
1932
1.32k
    AssertLockHeld(::cs_main);
1933
1.32k
    assert(m_coins_views != nullptr);
1934
1.32k
    m_coinstip_cache_size_bytes = cache_size_bytes;
1935
1.32k
    m_coins_views->InitCache(m_chainman.m_options.prevoutfetch_threads_num);
1936
1.32k
}
1937
1938
// Lock-free: depends on `m_cached_is_ibd`, which is latched by `UpdateIBDStatus()`.
1939
bool ChainstateManager::IsInitialBlockDownload() const noexcept
1940
1.75M
{
1941
1.75M
    return m_cached_is_ibd.load(std::memory_order_relaxed);
1942
1.75M
}
1943
1944
void Chainstate::CheckForkWarningConditions()
1945
107k
{
1946
107k
    AssertLockHeld(cs_main);
1947
1948
107k
    if (this->GetRole().historical) {
1949
807
        return;
1950
807
    }
1951
1952
106k
    if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
1953
140
        LogWarning("Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers.");
1954
140
        m_chainman.GetNotifications().warningSet(
1955
140
            kernel::Warning::LARGE_WORK_INVALID_CHAIN,
1956
140
            _("Warning: Found invalid chain more than 6 blocks longer than our best chain. This could be due to database corruption or consensus incompatibility with peers."));
1957
106k
    } else {
1958
106k
        m_chainman.GetNotifications().warningUnset(kernel::Warning::LARGE_WORK_INVALID_CHAIN);
1959
106k
    }
1960
106k
}
1961
1962
// Called both upon regular invalid block discovery *and* InvalidateBlock
1963
void Chainstate::InvalidChainFound(CBlockIndex* pindexNew)
1964
5.76k
{
1965
5.76k
    AssertLockHeld(cs_main);
1966
5.76k
    if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
1967
1.54k
        m_chainman.m_best_invalid = pindexNew;
1968
1.54k
    }
1969
5.76k
    SetBlockFailureFlags(pindexNew);
1970
5.76k
    if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
1971
2.76k
        m_chainman.RecalculateBestHeader();
1972
2.76k
    }
1973
1974
5.76k
    LogInfo("%s: invalid block=%s height=%d log2_work=%f date=%s", __func__,
1975
5.76k
      pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1976
5.76k
      log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1977
5.76k
    CBlockIndex *tip = m_chain.Tip();
1978
5.76k
    assert (tip);
1979
5.76k
    LogInfo("%s: current best=%s height=%d log2_work=%f date=%s", __func__,
1980
5.76k
      tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1981
5.76k
      FormatISO8601DateTime(tip->GetBlockTime()));
1982
5.76k
    CheckForkWarningConditions();
1983
5.76k
}
1984
1985
// Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1986
// which does its own setBlockIndexCandidates management.
1987
void Chainstate::InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state)
1988
2.80k
{
1989
2.80k
    AssertLockHeld(cs_main);
1990
2.80k
    if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
1991
2.79k
        pindex->nStatus |= BLOCK_FAILED_VALID;
1992
2.79k
        m_blockman.m_dirty_blockindex.insert(pindex);
1993
2.79k
        setBlockIndexCandidates.erase(pindex);
1994
2.79k
        InvalidChainFound(pindex);
1995
2.79k
    }
1996
2.80k
}
1997
1998
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1999
255k
{
2000
    // mark inputs spent
2001
255k
    if (!tx.IsCoinBase()) {
2002
98.2k
        txundo.vprevout.reserve(tx.vin.size());
2003
137k
        for (const CTxIn &txin : tx.vin) {
2004
137k
            txundo.vprevout.emplace_back();
2005
137k
            bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
2006
137k
            assert(is_spent);
2007
137k
        }
2008
98.2k
    }
2009
    // add outputs
2010
255k
    AddCoins(inputs, tx, nHeight);
2011
255k
}
2012
2013
264k
std::optional<std::pair<ScriptError, std::string>> CScriptCheck::operator()() {
2014
264k
    const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
2015
264k
    const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
2016
264k
    ScriptError error{SCRIPT_ERR_UNKNOWN_ERROR};
2017
264k
    if (VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, m_flags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *m_signature_cache, *txdata), &error)) {
2018
217k
        return std::nullopt;
2019
217k
    } else {
2020
46.4k
        auto debug_str = strprintf("input %i of %s (wtxid %s), spending %s:%i", nIn, ptxTo->GetHash().ToString(), ptxTo->GetWitnessHash().ToString(), ptxTo->vin[nIn].prevout.hash.ToString(), ptxTo->vin[nIn].prevout.n);
2021
46.4k
        return std::make_pair(error, std::move(debug_str));
2022
46.4k
    }
2023
264k
}
2024
2025
ValidationCache::ValidationCache(const size_t script_execution_cache_bytes, const size_t signature_cache_bytes)
2026
1.29k
    : m_signature_cache{signature_cache_bytes}
2027
1.29k
{
2028
    // Setup the salted hasher
2029
1.29k
    uint256 nonce = GetRandHash();
2030
    // We want the nonce to be 64 bytes long to force the hasher to process
2031
    // this chunk, which makes later hash computations more efficient. We
2032
    // just write our 32-byte entropy twice to fill the 64 bytes.
2033
1.29k
    m_script_execution_cache_hasher.Write(nonce.begin(), 32);
2034
1.29k
    m_script_execution_cache_hasher.Write(nonce.begin(), 32);
2035
2036
1.29k
    const auto [num_elems, approx_size_bytes] = m_script_execution_cache.setup_bytes(script_execution_cache_bytes);
2037
1.29k
    LogInfo("Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements",
2038
1.29k
              approx_size_bytes >> 20, script_execution_cache_bytes >> 20, num_elems);
2039
1.29k
}
2040
2041
/**
2042
 * Check whether all of this transaction's input scripts succeed.
2043
 *
2044
 * This involves ECDSA signature checks so can be computationally intensive. This function should
2045
 * only be called after the cheap sanity checks in CheckTxInputs passed.
2046
 *
2047
 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
2048
 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
2049
 * not pushed onto pvChecks/run.
2050
 *
2051
 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
2052
 * which are matched. This is useful for checking blocks where we will likely never need the cache
2053
 * entry again.
2054
 *
2055
 * Note that we may set state.reason to NOT_STANDARD for extra soft-fork flags in flags, block-checking
2056
 * callers should probably reset it to CONSENSUS in such cases.
2057
 *
2058
 * Non-static (and redeclared) in src/test/txvalidationcache_tests.cpp
2059
 */
2060
bool CheckInputScripts(const CTransaction& tx, TxValidationState& state,
2061
                       const CCoinsViewCache& inputs, script_verify_flags flags, bool cacheSigStore,
2062
                       bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
2063
                       ValidationCache& validation_cache,
2064
                       std::vector<CScriptCheck>* pvChecks)
2065
333k
{
2066
333k
    if (tx.IsCoinBase()) return true;
2067
2068
333k
    if (pvChecks) {
2069
154k
        pvChecks->reserve(tx.vin.size());
2070
154k
    }
2071
2072
    // First check if script executions have been cached with the same
2073
    // flags. Note that this assumes that the inputs provided are
2074
    // correct (ie that the transaction hash which is in tx's prevouts
2075
    // properly commits to the scriptPubKey in the inputs view of that
2076
    // transaction).
2077
333k
    uint256 hashCacheEntry;
2078
333k
    CSHA256 hasher = validation_cache.ScriptExecutionCacheHasher();
2079
333k
    hasher.Write(UCharCast(tx.GetWitnessHash().begin()), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
2080
333k
    AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
2081
333k
    if (validation_cache.m_script_execution_cache.contains(hashCacheEntry, !cacheFullScriptStore)) {
2082
89.0k
        return true;
2083
89.0k
    }
2084
2085
244k
    if (!txdata.m_spent_outputs_ready) {
2086
75.6k
        std::vector<CTxOut> spent_outputs;
2087
75.6k
        spent_outputs.reserve(tx.vin.size());
2088
2089
113k
        for (const auto& txin : tx.vin) {
2090
113k
            const COutPoint& prevout = txin.prevout;
2091
113k
            const Coin& coin = inputs.AccessCoin(prevout);
2092
113k
            assert(!coin.IsSpent());
2093
113k
            spent_outputs.emplace_back(coin.out);
2094
113k
        }
2095
75.6k
        txdata.Init(tx, std::move(spent_outputs));
2096
75.6k
    }
2097
244k
    assert(txdata.m_spent_outputs.size() == tx.vin.size());
2098
2099
504k
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
2100
2101
        // We very carefully only pass in things to CScriptCheck which
2102
        // are clearly committed to by tx' witness hash. This provides
2103
        // a sanity check that our caching is not introducing consensus
2104
        // failures through additional data in, eg, the coins being
2105
        // spent being checked as a part of CScriptCheck.
2106
2107
        // Verify signature
2108
303k
        CScriptCheck check(txdata.m_spent_outputs[i], tx, validation_cache.m_signature_cache, i, flags, cacheSigStore, &txdata);
2109
303k
        if (pvChecks) {
2110
88.6k
            pvChecks->emplace_back(std::move(check));
2111
214k
        } else if (auto result = check(); result.has_value()) {
2112
            // Tx failures never trigger disconnections/bans.
2113
            // This is so that network splits aren't triggered
2114
            // either due to non-consensus relay policies (such as
2115
            // non-standard DER encodings or non-null dummy
2116
            // arguments) or due to new consensus rules introduced in
2117
            // soft forks.
2118
43.6k
            if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2119
43.6k
                return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("mempool-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
2120
43.6k
            } else {
2121
35
                return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(result->first)), result->second);
2122
35
            }
2123
43.6k
        }
2124
303k
    }
2125
2126
201k
    if (cacheFullScriptStore && !pvChecks) {
2127
        // We executed all of the provided scripts, and were told to
2128
        // cache the result. Do so now.
2129
82.8k
        validation_cache.m_script_execution_cache.insert(hashCacheEntry);
2130
82.8k
    }
2131
2132
201k
    return true;
2133
244k
}
2134
2135
bool FatalError(Notifications& notifications, BlockValidationState& state, const bilingual_str& message)
2136
1
{
2137
1
    notifications.fatalError(message);
2138
1
    return state.Error(message.original);
2139
1
}
2140
2141
/**
2142
 * Restore the UTXO in a Coin at a given COutPoint
2143
 * @param undo The Coin to be restored.
2144
 * @param view The coins view to which to apply the changes.
2145
 * @param out The out point that corresponds to the tx input.
2146
 * @return A DisconnectResult as an int
2147
 */
2148
int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
2149
22.4k
{
2150
22.4k
    bool fClean = true;
2151
2152
22.4k
    if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
2153
2154
22.4k
    if (undo.nHeight == 0) {
2155
        // Missing undo metadata (height and coinbase). Older versions included this
2156
        // information only in undo records for the last spend of a transactions'
2157
        // outputs. This implies that it must be present for some other output of the same tx.
2158
0
        const Coin& alternate = AccessByTxid(view, out.hash);
2159
0
        if (!alternate.IsSpent()) {
2160
0
            undo.nHeight = alternate.nHeight;
2161
0
            undo.fCoinBase = alternate.fCoinBase;
2162
0
        } else {
2163
0
            return DISCONNECT_FAILED; // adding output for transaction without known metadata
2164
0
        }
2165
0
    }
2166
    // If the coin already exists as an unspent coin in the cache, then the
2167
    // possible_overwrite parameter to AddCoin must be set to true. We have
2168
    // already checked whether an unspent coin exists above using HaveCoin, so
2169
    // we don't need to guess. When fClean is false, an unspent coin already
2170
    // existed and it is an overwrite.
2171
22.4k
    view.AddCoin(out, std::move(undo), !fClean);
2172
2173
22.4k
    return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
2174
22.4k
}
2175
2176
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
2177
 *  When FAILED is returned, view is left in an indeterminate state. */
2178
DisconnectResult Chainstate::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
2179
15.3k
{
2180
15.3k
    AssertLockHeld(::cs_main);
2181
15.3k
    bool fClean = true;
2182
2183
15.3k
    CBlockUndo blockUndo;
2184
15.3k
    if (!m_blockman.ReadBlockUndo(blockUndo, *pindex)) {
2185
1
        LogError("DisconnectBlock(): failure reading undo data\n");
2186
1
        return DISCONNECT_FAILED;
2187
1
    }
2188
2189
15.3k
    if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
2190
0
        LogError("DisconnectBlock(): block and undo data inconsistent\n");
2191
0
        return DISCONNECT_FAILED;
2192
0
    }
2193
2194
    // Ignore blocks that contain transactions which are 'overwritten' by later transactions,
2195
    // unless those are already completely spent.
2196
    // See https://github.com/bitcoin/bitcoin/issues/22596 for additional information.
2197
    // Note: the blocks specified here are different than the ones used in ConnectBlock because DisconnectBlock
2198
    // unwinds the blocks in reverse. As a result, the inconsistency is not discovered until the earlier
2199
    // blocks with the duplicate coinbase transactions are disconnected.
2200
15.3k
    bool fEnforceBIP30 = !((pindex->nHeight==91722 && pindex->GetBlockHash() == uint256{"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
2201
15.3k
                           (pindex->nHeight==91812 && pindex->GetBlockHash() == uint256{"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"}));
2202
2203
    // undo transactions in reverse order
2204
43.6k
    for (int i = block.vtx.size() - 1; i >= 0; i--) {
2205
28.3k
        const CTransaction &tx = *(block.vtx[i]);
2206
28.3k
        Txid hash = tx.GetHash();
2207
28.3k
        bool is_coinbase = tx.IsCoinBase();
2208
28.3k
        bool is_bip30_exception = (is_coinbase && !fEnforceBIP30);
2209
2210
        // Check that all outputs are available and match the outputs in the block itself
2211
        // exactly.
2212
77.7k
        for (size_t o = 0; o < tx.vout.size(); o++) {
2213
49.4k
            if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
2214
35.0k
                COutPoint out(hash, o);
2215
35.0k
                Coin coin;
2216
35.0k
                bool is_spent = view.SpendCoin(out, &coin);
2217
35.0k
                if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.IsCoinBase()) {
2218
0
                    if (!is_bip30_exception) {
2219
0
                        fClean = false; // transaction output mismatch
2220
0
                    }
2221
0
                }
2222
35.0k
            }
2223
49.4k
        }
2224
2225
        // restore inputs
2226
28.3k
        if (i > 0) { // not coinbases
2227
13.0k
            CTxUndo &txundo = blockUndo.vtxundo[i-1];
2228
13.0k
            if (txundo.vprevout.size() != tx.vin.size()) {
2229
0
                LogError("DisconnectBlock(): transaction and undo data inconsistent\n");
2230
0
                return DISCONNECT_FAILED;
2231
0
            }
2232
33.7k
            for (unsigned int j = tx.vin.size(); j > 0;) {
2233
20.7k
                --j;
2234
20.7k
                const COutPoint& out = tx.vin[j].prevout;
2235
20.7k
                int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
2236
20.7k
                if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
2237
20.7k
                fClean = fClean && res != DISCONNECT_UNCLEAN;
2238
20.7k
            }
2239
            // At this point, all of txundo.vprevout should have been moved out.
2240
13.0k
        }
2241
28.3k
    }
2242
2243
    // move best block pointer to prevout block
2244
15.3k
    view.SetBestBlock(pindex->pprev->GetBlockHash());
2245
2246
15.3k
    return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
2247
15.3k
}
2248
2249
script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman)
2250
196k
{
2251
196k
    const Consensus::Params& consensusparams = chainman.GetConsensus();
2252
2253
    // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
2254
    // retroactively applied to testnet)
2255
    // However, only one historical block violated the P2SH rules (on both
2256
    // mainnet and testnet).
2257
    // Similarly, only one historical block violated the TAPROOT rules on
2258
    // mainnet.
2259
    // For simplicity, always leave P2SH+WITNESS+TAPROOT on except for the two
2260
    // violating blocks.
2261
196k
    script_verify_flags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};
2262
196k
    const auto it{consensusparams.script_flag_exceptions.find(*Assert(block_index.phashBlock))};
2263
196k
    if (it != consensusparams.script_flag_exceptions.end()) {
2264
0
        flags = it->second;
2265
0
    }
2266
2267
    // Enforce the DERSIG (BIP66) rule
2268
196k
    if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_DERSIG)) {
2269
193k
        flags |= SCRIPT_VERIFY_DERSIG;
2270
193k
    }
2271
2272
    // Enforce CHECKLOCKTIMEVERIFY (BIP65)
2273
196k
    if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CLTV)) {
2274
193k
        flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2275
193k
    }
2276
2277
    // Enforce CHECKSEQUENCEVERIFY (BIP112)
2278
196k
    if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CSV)) {
2279
192k
        flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
2280
192k
    }
2281
2282
    // Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
2283
196k
    if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_SEGWIT)) {
2284
191k
        flags |= SCRIPT_VERIFY_NULLDUMMY;
2285
191k
    }
2286
2287
196k
    return flags;
2288
196k
}
2289
2290
2291
/** Apply the effects of this block (with given index) on the UTXO set represented by coins.
2292
 *  Validity checks that depend on the UTXO set are also done; ConnectBlock()
2293
 *  can fail if those validity checks fail (among other reasons). */
2294
bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
2295
                               CCoinsViewCache& view, bool fJustCheck)
2296
153k
{
2297
153k
    AssertLockHeld(cs_main);
2298
153k
    assert(pindex);
2299
2300
153k
    uint256 block_hash{block.GetHash()};
2301
153k
    assert(*pindex->phashBlock == block_hash);
2302
2303
153k
    const auto time_start{SteadyClock::now()};
2304
153k
    const CChainParams& params{m_chainman.GetParams()};
2305
2306
    // Check it again in case a previous version let a bad block in
2307
    // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
2308
    // ContextualCheckBlockHeader() here. This means that if we add a new
2309
    // consensus rule that is enforced in one of those two functions, then we
2310
    // may have let in a block that violates the rule prior to updating the
2311
    // software, and we would NOT be enforcing the rule here. Fully solving
2312
    // upgrade from one software version to the next after a consensus rule
2313
    // change is potentially tricky and issue-specific (see NeedsRedownload()
2314
    // for one approach that was used for BIP 141 deployment).
2315
    // Also, currently the rule against blocks more than 2 hours in the future
2316
    // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
2317
    // re-enforce that rule here (at least until we make it impossible for
2318
    // the clock to go backward).
2319
153k
    if (!CheckBlock(block, state, params.GetConsensus(), !fJustCheck, !fJustCheck)) {
2320
0
        if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
2321
            // We don't write down blocks to disk if they may have been
2322
            // corrupted, so this should be impossible unless we're having hardware
2323
            // problems.
2324
0
            return FatalError(m_chainman.GetNotifications(), state, _("Corrupt block found indicating potential hardware failure."));
2325
0
        }
2326
0
        LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());
2327
0
        return false;
2328
0
    }
2329
2330
    // verify that the view's current state corresponds to the previous block
2331
153k
    uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
2332
153k
    assert(hashPrevBlock == view.GetBestBlock());
2333
2334
153k
    m_chainman.num_blocks_total++;
2335
2336
    // Special case for the genesis block, skipping connection of its transactions
2337
    // (its coinbase is unspendable)
2338
153k
    if (block_hash == params.GetConsensus().hashGenesisBlock) {
2339
497
        if (!fJustCheck)
2340
497
            view.SetBestBlock(pindex->GetBlockHash());
2341
497
        return true;
2342
497
    }
2343
2344
152k
    const char* script_check_reason;
2345
152k
    if (m_chainman.AssumedValidBlock().IsNull()) {
2346
148k
        script_check_reason = "assumevalid=0 (always verify)";
2347
148k
    } else {
2348
4.58k
        constexpr int64_t TWO_WEEKS_IN_SECONDS{60 * 60 * 24 * 7 * 2};
2349
        // We've been configured with the hash of a block which has been externally verified to have a valid history.
2350
        // A suitable default value is included with the software and updated from time to time.  Because validity
2351
        //  relative to a piece of software is an objective fact these defaults can be easily reviewed.
2352
        // This setting doesn't force the selection of any particular chain but makes validating some faster by
2353
        //  effectively caching the result of part of the verification.
2354
4.58k
        BlockMap::const_iterator it{m_blockman.m_block_index.find(m_chainman.AssumedValidBlock())};
2355
4.58k
        if (it == m_blockman.m_block_index.end()) {
2356
2.27k
            script_check_reason = "assumevalid hash not in headers";
2357
2.30k
        } else if (it->second.GetAncestor(pindex->nHeight) != pindex) {
2358
2.10k
            script_check_reason = (pindex->nHeight > it->second.nHeight) ? "block height above assumevalid height" : "block not in assumevalid chain";
2359
2.10k
        } else if (m_chainman.m_best_header->GetAncestor(pindex->nHeight) != pindex) {
2360
1
            script_check_reason = "block not in best header chain";
2361
205
        } else if (m_chainman.m_best_header->nChainWork < m_chainman.MinimumChainWork()) {
2362
1
            script_check_reason = "best header chainwork below minimumchainwork";
2363
204
        } else if (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, params.GetConsensus()) <= TWO_WEEKS_IN_SECONDS) {
2364
102
            script_check_reason = "block too recent relative to best header";
2365
102
        } else {
2366
            // This block is a member of the assumed verified chain and an ancestor of the best header.
2367
            // Script verification is skipped when connecting blocks under the
2368
            //  assumevalid block. Assuming the assumevalid block is valid this
2369
            //  is safe because block merkle hashes are still computed and checked,
2370
            // Of course, if an assumed valid block is invalid due to false scriptSigs
2371
            //  this optimization would allow an invalid chain to be accepted.
2372
            // The equivalent time check discourages hash power from extorting the network via DOS attack
2373
            //  into accepting an invalid block through telling users they must manually set assumevalid.
2374
            //  Requiring a software change or burying the invalid block, regardless of the setting, makes
2375
            //  it hard to hide the implication of the demand. This also avoids having release candidates
2376
            //  that are hardly doing any signature verification at all in testing without having to
2377
            //  artificially set the default assumed verified block further back.
2378
            // The test against the minimum chain work prevents the skipping when denied access to any chain at
2379
            //  least as good as the expected chain.
2380
102
            script_check_reason = nullptr;
2381
102
        }
2382
4.58k
    }
2383
2384
152k
    const auto time_1{SteadyClock::now()};
2385
152k
    m_chainman.time_check += time_1 - time_start;
2386
152k
    LogDebug(BCLog::BENCH, "    - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2387
152k
             Ticks<MillisecondsDouble>(time_1 - time_start),
2388
152k
             Ticks<SecondsDouble>(m_chainman.time_check),
2389
152k
             Ticks<MillisecondsDouble>(m_chainman.time_check) / m_chainman.num_blocks_total);
2390
2391
    // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2392
    // unless those are already completely spent.
2393
    // If such overwrites are allowed, coinbases and transactions depending upon those
2394
    // can be duplicated to remove the ability to spend the first instance -- even after
2395
    // being sent to another address.
2396
    // See BIP30, CVE-2012-1909, and https://r6.ca/blog/20120206T005236Z.html for more information.
2397
    // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2398
    // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2399
    // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2400
    // initial block download.
2401
152k
    bool fEnforceBIP30 = !IsBIP30Repeat(*pindex);
2402
2403
    // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2404
    // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs.  But by the
2405
    // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2406
    // before the first had been spent.  Since those coinbases are sufficiently buried it's no longer possible to create further
2407
    // duplicate transactions descending from the known pairs either.
2408
    // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
2409
2410
    // BIP34 requires that a block at height X (block X) has its coinbase
2411
    // scriptSig start with a CScriptNum of X (indicated height X).  The above
2412
    // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2413
    // case that there is a block X before the BIP34 height of 227,931 which has
2414
    // an indicated height Y where Y is greater than X.  The coinbase for block
2415
    // X would also be a valid coinbase for block Y, which could be a BIP30
2416
    // violation.  An exhaustive search of all mainnet coinbases before the
2417
    // BIP34 height which have an indicated height greater than the block height
2418
    // reveals many occurrences. The 3 lowest indicated heights found are
2419
    // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2420
    // heights would be the first opportunity for BIP30 to be violated.
2421
2422
    // The search reveals a great many blocks which have an indicated height
2423
    // greater than 1,983,702, so we simply remove the optimization to skip
2424
    // BIP30 checking for blocks at height 1,983,702 or higher.  Before we reach
2425
    // that block in another 25 years or so, we should take advantage of a
2426
    // future consensus change to do a new and improved version of BIP34 that
2427
    // will actually prevent ever creating any duplicate coinbases in the
2428
    // future.
2429
152k
    static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2430
2431
    // There is no potential to create a duplicate coinbase at block 209,921
2432
    // because this is still before the BIP34 height and so explicit BIP30
2433
    // checking is still active.
2434
2435
    // The final case is block 176,684 which has an indicated height of
2436
    // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2437
    // before block 490,897 so there was not much opportunity to address this
2438
    // case other than to carefully analyze it and determine it would not be a
2439
    // problem. Block 490,897 was, in fact, mined with a different coinbase than
2440
    // block 176,684, but it is important to note that even if it hadn't been or
2441
    // is remined on an alternate fork with a duplicate coinbase, we would still
2442
    // not run into a BIP30 violation.  This is because the coinbase for 176,684
2443
    // is spent in block 185,956 in transaction
2444
    // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781.  This
2445
    // spending transaction can't be duplicated because it also spends coinbase
2446
    // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29.  This
2447
    // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2448
    // duplicatable until that height, and it's currently impossible to create a
2449
    // chain that long. Nevertheless we may wish to consider a future soft fork
2450
    // which retroactively prevents block 490,897 from creating a duplicate
2451
    // coinbase. The two historical BIP30 violations often provide a confusing
2452
    // edge case when manipulating the UTXO and it would be simpler not to have
2453
    // another edge case to deal with.
2454
2455
    // testnet3 has no blocks before the BIP34 height with indicated heights
2456
    // post BIP34 before approximately height 486,000,000. After block
2457
    // 1,983,702 testnet3 starts doing unnecessary BIP30 checking again.
2458
152k
    assert(pindex->pprev);
2459
152k
    CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(params.GetConsensus().BIP34Height);
2460
    //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2461
152k
    fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == params.GetConsensus().BIP34Hash));
2462
2463
    // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
2464
    // consensus change that ensures coinbases at those heights cannot
2465
    // duplicate earlier coinbases.
2466
152k
    if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2467
217k
        for (const auto& tx : block.vtx) {
2468
754k
            for (size_t o = 0; o < tx->vout.size(); o++) {
2469
537k
                if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2470
1
                    state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30",
2471
1
                                  "tried to overwrite transaction");
2472
1
                }
2473
537k
            }
2474
217k
        }
2475
152k
    }
2476
2477
    // Enforce BIP68 (sequence locks)
2478
152k
    int nLockTimeFlags = 0;
2479
152k
    if (DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_CSV)) {
2480
149k
        nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2481
149k
    }
2482
2483
    // Get the script flags for this block
2484
152k
    script_verify_flags flags{GetBlockScriptFlags(*pindex, m_chainman)};
2485
2486
152k
    const auto time_2{SteadyClock::now()};
2487
152k
    m_chainman.time_forks += time_2 - time_1;
2488
152k
    LogDebug(BCLog::BENCH, "    - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2489
152k
             Ticks<MillisecondsDouble>(time_2 - time_1),
2490
152k
             Ticks<SecondsDouble>(m_chainman.time_forks),
2491
152k
             Ticks<MillisecondsDouble>(m_chainman.time_forks) / m_chainman.num_blocks_total);
2492
2493
152k
    const bool fScriptChecks{!!script_check_reason};
2494
152k
    const kernel::ChainstateRole role{GetRole()};
2495
152k
    if (script_check_reason != m_last_script_check_reason_logged && role.validated && !role.historical) {
2496
693
        if (fScriptChecks) {
2497
692
            LogInfo("Enabling script verification at block #%d (%s): %s.",
2498
692
                    pindex->nHeight, block_hash.ToString(), script_check_reason);
2499
692
        } else {
2500
1
            LogInfo("Disabling script verification at block #%d (%s).",
2501
1
                    pindex->nHeight, block_hash.ToString());
2502
1
        }
2503
693
        m_last_script_check_reason_logged = script_check_reason;
2504
693
    }
2505
2506
152k
    CBlockUndo blockundo;
2507
2508
    // Precomputed transaction data pointers must not be invalidated
2509
    // until after `control` has run the script checks (potentially
2510
    // in multiple threads). Preallocate the vector size so a new allocation
2511
    // doesn't invalidate pointers into the vector, and keep txsdata in scope
2512
    // for as long as `control`.
2513
152k
    std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
2514
152k
    std::optional<CCheckQueueControl<CScriptCheck>> control;
2515
152k
    if (auto& queue = m_chainman.GetCheckQueue(); queue.HasThreads() && fScriptChecks) control.emplace(queue);
2516
2517
152k
    std::vector<int> prevheights;
2518
152k
    CAmount nFees = 0;
2519
152k
    int nInputs = 0;
2520
152k
    int64_t nSigOpsCost = 0;
2521
152k
    blockundo.vtxundo.reserve(block.vtx.size() - 1);
2522
370k
    for (unsigned int i = 0; i < block.vtx.size(); i++)
2523
217k
    {
2524
217k
        if (!state.IsValid()) break;
2525
217k
        const CTransaction &tx = *(block.vtx[i]);
2526
2527
217k
        nInputs += tx.vin.size();
2528
2529
217k
        if (!tx.IsCoinBase())
2530
65.1k
        {
2531
65.1k
            CAmount txfee = 0;
2532
65.1k
            TxValidationState tx_state;
2533
65.1k
            if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
2534
                // Any transaction validation failure in ConnectBlock is a block consensus failure
2535
332
                state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
2536
332
                              tx_state.GetRejectReason(),
2537
332
                              tx_state.GetDebugMessage() + " in transaction " + tx.GetHash().ToString());
2538
332
                break;
2539
332
            }
2540
64.7k
            nFees += txfee;
2541
64.7k
            if (!MoneyRange(nFees)) {
2542
0
                state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange",
2543
0
                              "accumulated fee in the block out of range");
2544
0
                break;
2545
0
            }
2546
2547
            // Check that transaction is BIP68 final
2548
            // BIP68 lock checks (as opposed to nLockTime checks) must
2549
            // be in ConnectBlock because they require the UTXO set
2550
64.7k
            prevheights.resize(tx.vin.size());
2551
169k
            for (size_t j = 0; j < tx.vin.size(); j++) {
2552
104k
                prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2553
104k
            }
2554
2555
64.7k
            if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2556
12
                state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal",
2557
12
                              "contains a non-BIP68-final transaction " + tx.GetHash().ToString());
2558
12
                break;
2559
12
            }
2560
64.7k
        }
2561
2562
        // GetTransactionSigOpCost counts 3 types of sigops:
2563
        // * legacy (always)
2564
        // * p2sh (when P2SH enabled in flags and excludes coinbase)
2565
        // * witness (when witness enabled in flags and excludes coinbase)
2566
217k
        nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
2567
217k
        if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
2568
7
            state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "too many sigops");
2569
7
            break;
2570
7
        }
2571
2572
217k
        if (!tx.IsCoinBase() && fScriptChecks)
2573
64.7k
        {
2574
64.7k
            bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2575
64.7k
            bool tx_ok;
2576
64.7k
            TxValidationState tx_state;
2577
            // If CheckInputScripts is called with a pointer to a checks vector, the resulting checks are appended to it. In that case
2578
            // they need to be added to control which runs them asynchronously. Otherwise, CheckInputScripts runs the checks before returning.
2579
64.7k
            if (control) {
2580
64.1k
                std::vector<CScriptCheck> vChecks;
2581
64.1k
                tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache, &vChecks);
2582
64.1k
                if (tx_ok) control->Add(std::move(vChecks));
2583
64.1k
            } else {
2584
644
                tx_ok = CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], m_chainman.m_validation_cache);
2585
644
            }
2586
64.7k
            if (!tx_ok) {
2587
                // Any transaction validation failure in ConnectBlock is a block consensus failure
2588
21
                state.Invalid(BlockValidationResult::BLOCK_CONSENSUS,
2589
21
                              tx_state.GetRejectReason(), tx_state.GetDebugMessage());
2590
21
                break;
2591
21
            }
2592
64.7k
        }
2593
2594
217k
        CTxUndo undoDummy;
2595
217k
        if (i > 0) {
2596
64.7k
            blockundo.vtxundo.emplace_back();
2597
64.7k
        }
2598
217k
        UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2599
217k
    }
2600
152k
    const auto time_3{SteadyClock::now()};
2601
152k
    m_chainman.time_connect += time_3 - time_2;
2602
152k
    LogDebug(BCLog::BENCH, "      - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(),
2603
152k
             Ticks<MillisecondsDouble>(time_3 - time_2), Ticks<MillisecondsDouble>(time_3 - time_2) / block.vtx.size(),
2604
152k
             nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
2605
152k
             Ticks<SecondsDouble>(m_chainman.time_connect),
2606
152k
             Ticks<MillisecondsDouble>(m_chainman.time_connect) / m_chainman.num_blocks_total);
2607
2608
152k
    CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, params.GetConsensus());
2609
152k
    if (block.vtx[0]->GetValueOut() > blockReward && state.IsValid()) {
2610
9
        state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount",
2611
9
                      strprintf("coinbase pays too much (actual=%d vs limit=%d)", block.vtx[0]->GetValueOut(), blockReward));
2612
9
    }
2613
152k
    if (control) {
2614
152k
        auto parallel_result = control->Complete();
2615
152k
        if (parallel_result.has_value() && state.IsValid()) {
2616
2.71k
            state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, strprintf("block-script-verify-flag-failed (%s)", ScriptErrorString(parallel_result->first)), parallel_result->second);
2617
2.71k
        }
2618
152k
    }
2619
152k
    if (!state.IsValid()) {
2620
3.09k
        LogInfo("Block validation error: %s", state.ToString());
2621
3.09k
        return false;
2622
3.09k
    }
2623
149k
    const auto time_4{SteadyClock::now()};
2624
149k
    m_chainman.time_verify += time_4 - time_2;
2625
149k
    LogDebug(BCLog::BENCH, "    - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
2626
149k
             Ticks<MillisecondsDouble>(time_4 - time_2),
2627
149k
             nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
2628
149k
             Ticks<SecondsDouble>(m_chainman.time_verify),
2629
149k
             Ticks<MillisecondsDouble>(m_chainman.time_verify) / m_chainman.num_blocks_total);
2630
2631
149k
    if (fJustCheck) {
2632
43.6k
        return true;
2633
43.6k
    }
2634
2635
106k
    if (!m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2636
0
        return false;
2637
0
    }
2638
2639
106k
    const auto time_5{SteadyClock::now()};
2640
106k
    m_chainman.time_undo += time_5 - time_4;
2641
106k
    LogDebug(BCLog::BENCH, "    - Write undo data: %.2fms [%.2fs (%.2fms/blk)]\n",
2642
106k
             Ticks<MillisecondsDouble>(time_5 - time_4),
2643
106k
             Ticks<SecondsDouble>(m_chainman.time_undo),
2644
106k
             Ticks<MillisecondsDouble>(m_chainman.time_undo) / m_chainman.num_blocks_total);
2645
2646
106k
    if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
2647
101k
        pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2648
101k
        m_blockman.m_dirty_blockindex.insert(pindex);
2649
101k
    }
2650
2651
    // add this block to the view's block chain
2652
106k
    view.SetBestBlock(pindex->GetBlockHash());
2653
2654
106k
    const auto time_6{SteadyClock::now()};
2655
106k
    m_chainman.time_index += time_6 - time_5;
2656
106k
    LogDebug(BCLog::BENCH, "    - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n",
2657
106k
             Ticks<MillisecondsDouble>(time_6 - time_5),
2658
106k
             Ticks<SecondsDouble>(m_chainman.time_index),
2659
106k
             Ticks<MillisecondsDouble>(m_chainman.time_index) / m_chainman.num_blocks_total);
2660
2661
106k
    TRACEPOINT(validation, block_connected,
2662
106k
        block_hash.data(),
2663
106k
        pindex->nHeight,
2664
106k
        block.vtx.size(),
2665
106k
        nInputs,
2666
106k
        nSigOpsCost,
2667
106k
        Ticks<std::chrono::nanoseconds>(time_5 - time_start)
2668
106k
    );
2669
2670
106k
    return true;
2671
106k
}
2672
2673
CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState()
2674
378k
{
2675
378k
    AssertLockHeld(::cs_main);
2676
378k
    return this->GetCoinsCacheSizeState(
2677
378k
        m_coinstip_cache_size_bytes,
2678
378k
        m_mempool ? m_mempool->m_opts.max_size_bytes : 0);
2679
378k
}
2680
2681
CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState(
2682
    size_t max_coins_cache_size_bytes,
2683
    size_t max_mempool_size_bytes)
2684
435k
{
2685
435k
    AssertLockHeld(::cs_main);
2686
435k
    const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2687
435k
    int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2688
435k
    int64_t nTotalSpace =
2689
435k
        max_coins_cache_size_bytes + std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2690
2691
435k
    if (cacheSize > nTotalSpace) {
2692
4
        LogInfo("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
2693
4
        return CoinsCacheSizeState::CRITICAL;
2694
435k
    } else if (cacheSize > LargeCoinsCacheThreshold(nTotalSpace)) {
2695
9.82k
        return CoinsCacheSizeState::LARGE;
2696
9.82k
    }
2697
425k
    return CoinsCacheSizeState::OK;
2698
435k
}
2699
2700
bool Chainstate::FlushStateToDisk(
2701
    BlockValidationState &state,
2702
    FlushStateMode mode,
2703
    int nManualPruneHeight)
2704
377k
{
2705
377k
    LOCK(cs_main);
2706
377k
    assert(this->CanFlushToDisk());
2707
377k
    std::set<int> setFilesToPrune;
2708
377k
    bool full_flush_completed = false;
2709
2710
377k
    [[maybe_unused]] const size_t coins_count{CoinsTip().GetCacheSize()};
2711
377k
    [[maybe_unused]] const size_t coins_mem_usage{CoinsTip().DynamicMemoryUsage()};
2712
2713
377k
    try {
2714
377k
    {
2715
377k
        bool fFlushForPrune = false;
2716
2717
377k
        CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2718
377k
        if (m_blockman.IsPruneMode() && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && m_chainman.m_blockman.m_blockfiles_indexed) {
2719
            // make sure we don't prune above any of the prune locks bestblocks
2720
            // pruning is height-based
2721
157
            int last_prune{m_chain.Height()}; // last height we can prune
2722
157
            std::optional<std::string> limiting_lock; // prune lock that actually was the limiting factor, only used for logging
2723
2724
157
            for (const auto& prune_lock : m_blockman.m_prune_locks) {
2725
16
                if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
2726
                // Remove the buffer and one additional block here to get actual height that is outside of the buffer
2727
16
                const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
2728
16
                last_prune = std::max(1, std::min(last_prune, lock_height));
2729
16
                if (last_prune == lock_height) {
2730
13
                    limiting_lock = prune_lock.first;
2731
13
                }
2732
16
            }
2733
2734
157
            if (limiting_lock) {
2735
7
                LogDebug(BCLog::PRUNE, "%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
2736
7
            }
2737
2738
157
            if (nManualPruneHeight > 0) {
2739
11
                LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
2740
2741
11
                m_blockman.FindFilesToPruneManual(
2742
11
                    setFilesToPrune,
2743
11
                    std::min(last_prune, nManualPruneHeight),
2744
11
                    *this);
2745
146
            } else {
2746
146
                LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
2747
2748
146
                m_blockman.FindFilesToPrune(setFilesToPrune, last_prune, *this, m_chainman);
2749
146
                m_blockman.m_check_for_pruning = false;
2750
146
            }
2751
157
            if (!setFilesToPrune.empty()) {
2752
10
                fFlushForPrune = true;
2753
10
                if (!m_blockman.m_have_pruned) {
2754
8
                    m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
2755
8
                    m_blockman.m_have_pruned = true;
2756
8
                }
2757
10
            }
2758
157
        }
2759
377k
        const auto nNow{NodeClock::now()};
2760
        // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
2761
377k
        bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2762
        // The cache is over the limit, we have to write now.
2763
377k
        bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2764
        // It's been a while since we wrote the block index and chain state to disk. Do this frequently, so we don't need to redownload or reindex after a crash.
2765
377k
        bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow >= m_next_write;
2766
377k
        const auto empty_cache{(mode == FlushStateMode::FORCE_FLUSH) || fCacheLarge || fCacheCritical};
2767
        // Combine all conditions that result in a write to disk.
2768
377k
        bool should_write = (mode == FlushStateMode::FORCE_SYNC) || empty_cache || fPeriodicWrite || fFlushForPrune;
2769
        // Write blocks, block index and best chain related state to disk.
2770
377k
        if (should_write) {
2771
3.58k
            LogDebug(BCLog::COINDB, "Writing chainstate to disk: flush mode=%s, prune=%d, large=%d, critical=%d, periodic=%d",
2772
3.58k
                     FlushStateModeNames[size_t(mode)], fFlushForPrune, fCacheLarge, fCacheCritical, fPeriodicWrite);
2773
2774
            // Ensure we can write block index
2775
3.58k
            if (!CheckDiskSpace(m_blockman.m_opts.blocks_dir)) {
2776
0
                return FatalError(m_chainman.GetNotifications(), state, _("Disk space is too low!"));
2777
0
            }
2778
3.58k
            {
2779
3.58k
                LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
2780
2781
                // First make sure all block and undo data is flushed to disk.
2782
                // TODO: Handle return error, or add detailed comment why it is
2783
                // safe to not return an error upon failure.
2784
3.58k
                if (!m_blockman.FlushChainstateBlockFile(m_chain.Height())) {
2785
0
                    LogWarning("%s: Failed to flush block file.\n", __func__);
2786
0
                }
2787
3.58k
            }
2788
2789
            // Then update all block file information (which may refer to block and undo files).
2790
3.58k
            {
2791
3.58k
                LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
2792
2793
3.58k
                m_blockman.WriteBlockIndexDB();
2794
3.58k
            }
2795
            // Finally remove any pruned files
2796
3.58k
            if (fFlushForPrune) {
2797
10
                LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
2798
2799
10
                m_blockman.UnlinkPrunedFiles(setFilesToPrune);
2800
10
            }
2801
2802
3.58k
            if (!CoinsTip().GetBestBlock().IsNull()) {
2803
                // Typical Coin structures on disk are around 48 bytes in size.
2804
                // Pushing a new one to the database can cause it to be written
2805
                // twice (once in the log, and once in the tables). This is already
2806
                // an overestimation, as most will delete an existing entry or
2807
                // overwrite one. Still, use a conservative safety factor of 2.
2808
3.57k
                if (!CheckDiskSpace(m_chainman.m_options.datadir, 48 * 2 * 2 * CoinsTip().GetDirtyCount())) {
2809
0
                    return FatalError(m_chainman.GetNotifications(), state, _("Disk space is too low!"));
2810
0
                }
2811
                // Flush the chainstate (which may refer to block index entries).
2812
3.57k
                empty_cache ? CoinsTip().Flush() : CoinsTip().Sync();
2813
3.57k
                m_last_flushed_block = m_blockman.LookupBlockIndex(CoinsTip().GetBestBlock());
2814
3.57k
                full_flush_completed = true;
2815
3.57k
                TRACEPOINT(utxocache, flush,
2816
3.57k
                    int64_t{Ticks<std::chrono::microseconds>(NodeClock::now() - nNow)},
2817
3.57k
                    (uint32_t)mode,
2818
3.57k
                    (uint64_t)coins_count,
2819
3.57k
                    (uint64_t)coins_mem_usage,
2820
3.57k
                    (bool)fFlushForPrune);
2821
3.57k
            }
2822
3.58k
        }
2823
2824
377k
        if (should_write || m_next_write == NodeClock::time_point::max()) {
2825
4.52k
            constexpr auto range{DATABASE_WRITE_INTERVAL_MAX - DATABASE_WRITE_INTERVAL_MIN};
2826
4.52k
            m_next_write = FastRandomContext().rand_uniform_delay(NodeClock::now() + DATABASE_WRITE_INTERVAL_MIN, range);
2827
4.52k
        }
2828
377k
    }
2829
377k
    if (full_flush_completed) {
2830
3.57k
        if (m_chainman.m_options.signals) {
2831
3.57k
            m_chainman.m_options.signals->ChainStateFlushed(this->GetRole(), GetLocator(m_last_flushed_block));
2832
3.57k
        }
2833
2834
3.57k
        if (!m_chainman.m_interrupt && ShouldCompactChainstate(m_chainman.IsInitialBlockDownload())) {
2835
4
            try {
2836
4
                CoinsDB().CompactFullAsync();
2837
4
            } catch (const std::exception& e) {
2838
0
                LogWarning("Failed to start chainstate compaction (%s)", e.what());
2839
0
            }
2840
4
        }
2841
3.57k
    }
2842
377k
    } catch (const std::runtime_error& e) {
2843
0
        return FatalError(m_chainman.GetNotifications(), state, strprintf(_("System error while flushing: %s"), e.what()));
2844
0
    }
2845
377k
    return true;
2846
377k
}
2847
2848
void Chainstate::ForceFlushStateToDisk(bool wipe_cache)
2849
3.44k
{
2850
3.44k
    BlockValidationState state;
2851
3.44k
    if (!this->FlushStateToDisk(state, wipe_cache ? FlushStateMode::FORCE_FLUSH : FlushStateMode::FORCE_SYNC)) {
2852
0
        LogWarning("Failed to force flush state (%s)", state.ToString());
2853
0
    }
2854
3.44k
}
2855
2856
void Chainstate::PruneAndFlush()
2857
37
{
2858
37
    BlockValidationState state;
2859
37
    m_blockman.m_check_for_pruning = true;
2860
37
    if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2861
0
        LogWarning("Failed to flush state (%s)", state.ToString());
2862
0
    }
2863
37
}
2864
2865
static void UpdateTipLog(
2866
    const ChainstateManager& chainman,
2867
    const CCoinsViewCache& coins_tip,
2868
    const CBlockIndex* tip,
2869
    const std::string& func_name,
2870
    const std::string& prefix,
2871
    const std::string& warning_messages,
2872
    const bool background_validation) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
2873
114k
{
2874
2875
114k
    AssertLockHeld(::cs_main);
2876
2877
    // Disable rate limiting as this may log frequently during IBD.
2878
114k
    LogInfo(util::log::NO_RATE_LIMIT, "%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
2879
114k
                   prefix, func_name,
2880
114k
                   tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
2881
114k
                   log(tip->nChainWork.getdouble()) / log(2.0), tip->m_chain_tx_count,
2882
114k
                   FormatISO8601DateTime(tip->GetBlockTime()),
2883
114k
                   background_validation ? chainman.GetBackgroundVerificationProgress(*tip) : chainman.GuessVerificationProgress(tip),
2884
114k
                   coins_tip.DynamicMemoryUsage() / double(1_MiB),
2885
114k
                   coins_tip.GetCacheSize(),
2886
114k
                   !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
2887
114k
}
2888
2889
void Chainstate::UpdateTip(const CBlockIndex* pindexNew)
2890
115k
{
2891
115k
    AssertLockHeld(::cs_main);
2892
115k
    const auto& coins_tip = this->CoinsTip();
2893
2894
    // The remainder of the function isn't relevant if we are not acting on
2895
    // the active chainstate, so return if need be.
2896
115k
    if (this != &m_chainman.ActiveChainstate()) {
2897
        // Only log every so often so that we don't bury log messages at the tip.
2898
1.00k
        constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2899
1.00k
        if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2900
0
            UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, "[background validation] ", "", /*background_validation=*/true);
2901
0
        }
2902
1.00k
        return;
2903
1.00k
    }
2904
2905
    // New best block
2906
114k
    if (m_mempool) {
2907
114k
        m_mempool->AddTransactionsUpdated(1);
2908
114k
    }
2909
2910
114k
    std::vector<bilingual_str> warning_messages;
2911
114k
    if (!m_chainman.IsInitialBlockDownload()) {
2912
96.4k
        auto bits = m_chainman.m_versionbitscache.CheckUnknownActivations(pindexNew, m_chainman.GetParams());
2913
96.4k
        for (auto [bit, active] : bits) {
2914
148
            const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
2915
148
            if (active) {
2916
4
                m_chainman.GetNotifications().warningSet(kernel::Warning::UNKNOWN_NEW_RULES_ACTIVATED, warning);
2917
144
            } else {
2918
144
                warning_messages.push_back(warning);
2919
144
            }
2920
148
        }
2921
96.4k
    }
2922
114k
    UpdateTipLog(m_chainman, coins_tip, pindexNew, __func__, "",
2923
114k
                 util::Join(warning_messages, Untranslated(", ")).original, /*background_validation=*/false);
2924
114k
}
2925
2926
/** Disconnect m_chain's tip.
2927
  * After calling, the mempool will be in an inconsistent state, with
2928
  * transactions from disconnected blocks being added to disconnectpool.  You
2929
  * should make the mempool consistent again by calling MaybeUpdateMempoolForReorg.
2930
  * with cs_main held.
2931
  *
2932
  * If disconnectpool is nullptr, then no disconnected transactions are added to
2933
  * disconnectpool (note that the caller is responsible for mempool consistency
2934
  * in any case).
2935
  */
2936
bool Chainstate::DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool)
2937
9.95k
{
2938
9.95k
    AssertLockHeld(cs_main);
2939
9.95k
    if (m_mempool) AssertLockHeld(m_mempool->cs);
2940
2941
9.95k
    CBlockIndex *pindexDelete = m_chain.Tip();
2942
9.95k
    assert(pindexDelete);
2943
9.95k
    assert(pindexDelete->pprev);
2944
    // Read block from disk.
2945
9.95k
    std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2946
9.95k
    CBlock& block = *pblock;
2947
9.95k
    if (!m_blockman.ReadBlock(block, *pindexDelete)) {
2948
0
        LogError("DisconnectTip(): Failed to read block\n");
2949
0
        return false;
2950
0
    }
2951
    // Apply the block atomically to the chain state.
2952
9.95k
    const auto time_start{SteadyClock::now()};
2953
9.95k
    {
2954
9.95k
        CCoinsViewCache view(&CoinsTip());
2955
9.95k
        assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2956
9.95k
        if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK) {
2957
1
            LogError("DisconnectTip(): DisconnectBlock %s failed\n", pindexDelete->GetBlockHash().ToString());
2958
1
            return false;
2959
1
        }
2960
9.95k
        view.Flush(/*reallocate_cache=*/false); // local CCoinsViewCache goes out of scope
2961
9.95k
    }
2962
9.95k
    LogDebug(BCLog::BENCH, "- Disconnect block: %.2fms\n",
2963
9.95k
             Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));
2964
2965
9.95k
    {
2966
        // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
2967
9.95k
        const int max_height_first{pindexDelete->nHeight - 1};
2968
9.95k
        for (auto& prune_lock : m_blockman.m_prune_locks) {
2969
230
            if (prune_lock.second.height_first <= max_height_first) continue;
2970
2971
230
            prune_lock.second.height_first = max_height_first;
2972
230
            LogDebug(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
2973
230
        }
2974
9.95k
    }
2975
2976
    // Write the chain state to disk, if necessary.
2977
9.95k
    if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
2978
0
        return false;
2979
0
    }
2980
2981
9.95k
    if (disconnectpool && m_mempool) {
2982
        // Save transactions to re-add to mempool at end of reorg. If any entries are evicted for
2983
        // exceeding memory limits, remove them and their descendants from the mempool.
2984
9.85k
        for (auto&& evicted_tx : disconnectpool->AddTransactionsFromBlock(block.vtx)) {
2985
3.24k
            m_mempool->removeRecursive(*evicted_tx, MemPoolRemovalReason::REORG);
2986
3.24k
        }
2987
9.85k
    }
2988
2989
9.95k
    m_chain.SetTip(*pindexDelete->pprev);
2990
9.95k
    m_chainman.UpdateIBDStatus();
2991
2992
9.95k
    UpdateTip(pindexDelete->pprev);
2993
    // Let wallets know transactions went from 1-confirmed to
2994
    // 0-confirmed or conflicted:
2995
9.95k
    if (m_chainman.m_options.signals) {
2996
9.95k
        m_chainman.m_options.signals->BlockDisconnected(std::move(pblock), pindexDelete);
2997
9.95k
    }
2998
9.95k
    return true;
2999
9.95k
}
3000
3001
struct ConnectedBlock {
3002
    const CBlockIndex* pindex;
3003
    std::shared_ptr<const CBlock> pblock;
3004
};
3005
3006
/**
3007
 * Connect a new block to m_chain. block_to_connect is either nullptr or a pointer to a CBlock
3008
 * corresponding to pindexNew, to bypass loading it again from disk.
3009
 *
3010
 * The block is added to connected_blocks if connection succeeds.
3011
 */
3012
bool Chainstate::ConnectTip(
3013
    BlockValidationState& state,
3014
    CBlockIndex* pindexNew,
3015
    std::shared_ptr<const CBlock> block_to_connect,
3016
    std::vector<ConnectedBlock>& connected_blocks,
3017
    DisconnectedBlockTransactions& disconnectpool)
3018
108k
{
3019
108k
    AssertLockHeld(cs_main);
3020
108k
    if (m_mempool) AssertLockHeld(m_mempool->cs);
3021
3022
108k
    assert(pindexNew->pprev == m_chain.Tip());
3023
    // Read block from disk.
3024
108k
    const auto time_1{SteadyClock::now()};
3025
108k
    if (!block_to_connect) {
3026
16.9k
        std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3027
16.9k
        if (!m_blockman.ReadBlock(*pblockNew, *pindexNew)) {
3028
0
            return FatalError(m_chainman.GetNotifications(), state, _("Failed to read block."));
3029
0
        }
3030
16.9k
        block_to_connect = std::move(pblockNew);
3031
91.8k
    } else {
3032
91.8k
        LogDebug(BCLog::BENCH, "  - Using cached block\n");
3033
91.8k
    }
3034
    // Apply the block atomically to the chain state.
3035
108k
    const auto time_2{SteadyClock::now()};
3036
108k
    SteadyClock::time_point time_3;
3037
    // When adding aggregate statistics in the future, keep in mind that
3038
    // num_blocks_total may be zero until the ConnectBlock() call below.
3039
108k
    LogDebug(BCLog::BENCH, "  - Load block from disk: %.2fms\n",
3040
108k
             Ticks<MillisecondsDouble>(time_2 - time_1));
3041
108k
    {
3042
108k
        CoinsViewOverlay& view{*m_coins_views->m_connect_block_view};
3043
108k
        const auto reset_guard{view.StartFetching(*block_to_connect)};
3044
108k
        bool rv = ConnectBlock(*block_to_connect, state, pindexNew, view);
3045
108k
        if (m_chainman.m_options.signals) {
3046
108k
            m_chainman.m_options.signals->BlockChecked(block_to_connect, state);
3047
108k
        }
3048
108k
        if (!rv) {
3049
2.78k
            if (state.IsInvalid())
3050
2.78k
                InvalidBlockFound(pindexNew, state);
3051
2.78k
            LogError("%s: ConnectBlock %s failed, %s\n", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
3052
2.78k
            return false;
3053
2.78k
        }
3054
105k
        time_3 = SteadyClock::now();
3055
105k
        m_chainman.time_connect_total += time_3 - time_2;
3056
105k
        assert(m_chainman.num_blocks_total > 0);
3057
105k
        LogDebug(BCLog::BENCH, "  - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
3058
105k
                 Ticks<MillisecondsDouble>(time_3 - time_2),
3059
105k
                 Ticks<SecondsDouble>(m_chainman.time_connect_total),
3060
105k
                 Ticks<MillisecondsDouble>(m_chainman.time_connect_total) / m_chainman.num_blocks_total);
3061
105k
        view.Flush(/*reallocate_cache=*/false); // No need to reallocate since it only has capacity for 1 block
3062
105k
    }
3063
0
    const auto time_4{SteadyClock::now()};
3064
105k
    m_chainman.time_flush += time_4 - time_3;
3065
105k
    LogDebug(BCLog::BENCH, "  - Flush: %.2fms [%.2fs (%.2fms/blk)]\n",
3066
105k
             Ticks<MillisecondsDouble>(time_4 - time_3),
3067
105k
             Ticks<SecondsDouble>(m_chainman.time_flush),
3068
105k
             Ticks<MillisecondsDouble>(m_chainman.time_flush) / m_chainman.num_blocks_total);
3069
    // Write the chain state to disk, if necessary.
3070
105k
    if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
3071
0
        return false;
3072
0
    }
3073
105k
    const auto time_5{SteadyClock::now()};
3074
105k
    m_chainman.time_chainstate += time_5 - time_4;
3075
105k
    LogDebug(BCLog::BENCH, "  - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3076
105k
             Ticks<MillisecondsDouble>(time_5 - time_4),
3077
105k
             Ticks<SecondsDouble>(m_chainman.time_chainstate),
3078
105k
             Ticks<MillisecondsDouble>(m_chainman.time_chainstate) / m_chainman.num_blocks_total);
3079
    // Remove conflicting transactions from the mempool.
3080
105k
    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
3081
105k
    if (m_mempool) {
3082
105k
        txs_removed_for_block = m_mempool->removeForBlock(block_to_connect->vtx);
3083
105k
        disconnectpool.removeForBlock(block_to_connect->vtx);
3084
105k
    }
3085
    // Update m_chain & related variables.
3086
105k
    m_chain.SetTip(*pindexNew);
3087
105k
    m_chainman.UpdateIBDStatus();
3088
    // Not fired while IBD is active. removeForBlock() above still runs.
3089
105k
    if (m_mempool && m_chainman.m_options.signals && !m_chainman.IsInitialBlockDownload()) {
3090
87.7k
        m_chainman.m_options.signals->MempoolTransactionsRemovedForBlock(block_to_connect, std::move(txs_removed_for_block), pindexNew->nHeight);
3091
87.7k
    }
3092
105k
    UpdateTip(pindexNew);
3093
3094
105k
    const auto time_6{SteadyClock::now()};
3095
105k
    m_chainman.time_post_connect += time_6 - time_5;
3096
105k
    m_chainman.time_total += time_6 - time_1;
3097
105k
    LogDebug(BCLog::BENCH, "  - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
3098
105k
             Ticks<MillisecondsDouble>(time_6 - time_5),
3099
105k
             Ticks<SecondsDouble>(m_chainman.time_post_connect),
3100
105k
             Ticks<MillisecondsDouble>(m_chainman.time_post_connect) / m_chainman.num_blocks_total);
3101
105k
    LogDebug(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n",
3102
105k
             Ticks<MillisecondsDouble>(time_6 - time_1),
3103
105k
             Ticks<SecondsDouble>(m_chainman.time_total),
3104
105k
             Ticks<MillisecondsDouble>(m_chainman.time_total) / m_chainman.num_blocks_total);
3105
3106
    // See if this chainstate has reached a target block and can be used to
3107
    // validate an assumeutxo snapshot. If it can, hashing the UTXO database
3108
    // will be slow, and cs_main could remain locked here for several minutes.
3109
    // If the snapshot is validated, the UTXO hash will be saved to
3110
    // this->m_target_utxohash, causing HistoricalChainstate() to return null
3111
    // and this chainstate to no longer be used. ActivateBestChain() will also
3112
    // stop connecting blocks to this chainstate because this->ReachedTarget()
3113
    // will be true and this->setBlockIndexCandidates will not have additional
3114
    // blocks.
3115
105k
    Chainstate& current_cs{m_chainman.CurrentChainstate()};
3116
105k
    m_chainman.MaybeValidateSnapshot(*this, current_cs);
3117
3118
105k
    connected_blocks.emplace_back(pindexNew, std::move(block_to_connect));
3119
105k
    return true;
3120
105k
}
3121
3122
/**
3123
 * Return the tip of the chain with the most work in it, that isn't
3124
 * known to be invalid (it's however far from certain to be valid).
3125
 */
3126
CBlockIndex* Chainstate::FindMostWorkChain()
3127
119k
{
3128
119k
    AssertLockHeld(::cs_main);
3129
119k
    do {
3130
119k
        CBlockIndex *pindexNew = nullptr;
3131
3132
        // Find the best candidate header.
3133
119k
        {
3134
119k
            std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
3135
119k
            if (it == setBlockIndexCandidates.rend())
3136
0
                return nullptr;
3137
119k
            pindexNew = *it;
3138
119k
        }
3139
3140
        // Check whether all blocks on the path between the currently active chain and the candidate are valid.
3141
        // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
3142
0
        bool fInvalidAncestor = false;
3143
228k
        for (CBlockIndex *pindexTest = pindexNew; pindexTest && !m_chain.Contains(*pindexTest); pindexTest = pindexTest->pprev) {
3144
108k
            assert(pindexTest->HaveNumChainTxs() || pindexTest->nHeight == 0);
3145
3146
            // Pruned nodes may have entries in setBlockIndexCandidates for
3147
            // which block files have been deleted.  Remove those as candidates
3148
            // for the most work chain if we come across them; we can't switch
3149
            // to a chain unless we have all the non-active-chain parent blocks.
3150
108k
            bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_VALID;
3151
108k
            bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
3152
108k
            if (fFailedChain || fMissingData) {
3153
                // Candidate chain is not usable (either invalid or missing data)
3154
13
                if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
3155
0
                    m_chainman.m_best_invalid = pindexNew;
3156
0
                }
3157
                // Remove the entire chain from the set.
3158
13
                for (CBlockIndex *pindexFailed = pindexNew; pindexFailed != pindexTest; pindexFailed = pindexFailed->pprev) {
3159
                    // If we're missing data and not a descendant of an invalid block,
3160
                    // then add back to m_blocks_unlinked, so that if the block arrives in the future
3161
                    // we can try adding to setBlockIndexCandidates again.
3162
0
                    if (fMissingData && !fFailedChain) {
3163
                        // Avoid duplicate entries in m_blocks_unlinked. If the same entry is
3164
                        // processed twice in ReceivedBlockTransactions(), it may be re-added to
3165
                        // setBlockIndexCandidates with a modified nSequenceId, breaking ordering
3166
                        // guarantees and leading to undefined behavior.
3167
0
                        m_blockman.AddUnlinkedBlock(pindexFailed);
3168
0
                    }
3169
0
                    setBlockIndexCandidates.erase(pindexFailed);
3170
0
                }
3171
13
                setBlockIndexCandidates.erase(pindexTest);
3172
13
                fInvalidAncestor = true;
3173
13
                break;
3174
13
            }
3175
108k
        }
3176
119k
        if (!fInvalidAncestor)
3177
119k
            return pindexNew;
3178
119k
    } while(true);
3179
119k
}
3180
3181
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
3182
105k
void Chainstate::PruneBlockIndexCandidates() {
3183
    // Note that we can't delete the current block itself, as we may need to return to it later in case a
3184
    // reorganization to a better block fails.
3185
105k
    std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3186
203k
    while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
3187
97.5k
        setBlockIndexCandidates.erase(it++);
3188
97.5k
    }
3189
    // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3190
105k
    assert(!setBlockIndexCandidates.empty());
3191
105k
}
3192
3193
/**
3194
 * Try to make some progress towards making index_most_work the active block.
3195
 * pblock is either nullptr or a pointer to a CBlock corresponding to index_most_work.
3196
 *
3197
 * @returns true unless a system error occurred
3198
 */
3199
bool Chainstate::ActivateBestChainStep(BlockValidationState& state, CBlockIndex& index_most_work, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, std::vector<ConnectedBlock>& connected_blocks)
3200
100k
{
3201
100k
    AssertLockHeld(cs_main);
3202
100k
    if (m_mempool) AssertLockHeld(m_mempool->cs);
3203
3204
100k
    const CBlockIndex* pindexOldTip = m_chain.Tip();
3205
100k
    const CBlockIndex* pindexFork = m_chain.FindFork(index_most_work);
3206
3207
    // Disconnect active blocks which are no longer in the best chain.
3208
100k
    bool fBlocksDisconnected = false;
3209
100k
    DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};
3210
108k
    while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
3211
8.00k
        if (!DisconnectTip(state, &disconnectpool)) {
3212
            // This is likely a fatal error, but keep the mempool consistent,
3213
            // just in case. Only remove from the mempool in this case.
3214
1
            MaybeUpdateMempoolForReorg(disconnectpool, false);
3215
3216
            // If we're unable to disconnect a block during normal operation,
3217
            // then that is a failure of our local system -- we should abort
3218
            // rather than stay on a less work chain.
3219
1
            FatalError(m_chainman.GetNotifications(), state, _("Failed to disconnect block."));
3220
1
            return false;
3221
1
        }
3222
8.00k
        fBlocksDisconnected = true;
3223
8.00k
    }
3224
3225
    // Build list of new blocks to connect (in descending height order).
3226
100k
    std::vector<CBlockIndex*> vpindexToConnect;
3227
100k
    bool fContinue = true;
3228
100k
    int nHeight = pindexFork ? pindexFork->nHeight : -1;
3229
201k
    while (fContinue && nHeight != index_most_work.nHeight) {
3230
        // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3231
        // a few blocks along the way.
3232
101k
        int nTargetHeight = std::min(nHeight + 32, index_most_work.nHeight);
3233
101k
        vpindexToConnect.clear();
3234
101k
        vpindexToConnect.reserve(nTargetHeight - nHeight);
3235
101k
        CBlockIndex* pindexIter = index_most_work.GetAncestor(nTargetHeight);
3236
436k
        while (pindexIter && pindexIter->nHeight != nHeight) {
3237
335k
            vpindexToConnect.push_back(pindexIter);
3238
335k
            pindexIter = pindexIter->pprev;
3239
335k
        }
3240
101k
        nHeight = nTargetHeight;
3241
3242
        // Connect new blocks.
3243
108k
        for (CBlockIndex* pindexConnect : vpindexToConnect | std::views::reverse) {
3244
108k
            if (!ConnectTip(state, pindexConnect, pindexConnect == &index_most_work ? pblock : std::shared_ptr<const CBlock>(), connected_blocks, disconnectpool)) {
3245
2.78k
                if (state.IsInvalid()) {
3246
                    // The block violates a consensus rule.
3247
2.78k
                    if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3248
2.78k
                        InvalidChainFound(vpindexToConnect.front());
3249
2.78k
                    }
3250
2.78k
                    state = BlockValidationState();
3251
2.78k
                    fInvalidFound = true;
3252
2.78k
                    fContinue = false;
3253
2.78k
                    break;
3254
2.78k
                } else {
3255
                    // A system error occurred (disk space, database error, ...).
3256
                    // Make the mempool consistent with the current tip, just in case
3257
                    // any observers try to use it before shutdown.
3258
0
                    MaybeUpdateMempoolForReorg(disconnectpool, false);
3259
0
                    return false;
3260
0
                }
3261
105k
            } else {
3262
105k
                PruneBlockIndexCandidates();
3263
105k
                if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
3264
                    // We're in a better position than we were. Return temporarily to release the lock.
3265
97.9k
                    fContinue = false;
3266
97.9k
                    break;
3267
97.9k
                }
3268
105k
            }
3269
108k
        }
3270
101k
    }
3271
3272
100k
    if (fBlocksDisconnected) {
3273
        // If any blocks were disconnected, disconnectpool may be non empty.  Add
3274
        // any disconnected transactions back to the mempool.
3275
187
        MaybeUpdateMempoolForReorg(disconnectpool, true);
3276
187
    }
3277
100k
    if (m_mempool) m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
3278
3279
100k
    CheckForkWarningConditions();
3280
3281
100k
    return true;
3282
100k
}
3283
3284
static SynchronizationState GetSynchronizationState(bool init, bool blockfiles_indexed)
3285
172k
{
3286
172k
    if (!init) return SynchronizationState::POST_INIT;
3287
24.5k
    if (!blockfiles_indexed) return SynchronizationState::INIT_REINDEX;
3288
22.4k
    return SynchronizationState::INIT_DOWNLOAD;
3289
24.5k
}
3290
3291
void ChainstateManager::UpdateIBDStatus()
3292
117k
{
3293
117k
    AssertLockHeld(cs_main);
3294
117k
    if (!m_cached_is_ibd.load(std::memory_order_relaxed)) return;
3295
20.9k
    if (m_blockman.LoadingBlocks()) return;
3296
17.9k
    if (!CurrentChainstate().m_chain.IsTipRecent(MinimumChainWork(), m_options.max_tip_age)) return;
3297
916
    LogInfo("Leaving InitialBlockDownload (latching to false)");
3298
916
    m_cached_is_ibd.store(false, std::memory_order_relaxed);
3299
916
}
3300
3301
bool ChainstateManager::NotifyHeaderTip()
3302
146k
{
3303
146k
    bool fNotify = false;
3304
146k
    bool fInitialBlockDownload = false;
3305
146k
    CBlockIndex* pindexHeader = nullptr;
3306
146k
    {
3307
146k
        LOCK(GetMutex());
3308
146k
        pindexHeader = m_best_header;
3309
3310
146k
        if (pindexHeader != m_last_notified_header) {
3311
74.0k
            fNotify = true;
3312
74.0k
            fInitialBlockDownload = IsInitialBlockDownload();
3313
74.0k
            m_last_notified_header = pindexHeader;
3314
74.0k
        }
3315
146k
    }
3316
    // Send block tip changed notifications without the lock held
3317
146k
    if (fNotify) {
3318
74.0k
        GetNotifications().headerTip(GetSynchronizationState(fInitialBlockDownload, m_blockman.m_blockfiles_indexed), pindexHeader->nHeight, pindexHeader->nTime, false);
3319
74.0k
    }
3320
146k
    return fNotify;
3321
146k
}
3322
3323
129k
static void LimitValidationInterfaceQueue(ValidationSignals& signals) LOCKS_EXCLUDED(cs_main) {
3324
129k
    AssertLockNotHeld(cs_main);
3325
3326
129k
    if (signals.CallbacksPending() > 10) {
3327
999
        signals.SyncWithValidationInterfaceQueue();
3328
999
    }
3329
129k
}
3330
3331
bool Chainstate::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
3332
116k
{
3333
116k
    AssertLockNotHeld(m_chainstate_mutex);
3334
3335
    // Note that while we're often called here from ProcessNewBlock, this is
3336
    // far from a guarantee. Things in the P2P/RPC will often end up calling
3337
    // us in the middle of ProcessNewBlock - do not assume pblock is set
3338
    // sanely for performance or correctness!
3339
116k
    AssertLockNotHeld(::cs_main);
3340
3341
    // ABC maintains a fair degree of expensive-to-calculate internal state
3342
    // because this function periodically releases cs_main so that it does not lock up other threads for too long
3343
    // during large connects - and to allow for e.g. the callback queue to drain
3344
    // we use m_chainstate_mutex to enforce mutual exclusion so that only one caller may execute this function at a time
3345
116k
    LOCK(m_chainstate_mutex);
3346
3347
    // Belt-and-suspenders check that we aren't attempting to advance the
3348
    // chainstate past the target block.
3349
116k
    if (WITH_LOCK(::cs_main, return m_target_utxohash)) {
3350
0
        LogError("%s", STR_INTERNAL_BUG("m_target_utxohash is set - this chainstate should not be in operation."));
3351
0
        return Assume(false);
3352
0
    }
3353
3354
116k
    CBlockIndex *pindexMostWork = nullptr;
3355
116k
    CBlockIndex *pindexNewTip = nullptr;
3356
116k
    bool exited_ibd{false};
3357
127k
    do {
3358
        // Block until the validation queue drains. This should largely
3359
        // never happen in normal operation, however may happen during
3360
        // reindex, causing memory blowup if we run too far ahead.
3361
        // Note that if a validationinterface callback ends up calling
3362
        // ActivateBestChain this may lead to a deadlock! We should
3363
        // probably have a DEBUG_LOCKORDER test for this in the future.
3364
127k
        if (m_chainman.m_options.signals) LimitValidationInterfaceQueue(*m_chainman.m_options.signals);
3365
3366
127k
        {
3367
127k
            LOCK(cs_main);
3368
127k
            {
3369
            // Lock transaction pool for at least as long as it takes for connected_blocks to be consumed
3370
127k
            LOCK(MempoolMutex());
3371
127k
            const bool was_in_ibd = m_chainman.IsInitialBlockDownload();
3372
127k
            CBlockIndex* starting_tip = m_chain.Tip();
3373
127k
            bool blocks_connected = false;
3374
127k
            do {
3375
                // We absolutely may not unlock cs_main until we've made forward progress
3376
                // (with the exception of shutdown due to hardware issues, low disk space, etc).
3377
127k
                std::vector<ConnectedBlock> connected_blocks; // Destructed before cs_main is unlocked
3378
3379
127k
                if (pindexMostWork == nullptr) {
3380
119k
                    pindexMostWork = FindMostWorkChain();
3381
119k
                }
3382
3383
                // Whether we have anything to do at all.
3384
127k
                if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
3385
26.7k
                    break;
3386
26.7k
                }
3387
3388
100k
                bool fInvalidFound = false;
3389
100k
                std::shared_ptr<const CBlock> nullBlockPtr;
3390
                // BlockConnected signals must be sent for the original role;
3391
                // in case snapshot validation is completed during ActivateBestChainStep, the
3392
                // result of GetRole() changes from BACKGROUND to NORMAL.
3393
100k
               const ChainstateRole chainstate_role{this->GetRole()};
3394
100k
                if (!ActivateBestChainStep(state, *pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connected_blocks)) {
3395
                    // A system error occurred
3396
1
                    return false;
3397
1
                }
3398
100k
                blocks_connected = true;
3399
3400
100k
                if (fInvalidFound) {
3401
                    // Wipe cache, we may need another branch now.
3402
2.78k
                    pindexMostWork = nullptr;
3403
2.78k
                }
3404
100k
                pindexNewTip = m_chain.Tip();
3405
3406
105k
                for (auto& [index, block] : std::move(connected_blocks)) {
3407
105k
                    if (m_chainman.m_options.signals) {
3408
105k
                        m_chainman.m_options.signals->BlockConnected(chainstate_role, std::move(Assert(block)), Assert(index));
3409
105k
                    }
3410
105k
                }
3411
3412
                // Break this do-while to ensure we don't advance past the target block.
3413
100k
                if (ReachedTarget()) {
3414
8
                    break;
3415
8
                }
3416
100k
            } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
3417
127k
            if (!blocks_connected) return true;
3418
3419
100k
            const CBlockIndex* pindexFork = starting_tip ? m_chain.FindFork(*starting_tip) : nullptr;
3420
100k
            bool still_in_ibd = m_chainman.IsInitialBlockDownload();
3421
3422
100k
            if (was_in_ibd && !still_in_ibd) {
3423
                // Active chainstate has exited IBD.
3424
505
                exited_ibd = true;
3425
505
            }
3426
3427
            // Notify external listeners about the new tip.
3428
            // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
3429
100k
            if (this == &m_chainman.ActiveChainstate() && pindexFork != pindexNewTip) {
3430
                // Notify ValidationInterface subscribers
3431
97.2k
                if (m_chainman.m_options.signals) {
3432
97.2k
                    m_chainman.m_options.signals->UpdatedBlockTip(pindexNewTip, pindexFork, still_in_ibd);
3433
97.2k
                }
3434
3435
97.2k
                if (kernel::IsInterrupted(m_chainman.GetNotifications().blockTip(
3436
97.2k
                        /*state=*/GetSynchronizationState(still_in_ibd, m_chainman.m_blockman.m_blockfiles_indexed),
3437
97.2k
                        /*index=*/*pindexNewTip,
3438
97.2k
                        /*verification_progress=*/m_chainman.GuessVerificationProgress(pindexNewTip))))
3439
2
                {
3440
                    // Just breaking and returning success for now. This could
3441
                    // be changed to bubble up the kernel::Interrupted value to
3442
                    // the caller so the caller could distinguish between
3443
                    // completed and interrupted operations.
3444
2
                    break;
3445
2
                }
3446
97.2k
            }
3447
100k
            } // release MempoolMutex
3448
            // Notify external listeners about the new tip, even if pindexFork == pindexNewTip.
3449
100k
            if (m_chainman.m_options.signals && this == &m_chainman.ActiveChainstate()) {
3450
99.9k
                m_chainman.m_options.signals->ActiveTipChange(*Assert(pindexNewTip), m_chainman.IsInitialBlockDownload());
3451
99.9k
            }
3452
100k
        } // release cs_main
3453
        // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3454
3455
0
        bool reached_target;
3456
100k
        {
3457
100k
            LOCK(m_chainman.GetMutex());
3458
100k
            if (exited_ibd) {
3459
                // If a background chainstate is in use, we may need to rebalance our
3460
                // allocation of caches once a chainstate exits initial block download.
3461
505
                m_chainman.MaybeRebalanceCaches();
3462
505
            }
3463
3464
            // Write changes periodically to disk, after relay.
3465
100k
            if (!FlushStateToDisk(state, FlushStateMode::PERIODIC)) {
3466
0
                return false;
3467
0
            }
3468
3469
100k
            reached_target = ReachedTarget();
3470
100k
        }
3471
3472
100k
        if (reached_target) {
3473
            // Chainstate has reached the target block, so exit.
3474
            //
3475
            // Restart indexes so indexes can resync and index new blocks after
3476
            // the target block.
3477
            //
3478
            // This cannot be done while holding cs_main (within
3479
            // MaybeValidateSnapshot) or a cs_main deadlock will occur.
3480
8
            if (m_chainman.snapshot_download_completed) {
3481
7
                m_chainman.snapshot_download_completed();
3482
7
            }
3483
8
            break;
3484
8
        }
3485
3486
        // We check interrupt only after giving ActivateBestChainStep a chance to run once so that we
3487
        // never interrupt before connecting the genesis block during LoadChainTip(). Previously this
3488
        // caused an assert() failure during interrupt in such cases as the UTXO DB flushing checks
3489
        // that the best block hash is non-null.
3490
100k
        if (m_chainman.m_interrupt) break;
3491
100k
    } while (pindexNewTip != pindexMostWork);
3492
3493
89.9k
    m_chainman.CheckBlockIndex();
3494
3495
89.9k
    return true;
3496
116k
}
3497
3498
bool Chainstate::PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
3499
10
{
3500
10
    AssertLockNotHeld(m_chainstate_mutex);
3501
10
    AssertLockNotHeld(::cs_main);
3502
10
    {
3503
10
        LOCK(cs_main);
3504
10
        if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
3505
            // Nothing to do, this block is not at the tip.
3506
1
            return true;
3507
1
        }
3508
9
        if (m_chain.Tip()->nChainWork > m_chainman.nLastPreciousChainwork) {
3509
            // The chain has been extended since the last call, reset the counter.
3510
5
            m_chainman.nBlockReverseSequenceId = -1;
3511
5
        }
3512
9
        m_chainman.nLastPreciousChainwork = m_chain.Tip()->nChainWork;
3513
9
        setBlockIndexCandidates.erase(pindex);
3514
9
        pindex->nSequenceId = m_chainman.nBlockReverseSequenceId;
3515
9
        if (m_chainman.nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3516
            // We can't keep reducing the counter if somebody really wants to
3517
            // call preciousblock 2**31-1 times on the same set of tips...
3518
9
            m_chainman.nBlockReverseSequenceId--;
3519
9
        }
3520
9
        if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveNumChainTxs()) {
3521
8
            setBlockIndexCandidates.insert(pindex);
3522
8
            PruneBlockIndexCandidates();
3523
8
        }
3524
9
    }
3525
3526
0
    return ActivateBestChain(state, std::shared_ptr<const CBlock>());
3527
10
}
3528
3529
bool Chainstate::InvalidateBlock(BlockValidationState& state, CBlockIndex* const pindex)
3530
184
{
3531
184
    AssertLockNotHeld(m_chainstate_mutex);
3532
184
    AssertLockNotHeld(::cs_main);
3533
3534
    // Genesis block can't be invalidated
3535
184
    assert(pindex);
3536
184
    if (pindex->nHeight == 0) return false;
3537
3538
    // We do not allow ActivateBestChain() to run while InvalidateBlock() is
3539
    // running, as that could cause the tip to change while we disconnect
3540
    // blocks.
3541
184
    LOCK(m_chainstate_mutex);
3542
3543
    // We'll be acquiring and releasing cs_main below, to allow the validation
3544
    // callbacks to run. However, we should keep the block index in a
3545
    // consistent state as we disconnect blocks -- in particular we need to
3546
    // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3547
    // To avoid walking the block index repeatedly in search of candidates,
3548
    // build a map once so that we can look up candidate blocks by chain
3549
    // work as we go.
3550
184
    std::multimap<const arith_uint256, CBlockIndex*> highpow_outofchain_headers;
3551
3552
184
    {
3553
184
        LOCK(cs_main);
3554
40.4k
        for (auto& entry : m_blockman.m_block_index) {
3555
40.4k
            CBlockIndex& candidate = entry.second;
3556
            // We don't need to put anything in our active chain into the
3557
            // multimap, because those candidates will be found and considered
3558
            // as we disconnect.
3559
            // Instead, consider only non-active-chain blocks that score
3560
            // at least as good with CBlockIndexWorkComparator as the new tip.
3561
40.4k
            if (!m_chain.Contains(candidate) &&
3562
40.4k
                !CBlockIndexWorkComparator()(&candidate, pindex->pprev) &&
3563
40.4k
                !(candidate.nStatus & BLOCK_FAILED_VALID)) {
3564
117
                highpow_outofchain_headers.insert({candidate.nChainWork, &candidate});
3565
117
            }
3566
40.4k
        }
3567
184
    }
3568
3569
184
    CBlockIndex* to_mark_failed = pindex;
3570
184
    bool pindex_was_in_chain = false;
3571
184
    int disconnected = 0;
3572
3573
    // Disconnect (descendants of) pindex, and mark them invalid.
3574
2.13k
    while (true) {
3575
2.13k
        if (m_chainman.m_interrupt) break;
3576
3577
        // Make sure the queue of validation callbacks doesn't grow unboundedly.
3578
2.13k
        if (m_chainman.m_options.signals) LimitValidationInterfaceQueue(*m_chainman.m_options.signals);
3579
3580
2.13k
        LOCK(cs_main);
3581
        // Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
3582
        // called after DisconnectTip without unlocking in between
3583
2.13k
        LOCK(MempoolMutex());
3584
2.13k
        if (!m_chain.Contains(*pindex)) break;
3585
1.95k
        pindex_was_in_chain = true;
3586
1.95k
        CBlockIndex* const disconnected_tip{m_chain.Tip()};
3587
3588
        // ActivateBestChain considers blocks already in m_chain
3589
        // unconditionally valid already, so force disconnect away from it.
3590
1.95k
        DisconnectedBlockTransactions disconnectpool{MAX_DISCONNECTED_TX_POOL_BYTES};
3591
1.95k
        bool ret = DisconnectTip(state, &disconnectpool);
3592
        // DisconnectTip will add transactions to disconnectpool.
3593
        // Adjust the mempool to be consistent with the new tip, adding
3594
        // transactions back to the mempool if disconnecting was successful,
3595
        // and we're not doing a very deep invalidation (in which case
3596
        // keeping the mempool up to date is probably futile anyway).
3597
1.95k
        MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
3598
1.95k
        if (!ret) return false;
3599
1.95k
        CBlockIndex* new_tip{m_chain.Tip()};
3600
1.95k
        assert(disconnected_tip->pprev == new_tip);
3601
3602
        // We immediately mark the disconnected blocks as invalid.
3603
        // This prevents a case where pruned nodes may fail to invalidateblock
3604
        // and be left unable to start as they have no tip candidates (as there
3605
        // are no blocks that meet the "have data and are not invalid per
3606
        // nStatus" criteria for inclusion in setBlockIndexCandidates).
3607
1.95k
        disconnected_tip->nStatus |= BLOCK_FAILED_VALID;
3608
1.95k
        m_blockman.m_dirty_blockindex.insert(disconnected_tip);
3609
1.95k
        setBlockIndexCandidates.erase(disconnected_tip);
3610
1.95k
        setBlockIndexCandidates.insert(new_tip);
3611
3612
        // Mark out-of-chain descendants of the invalidated block as invalid
3613
        // Add any equal or more work headers that are not invalidated to setBlockIndexCandidates
3614
        // Recalculate m_best_header if it became invalid.
3615
1.95k
        auto candidate_it = highpow_outofchain_headers.lower_bound(new_tip->nChainWork);
3616
3617
1.95k
        const bool best_header_needs_update{m_chainman.m_best_header->GetAncestor(disconnected_tip->nHeight) == disconnected_tip};
3618
1.95k
        if (best_header_needs_update) {
3619
            // new_tip is definitely still valid at this point, but there may be better ones
3620
1.90k
            m_chainman.m_best_header = new_tip;
3621
1.90k
        }
3622
3623
2.09k
        while (candidate_it != highpow_outofchain_headers.end()) {
3624
144
            CBlockIndex* candidate{candidate_it->second};
3625
144
            if (candidate->GetAncestor(disconnected_tip->nHeight) == disconnected_tip) {
3626
                // Children of failed blocks are marked as BLOCK_FAILED_VALID.
3627
11
                candidate->nStatus |= BLOCK_FAILED_VALID;
3628
11
                m_blockman.m_dirty_blockindex.insert(candidate);
3629
                // If invalidated, the block is irrelevant for setBlockIndexCandidates
3630
                // and for m_best_header and can be removed from the cache.
3631
11
                candidate_it = highpow_outofchain_headers.erase(candidate_it);
3632
11
                continue;
3633
11
            }
3634
133
            if (!CBlockIndexWorkComparator()(candidate, new_tip) &&
3635
133
                candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
3636
133
                candidate->HaveNumChainTxs()) {
3637
115
                setBlockIndexCandidates.insert(candidate);
3638
                // Do not remove candidate from the highpow_outofchain_headers cache, because it might be a descendant of the block being invalidated
3639
                // which needs to be marked failed later.
3640
115
            }
3641
133
            if (best_header_needs_update &&
3642
133
                m_chainman.m_best_header->nChainWork < candidate->nChainWork) {
3643
7
                m_chainman.m_best_header = candidate;
3644
7
            }
3645
133
            ++candidate_it;
3646
133
        }
3647
3648
        // Track the last disconnected block to call InvalidChainFound on it.
3649
1.95k
        to_mark_failed = disconnected_tip;
3650
1.95k
    }
3651
3652
184
    m_chainman.CheckBlockIndex();
3653
3654
184
    {
3655
184
        LOCK(cs_main);
3656
184
        if (m_chain.Contains(*to_mark_failed)) {
3657
            // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
3658
0
            return false;
3659
0
        }
3660
3661
        // Mark pindex as invalid if it never was in the main chain
3662
184
        if (!pindex_was_in_chain && !(pindex->nStatus & BLOCK_FAILED_VALID)) {
3663
2
            pindex->nStatus |= BLOCK_FAILED_VALID;
3664
2
            m_blockman.m_dirty_blockindex.insert(pindex);
3665
2
            setBlockIndexCandidates.erase(pindex);
3666
2
        }
3667
3668
        // If any new blocks somehow arrived while we were disconnecting
3669
        // (above), then the pre-calculation of what should go into
3670
        // setBlockIndexCandidates may have missed entries. This would
3671
        // technically be an inconsistency in the block index, but if we clean
3672
        // it up here, this should be an essentially unobservable error.
3673
        // Loop back over all block index entries and add any missing entries
3674
        // to setBlockIndexCandidates.
3675
40.4k
        for (auto& [_, block_index] : m_blockman.m_block_index) {
3676
40.4k
            if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveNumChainTxs() && !setBlockIndexCandidates.value_comp()(&block_index, m_chain.Tip())) {
3677
276
                setBlockIndexCandidates.insert(&block_index);
3678
276
            }
3679
40.4k
        }
3680
3681
184
        InvalidChainFound(to_mark_failed);
3682
184
    }
3683
3684
    // Only notify about a new block tip if the active chain was modified.
3685
184
    if (pindex_was_in_chain) {
3686
        // Ignoring return value for now, this could be changed to bubble up
3687
        // kernel::Interrupted value to the caller so the caller could
3688
        // distinguish between completed and interrupted operations. It might
3689
        // also make sense for the blockTip notification to have an enum
3690
        // parameter indicating the source of the tip change so hooks can
3691
        // distinguish user-initiated invalidateblock changes from other
3692
        // changes.
3693
182
        (void)m_chainman.GetNotifications().blockTip(
3694
182
            /*state=*/GetSynchronizationState(m_chainman.IsInitialBlockDownload(), m_chainman.m_blockman.m_blockfiles_indexed),
3695
182
            /*index=*/*to_mark_failed->pprev,
3696
182
            /*verification_progress=*/WITH_LOCK(m_chainman.GetMutex(), return m_chainman.GuessVerificationProgress(to_mark_failed->pprev)));
3697
3698
        // Fire ActiveTipChange now for the current chain tip to make sure clients are notified.
3699
        // ActivateBestChain may call this as well, but not necessarily.
3700
182
        if (m_chainman.m_options.signals) {
3701
182
            m_chainman.m_options.signals->ActiveTipChange(*Assert(m_chain.Tip()), m_chainman.IsInitialBlockDownload());
3702
182
        }
3703
182
    }
3704
184
    return true;
3705
184
}
3706
3707
void Chainstate::SetBlockFailureFlags(CBlockIndex* invalid_block)
3708
5.76k
{
3709
5.76k
    AssertLockHeld(cs_main);
3710
3711
11.0M
    for (auto& [_, block_index] : m_blockman.m_block_index) {
3712
11.0M
        if (invalid_block != &block_index && block_index.GetAncestor(invalid_block->nHeight) == invalid_block) {
3713
7.12k
            block_index.nStatus |= BLOCK_FAILED_VALID;
3714
7.12k
            m_blockman.m_dirty_blockindex.insert(&block_index);
3715
7.12k
        }
3716
11.0M
    }
3717
5.76k
}
3718
3719
31
void Chainstate::ResetBlockFailureFlags(CBlockIndex *pindex) {
3720
31
    AssertLockHeld(cs_main);
3721
3722
31
    int nHeight = pindex->nHeight;
3723
3724
    // Remove the invalidity flag from this block and all its descendants and ancestors.
3725
5.62k
    for (auto& [_, block_index] : m_blockman.m_block_index) {
3726
5.62k
        if ((block_index.nStatus & BLOCK_FAILED_VALID) && (block_index.GetAncestor(nHeight) == pindex || pindex->GetAncestor(block_index.nHeight) == &block_index)) {
3727
1.23k
            block_index.nStatus &= ~BLOCK_FAILED_VALID;
3728
1.23k
            m_blockman.m_dirty_blockindex.insert(&block_index);
3729
1.23k
            if (block_index.IsValid(BLOCK_VALID_TRANSACTIONS) && block_index.HaveNumChainTxs() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), &block_index)) {
3730
1.22k
                setBlockIndexCandidates.insert(&block_index);
3731
1.22k
            }
3732
1.23k
            if (&block_index == m_chainman.m_best_invalid) {
3733
                // Reset invalid block marker if it was pointing to one of those.
3734
31
                m_chainman.m_best_invalid = nullptr;
3735
31
            }
3736
1.23k
        }
3737
5.62k
    }
3738
31
}
3739
3740
void Chainstate::TryAddBlockIndexCandidate(CBlockIndex* pindex)
3741
254k
{
3742
254k
    AssertLockHeld(cs_main);
3743
3744
    // Do not continue building a chainstate that is based on an invalid
3745
    // snapshot. This is a belt-and-suspenders type of check because if an
3746
    // invalid snapshot is loaded, the node will shut down to force a manual
3747
    // intervention. But it is good to handle this case correctly regardless.
3748
254k
    if (m_assumeutxo == Assumeutxo::INVALID) {
3749
0
        return;
3750
0
    }
3751
3752
    // The block only is a candidate for the most-work-chain if it has the same
3753
    // or more work than our current tip.
3754
254k
    if (m_chain.Tip() != nullptr && setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
3755
151k
        return;
3756
151k
    }
3757
3758
103k
    const CBlockIndex* target_block{TargetBlock()};
3759
103k
    if (!target_block) {
3760
        // If no specific target block, add all entries that have more
3761
        // work than the tip.
3762
100k
        setBlockIndexCandidates.insert(pindex);
3763
100k
    } else {
3764
        // If there is a target block, only consider connecting blocks
3765
        // towards the target block.
3766
3.03k
        if (target_block->GetAncestor(pindex->nHeight) == pindex) {
3767
809
            setBlockIndexCandidates.insert(pindex);
3768
809
        }
3769
3.03k
    }
3770
103k
}
3771
3772
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3773
void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)
3774
104k
{
3775
104k
    AssertLockHeld(cs_main);
3776
104k
    pindexNew->nTx = block.vtx.size();
3777
    // Typically m_chain_tx_count will be 0 at this point, but it can be nonzero if this
3778
    // is a pruned block which is being downloaded again, or if this is an
3779
    // assumeutxo snapshot block which has a hardcoded m_chain_tx_count value from the
3780
    // snapshot metadata. If the pindex is not the snapshot block and the
3781
    // m_chain_tx_count value is not zero, assert that value is actually correct.
3782
104k
    auto prev_tx_sum = [](CBlockIndex& block) { return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };
3783
104k
    if (!Assume(pindexNew->m_chain_tx_count == 0 || pindexNew->m_chain_tx_count == prev_tx_sum(*pindexNew) ||
3784
104k
                std::ranges::any_of(m_chainstates, [&](const auto& cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->SnapshotBase() == pindexNew; }))) {
3785
0
        LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3786
0
            pindexNew->nHeight, pindexNew->m_chain_tx_count, prev_tx_sum(*pindexNew), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
3787
0
        pindexNew->m_chain_tx_count = 0;
3788
0
    }
3789
104k
    pindexNew->nFile = pos.nFile;
3790
104k
    pindexNew->nDataPos = pos.nPos;
3791
104k
    pindexNew->nUndoPos = 0;
3792
104k
    pindexNew->nStatus |= BLOCK_HAVE_DATA;
3793
104k
    if (DeploymentActiveAt(*pindexNew, *this, Consensus::DEPLOYMENT_SEGWIT)) {
3794
101k
        pindexNew->nStatus |= BLOCK_OPT_WITNESS;
3795
101k
    }
3796
104k
    pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3797
104k
    m_blockman.m_dirty_blockindex.insert(pindexNew);
3798
3799
104k
    if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveNumChainTxs()) {
3800
        // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3801
100k
        std::deque<CBlockIndex*> queue;
3802
100k
        queue.push_back(pindexNew);
3803
3804
        // Recursively process any descendant blocks that now may be eligible to be connected.
3805
205k
        while (!queue.empty()) {
3806
104k
            CBlockIndex *pindex = queue.front();
3807
104k
            queue.pop_front();
3808
            // Before setting m_chain_tx_count, assert that it is 0 or already set to
3809
            // the correct value. This assert will fail after receiving the
3810
            // assumeutxo snapshot block if assumeutxo snapshot metadata has an
3811
            // incorrect hardcoded AssumeutxoData::m_chain_tx_count value.
3812
104k
            if (!Assume(pindex->m_chain_tx_count == 0 || pindex->m_chain_tx_count == prev_tx_sum(*pindex))) {
3813
0
                LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",
3814
0
                   pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);
3815
0
            }
3816
104k
            pindex->m_chain_tx_count = prev_tx_sum(*pindex);
3817
104k
            pindex->nSequenceId = nBlockSequenceId++;
3818
107k
            for (const auto& c : m_chainstates) {
3819
107k
                c->TryAddBlockIndexCandidate(pindex);
3820
107k
            }
3821
104k
            std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
3822
109k
            while (range.first != range.second) {
3823
4.23k
                std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3824
4.23k
                queue.push_back(it->second);
3825
4.23k
                range.first++;
3826
4.23k
                m_blockman.m_blocks_unlinked.erase(it);
3827
4.23k
            }
3828
104k
        }
3829
100k
    } else {
3830
4.23k
        if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3831
4.23k
            m_blockman.AddUnlinkedBlock(pindexNew);
3832
4.23k
        }
3833
4.23k
    }
3834
104k
}
3835
3836
static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3837
331k
{
3838
    // Check proof of work matches claimed amount
3839
331k
    if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3840
5
        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
3841
3842
331k
    return true;
3843
331k
}
3844
3845
static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)
3846
181k
{
3847
181k
    if (block.m_checked_merkle_root) return true;
3848
3849
128k
    bool mutated;
3850
128k
    uint256 merkle_root = BlockMerkleRoot(block, &mutated);
3851
128k
    if (block.hashMerkleRoot != merkle_root) {
3852
16
        return state.Invalid(
3853
16
            /*result=*/BlockValidationResult::BLOCK_MUTATED,
3854
16
            /*reject_reason=*/"bad-txnmrklroot",
3855
16
            /*debug_message=*/"hashMerkleRoot mismatch");
3856
16
    }
3857
3858
    // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3859
    // of transactions in a block without affecting the merkle root of a block,
3860
    // while still invalidating it.
3861
128k
    if (mutated) {
3862
146
        return state.Invalid(
3863
146
            /*result=*/BlockValidationResult::BLOCK_MUTATED,
3864
146
            /*reject_reason=*/"bad-txns-duplicate",
3865
146
            /*debug_message=*/"duplicate transaction");
3866
146
    }
3867
3868
128k
    block.m_checked_merkle_root = true;
3869
128k
    return true;
3870
128k
}
3871
3872
/** CheckWitnessMalleation performs checks for block malleation with regard to
3873
 * its witnesses.
3874
 *
3875
 * Note: If the witness commitment is expected (i.e. `expect_witness_commitment
3876
 * = true`), then the block is required to have at least one transaction and the
3877
 * first transaction needs to have at least one input. */
3878
static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state)
3879
201k
{
3880
201k
    if (expect_witness_commitment) {
3881
196k
        if (block.m_checked_witness_commitment) return true;
3882
3883
112k
        int commitpos = GetWitnessCommitmentIndex(block);
3884
112k
        if (commitpos != NO_WITNESS_COMMITMENT) {
3885
91.0k
            assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());
3886
91.0k
            const auto& witness_stack{block.vtx[0]->vin[0].scriptWitness.stack};
3887
3888
91.0k
            if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {
3889
9
                return state.Invalid(
3890
9
                    /*result=*/BlockValidationResult::BLOCK_MUTATED,
3891
9
                    /*reject_reason=*/"bad-witness-nonce-size",
3892
9
                    /*debug_message=*/strprintf("%s : invalid witness reserved value size", __func__));
3893
9
            }
3894
3895
            // The malleation check is ignored; as the transaction tree itself
3896
            // already does not permit it, it is impossible to trigger in the
3897
            // witness tree.
3898
91.0k
            uint256 hash_witness = BlockWitnessMerkleRoot(block);
3899
3900
91.0k
            CHash256().Write(hash_witness).Write(witness_stack[0]).Finalize(hash_witness);
3901
91.0k
            if (memcmp(hash_witness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3902
5
                return state.Invalid(
3903
5
                    /*result=*/BlockValidationResult::BLOCK_MUTATED,
3904
5
                    /*reject_reason=*/"bad-witness-merkle-match",
3905
5
                    /*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__));
3906
5
            }
3907
3908
91.0k
            block.m_checked_witness_commitment = true;
3909
91.0k
            return true;
3910
91.0k
        }
3911
112k
    }
3912
3913
    // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3914
68.4k
    for (const auto& tx : block.vtx) {
3915
68.4k
        if (tx->HasWitness()) {
3916
6
            return state.Invalid(
3917
6
                /*result=*/BlockValidationResult::BLOCK_MUTATED,
3918
6
                /*reject_reason=*/"unexpected-witness",
3919
6
                /*debug_message=*/strprintf("%s : unexpected witness data found", __func__));
3920
6
        }
3921
68.4k
    }
3922
3923
26.6k
    return true;
3924
26.6k
}
3925
3926
bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
3927
420k
{
3928
    // These are checks that are independent of context.
3929
3930
420k
    if (block.fChecked)
3931
204k
        return true;
3932
3933
    // Check that the header is valid (particularly PoW).  This is mostly
3934
    // redundant with the call in AcceptBlockHeader.
3935
215k
    if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3936
5
        return false;
3937
3938
    // Signet only: check block solution
3939
215k
    if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
3940
1
        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
3941
1
    }
3942
3943
    // Check the merkle root.
3944
215k
    if (fCheckMerkleRoot && !CheckMerkleRoot(block, state)) {
3945
8
        return false;
3946
8
    }
3947
3948
    // All potential-corruption validation must be done before we do any
3949
    // transaction validation, as otherwise we may mark the header as invalid
3950
    // because we receive the wrong transactions for it.
3951
    // Note that witness malleability is checked in ContextualCheckBlock, so no
3952
    // checks that use witness data may be performed here.
3953
3954
    // Size limits
3955
215k
    if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(TX_NO_WITNESS(block)) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
3956
4
        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
3957
3958
    // First transaction must be coinbase, the rest must not be
3959
215k
    if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3960
3
        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
3961
299k
    for (unsigned int i = 1; i < block.vtx.size(); i++)
3962
84.1k
        if (block.vtx[i]->IsCoinBase())
3963
2
            return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
3964
3965
    // Check transactions
3966
    // Must check for duplicate inputs (see CVE-2018-17144)
3967
299k
    for (const auto& tx : block.vtx) {
3968
299k
        TxValidationState tx_state;
3969
299k
        if (!CheckTransaction(*tx, tx_state)) {
3970
            // CheckBlock() does context-free validation checks. The only
3971
            // possible failures are consensus failures.
3972
296
            assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);
3973
296
            return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),
3974
296
                                 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
3975
296
        }
3976
299k
    }
3977
    // This underestimates the number of sigops, because unlike ConnectBlock it
3978
    // does not count witness and p2sh sigops.
3979
215k
    unsigned int nSigOps = 0;
3980
215k
    for (const auto& tx : block.vtx)
3981
299k
    {
3982
299k
        nSigOps += GetLegacySigOpCount(*tx);
3983
299k
    }
3984
215k
    if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
3985
8
        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
3986
3987
215k
    if (fCheckPOW && fCheckMerkleRoot)
3988
127k
        block.fChecked = true;
3989
3990
215k
    return true;
3991
215k
}
3992
3993
void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const
3994
60.4k
{
3995
60.4k
    int commitpos = GetWitnessCommitmentIndex(block);
3996
60.4k
    static const std::vector<unsigned char> nonce(32, 0x00);
3997
60.4k
    if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
3998
44.2k
        CMutableTransaction tx(*block.vtx[0]);
3999
44.2k
        tx.vin[0].scriptWitness.stack.resize(1);
4000
44.2k
        tx.vin[0].scriptWitness.stack[0] = nonce;
4001
44.2k
        block.vtx[0] = MakeTransactionRef(std::move(tx));
4002
44.2k
    }
4003
60.4k
}
4004
4005
void ChainstateManager::GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const
4006
53.2k
{
4007
53.2k
    int commitpos = GetWitnessCommitmentIndex(block);
4008
53.2k
    std::vector<unsigned char> ret(32, 0x00);
4009
53.2k
    if (commitpos == NO_WITNESS_COMMITMENT) {
4010
53.2k
        uint256 witnessroot = BlockWitnessMerkleRoot(block);
4011
53.2k
        CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
4012
53.2k
        CTxOut out;
4013
53.2k
        out.nValue = 0;
4014
53.2k
        out.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
4015
53.2k
        out.scriptPubKey[0] = OP_RETURN;
4016
53.2k
        out.scriptPubKey[1] = 0x24;
4017
53.2k
        out.scriptPubKey[2] = 0xaa;
4018
53.2k
        out.scriptPubKey[3] = 0x21;
4019
53.2k
        out.scriptPubKey[4] = 0xa9;
4020
53.2k
        out.scriptPubKey[5] = 0xed;
4021
53.2k
        memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
4022
53.2k
        CMutableTransaction tx(*block.vtx[0]);
4023
53.2k
        tx.vout.push_back(out);
4024
53.2k
        block.vtx[0] = MakeTransactionRef(std::move(tx));
4025
53.2k
    }
4026
53.2k
    UpdateUncommittedBlockStructures(block, pindexPrev);
4027
53.2k
}
4028
4029
bool HasValidProofOfWork(std::span<const CBlockHeader> headers, const Consensus::Params& consensusParams)
4030
7.23k
{
4031
7.23k
    return std::ranges::all_of(headers,
4032
456k
                               [&](const auto& header) { return CheckProofOfWork(header.GetHash(), header.nBits, consensusParams); });
4033
7.23k
}
4034
4035
bool IsBlockMutated(const CBlock& block, bool check_witness_root)
4036
53.0k
{
4037
53.0k
    BlockValidationState state;
4038
53.0k
    if (!CheckMerkleRoot(block, state)) {
4039
154
        LogDebug(BCLog::VALIDATION, "Block mutated: %s\n", state.ToString());
4040
154
        return true;
4041
154
    }
4042
4043
52.8k
    if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
4044
        // Consider the block mutated if any transaction is 64 bytes in size (see 3.1
4045
        // in "Weaknesses in Bitcoin’s Merkle Root Construction":
4046
        // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20190225/a27d8837/attachment-0001.pdf).
4047
        //
4048
        // Note: This is not a consensus change as this only applies to blocks that
4049
        // don't have a coinbase transaction and would therefore already be invalid.
4050
5
        return std::any_of(block.vtx.begin(), block.vtx.end(),
4051
5
                           [](auto& tx) { return GetSerializeSize(TX_NO_WITNESS(tx)) == 64; });
4052
52.8k
    } else {
4053
        // Theoretically it is still possible for a block with a 64 byte
4054
        // coinbase transaction to be mutated but we neglect that possibility
4055
        // here as it requires at least 224 bits of work.
4056
52.8k
    }
4057
4058
52.8k
    if (!CheckWitnessMalleation(block, check_witness_root, state)) {
4059
12
        LogDebug(BCLog::VALIDATION, "Block mutated: %s\n", state.ToString());
4060
12
        return true;
4061
12
    }
4062
4063
52.8k
    return false;
4064
52.8k
}
4065
4066
arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers)
4067
1.57k
{
4068
1.57k
    arith_uint256 total_work{0};
4069
399k
    for (const CBlockHeader& header : headers) {
4070
399k
        total_work += GetBlockProof(header);
4071
399k
    }
4072
1.57k
    return total_work;
4073
1.57k
}
4074
4075
/** Context-dependent validity checks.
4076
 *  By "context", we mean only the previous block headers, but not the UTXO
4077
 *  set; UTXO-related validity checks are done in ConnectBlock().
4078
 *  NOTE: This function is not currently invoked by ConnectBlock(), so we
4079
 *  should consider upgrade issues if we change which consensus rules are
4080
 *  enforced in this function (eg by adding a new consensus rule). See comment
4081
 *  in ConnectBlock().
4082
 *  Note that -reindex-chainstate skips the validation that happens here!
4083
 *
4084
 *  NOTE: failing to check the header's height against the last checkpoint's opened a DoS vector between
4085
 *  v0.12 and v0.15 (when no additional protection was in place) whereby an attacker could unboundedly
4086
 *  grow our in-memory block index. See https://bitcoincore.org/en/2024/07/03/disclose-header-spam.
4087
 */
4088
static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
4089
159k
{
4090
159k
    AssertLockHeld(::cs_main);
4091
159k
    assert(pindexPrev != nullptr);
4092
159k
    const int nHeight = pindexPrev->nHeight + 1;
4093
4094
    // Check proof of work
4095
159k
    const Consensus::Params& consensusParams = chainman.GetConsensus();
4096
159k
    if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
4097
4
        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
4098
4099
    // Check timestamp against prev
4100
159k
    if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
4101
5
        return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
4102
4103
    // Testnet4 and regtest only: Check timestamp against prev for difficulty-adjustment
4104
    // blocks to prevent timewarp attacks (see https://github.com/bitcoin/bitcoin/pull/15482).
4105
159k
    if (consensusParams.enforce_BIP94) {
4106
        // Check timestamp for the first block of each difficulty adjustment
4107
        // interval, except the genesis block.
4108
509
        if (nHeight % consensusParams.DifficultyAdjustmentInterval() == 0) {
4109
9
            if (block.GetBlockTime() < pindexPrev->GetBlockTime() - MAX_TIMEWARP) {
4110
2
                return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-timewarp-attack", "block's timestamp is too early on diff adjustment block");
4111
2
            }
4112
9
        }
4113
509
    }
4114
4115
    // Check timestamp
4116
159k
    if (block.Time() > NodeClock::now() + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4117
13
        return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
4118
13
    }
4119
4120
    // Reject blocks with outdated version
4121
159k
    if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
4122
159k
        (block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_DERSIG)) ||
4123
159k
        (block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CLTV))) {
4124
6
            return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
4125
6
                                 strprintf("rejected nVersion=0x%08x block", block.nVersion));
4126
6
    }
4127
4128
159k
    return true;
4129
159k
}
4130
4131
/** NOTE: This function is not currently invoked by ConnectBlock(), so we
4132
 *  should consider upgrade issues if we change which consensus rules are
4133
 *  enforced in this function (eg by adding a new consensus rule). See comment
4134
 *  in ConnectBlock().
4135
 *  Note that -reindex-chainstate skips the validation that happens here!
4136
 */
4137
static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const ChainstateManager& chainman, const CBlockIndex* pindexPrev)
4138
148k
{
4139
148k
    const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
4140
4141
    // Enforce BIP113 (Median Time Past).
4142
148k
    bool enforce_locktime_median_time_past{false};
4143
148k
    if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_CSV)) {
4144
144k
        assert(pindexPrev != nullptr);
4145
144k
        enforce_locktime_median_time_past = true;
4146
144k
    }
4147
4148
148k
    const int64_t nLockTimeCutoff{enforce_locktime_median_time_past ?
4149
144k
                                      pindexPrev->GetMedianTimePast() :
4150
148k
                                      block.GetBlockTime()};
4151
4152
    // Check that all transactions are finalized
4153
211k
    for (const auto& tx : block.vtx) {
4154
211k
        if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
4155
8
            return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
4156
8
        }
4157
211k
    }
4158
4159
    // Enforce rule that the coinbase starts with serialized block height
4160
148k
    if (DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_HEIGHTINCB))
4161
146k
    {
4162
146k
        CScript expect = CScript() << nHeight;
4163
146k
        if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
4164
146k
            !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
4165
1
            return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
4166
1
        }
4167
146k
    }
4168
4169
    // Validation for witness commitments.
4170
    // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
4171
    //   coinbase (where 0x0000....0000 is used instead).
4172
    // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
4173
    // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
4174
    // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
4175
    //   {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
4176
    //   multiple, the last one is used.
4177
148k
    if (!CheckWitnessMalleation(block, DeploymentActiveAfter(pindexPrev, chainman, Consensus::DEPLOYMENT_SEGWIT), state)) {
4178
8
        return false;
4179
8
    }
4180
4181
    // After the coinbase witness reserved value and commitment are verified,
4182
    // we can check if the block weight passes (before we've checked the
4183
    // coinbase witness, it would be possible for the weight to be too
4184
    // large by filling up the coinbase witness, which doesn't change
4185
    // the block hash, so we couldn't mark the block as permanently
4186
    // failed).
4187
148k
    if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
4188
1
        return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
4189
1
    }
4190
4191
148k
    return true;
4192
148k
}
4193
4194
bool ChainstateManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, CBlockIndex** ppindex, bool min_pow_checked)
4195
222k
{
4196
222k
    AssertLockHeld(cs_main);
4197
4198
    // Check for duplicate
4199
222k
    uint256 hash = block.GetHash();
4200
222k
    BlockMap::iterator miSelf{m_blockman.m_block_index.find(hash)};
4201
222k
    if (hash != GetConsensus().hashGenesisBlock) {
4202
222k
        if (miSelf != m_blockman.m_block_index.end()) {
4203
            // Block header is already known.
4204
106k
            CBlockIndex* pindex = &(miSelf->second);
4205
106k
            if (ppindex)
4206
106k
                *ppindex = pindex;
4207
106k
            if (pindex->nStatus & BLOCK_FAILED_VALID) {
4208
160
                LogDebug(BCLog::VALIDATION, "%s: block %s is marked invalid\n", __func__, hash.ToString());
4209
160
                return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate-invalid",
4210
160
                                     strprintf("block %s was previously marked invalid", hash.ToString()));
4211
160
            }
4212
106k
            return true;
4213
106k
        }
4214
4215
115k
        if (!CheckBlockHeader(block, state, GetConsensus())) {
4216
0
            LogDebug(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
4217
0
            return false;
4218
0
        }
4219
4220
        // Get prev block index
4221
115k
        CBlockIndex* pindexPrev = nullptr;
4222
115k
        BlockMap::iterator mi{m_blockman.m_block_index.find(block.hashPrevBlock)};
4223
115k
        if (mi == m_blockman.m_block_index.end()) {
4224
3
            LogDebug(BCLog::VALIDATION, "header %s has prev block not found: %s\n", hash.ToString(), block.hashPrevBlock.ToString());
4225
3
            return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
4226
3
        }
4227
115k
        pindexPrev = &((*mi).second);
4228
115k
        if (pindexPrev->nStatus & BLOCK_FAILED_VALID) {
4229
5
            LogDebug(BCLog::VALIDATION, "header %s has prev block invalid: %s\n", hash.ToString(), block.hashPrevBlock.ToString());
4230
5
            return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
4231
5
        }
4232
115k
        if (!ContextualCheckBlockHeader(block, state, *this, pindexPrev)) {
4233
25
            LogDebug(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
4234
25
            return false;
4235
25
        }
4236
115k
    }
4237
115k
    if (!min_pow_checked) {
4238
1
        LogDebug(BCLog::VALIDATION, "%s: not adding new block header %s, missing anti-dos proof-of-work validation\n", __func__, hash.ToString());
4239
1
        return state.Invalid(BlockValidationResult::BLOCK_HEADER_LOW_WORK, "too-little-chainwork");
4240
1
    }
4241
115k
    CBlockIndex* pindex{m_blockman.AddToBlockIndex(block, m_best_header)};
4242
4243
115k
    if (ppindex)
4244
115k
        *ppindex = pindex;
4245
4246
115k
    return true;
4247
115k
}
4248
4249
// Exposed wrapper for AcceptBlockHeader
4250
bool ChainstateManager::ProcessNewBlockHeaders(std::span<const CBlockHeader> headers, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex)
4251
31.1k
{
4252
31.1k
    AssertLockNotHeld(cs_main);
4253
31.1k
    {
4254
31.1k
        LOCK(cs_main);
4255
107k
        for (const CBlockHeader& header : headers) {
4256
107k
            CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
4257
107k
            bool accepted{AcceptBlockHeader(header, state, &pindex, min_pow_checked)};
4258
107k
            CheckBlockIndex();
4259
4260
107k
            if (!accepted) {
4261
17
                return false;
4262
17
            }
4263
107k
            if (ppindex) {
4264
104k
                *ppindex = pindex;
4265
104k
            }
4266
107k
        }
4267
31.1k
    }
4268
31.0k
    if (NotifyHeaderTip()) {
4269
22.3k
        if (IsInitialBlockDownload() && ppindex && *ppindex) {
4270
963
            const CBlockIndex& last_accepted{**ppindex};
4271
963
            int64_t blocks_left{(NodeClock::now() - last_accepted.Time()) / GetConsensus().PowTargetSpacing()};
4272
963
            blocks_left = std::max<int64_t>(0, blocks_left);
4273
963
            const double progress{100.0 * last_accepted.nHeight / (last_accepted.nHeight + blocks_left)};
4274
963
            LogInfo("Synchronizing blockheaders, height: %d (~%.2f%%)\n", last_accepted.nHeight, progress);
4275
963
        }
4276
22.3k
    }
4277
31.0k
    return true;
4278
31.1k
}
4279
4280
void ChainstateManager::ReportHeadersPresync(int64_t height, int64_t timestamp)
4281
6
{
4282
6
    AssertLockNotHeld(GetMutex());
4283
6
    {
4284
6
        LOCK(GetMutex());
4285
        // Don't report headers presync progress if we already have a post-minchainwork header chain.
4286
        // This means we lose reporting for potentially legitimate, but unlikely, deep reorgs, but
4287
        // prevent attackers that spam low-work headers from filling our logs.
4288
6
        if (m_best_header->nChainWork >= UintToArith256(GetConsensus().nMinimumChainWork)) return;
4289
        // Rate limit headers presync updates to 4 per second, as these are not subject to DoS
4290
        // protection.
4291
0
        auto now = MockableSteadyClock::now();
4292
0
        if (now < m_last_presync_update + std::chrono::milliseconds{250}) return;
4293
0
        m_last_presync_update = now;
4294
0
    }
4295
0
    bool initial_download = IsInitialBlockDownload();
4296
0
    GetNotifications().headerTip(GetSynchronizationState(initial_download, m_blockman.m_blockfiles_indexed), height, timestamp, /*presync=*/true);
4297
0
    if (initial_download) {
4298
0
        int64_t blocks_left{(NodeClock::now() - NodeSeconds{std::chrono::seconds{timestamp}}) / GetConsensus().PowTargetSpacing()};
4299
0
        blocks_left = std::max<int64_t>(0, blocks_left);
4300
0
        const double progress{100.0 * height / (height + blocks_left)};
4301
0
        LogInfo("Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n", height, progress);
4302
0
    }
4303
0
}
4304
4305
/** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
4306
bool ChainstateManager::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked)
4307
115k
{
4308
115k
    const CBlock& block = *pblock;
4309
4310
115k
    if (fNewBlock) *fNewBlock = false;
4311
115k
    AssertLockHeld(cs_main);
4312
4313
115k
    CBlockIndex *pindexDummy = nullptr;
4314
115k
    CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
4315
4316
115k
    bool accepted_header{AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4317
115k
    CheckBlockIndex();
4318
4319
115k
    if (!accepted_header)
4320
177
        return false;
4321
4322
    // Check all requested blocks that we do not already have for validity and
4323
    // save them to disk. Skip processing of unrequested blocks as an anti-DoS
4324
    // measure, unless the blocks have more work than the active chain tip, and
4325
    // aren't too far ahead of it, so are likely to be attached soon.
4326
115k
    bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
4327
115k
    bool fHasMoreOrSameWork = (ActiveTip() ? pindex->nChainWork >= ActiveTip()->nChainWork : true);
4328
    // Blocks that are too out-of-order needlessly limit the effectiveness of
4329
    // pruning, because pruning will not delete block files that contain any
4330
    // blocks which are too close in height to the tip.  Apply this test
4331
    // regardless of whether pruning is enabled; it should generally be safe to
4332
    // not process unrequested blocks.
4333
115k
    bool fTooFarAhead{pindex->nHeight > ActiveHeight() + int(MIN_BLOCKS_TO_KEEP)};
4334
4335
    // TODO: Decouple this function from the block download logic by removing fRequested
4336
    // This requires some new chain data structure to efficiently look up if a
4337
    // block is in a chain leading to a candidate for best tip, despite not
4338
    // being such a candidate itself.
4339
    // Note that this would break the getblockfrompeer RPC
4340
4341
    // TODO: deal better with return value and error conditions for duplicate
4342
    // and unrequested blocks.
4343
115k
    if (fAlreadyHave) return true;
4344
104k
    if (!fRequested) {  // If we didn't ask for it:
4345
730
        if (pindex->nTx != 0) return true;    // This is a previously-processed block that was pruned
4346
730
        if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
4347
723
        if (fTooFarAhead) return true;        // Block height is too high
4348
4349
        // Protect against DoS attacks from low-work chains.
4350
        // If our tip is behind, a peer could try to send us
4351
        // low-work blocks on a fake chain that we would never
4352
        // request; don't process these.
4353
722
        if (pindex->nChainWork < MinimumChainWork()) return true;
4354
722
    }
4355
4356
104k
    const CChainParams& params{GetParams()};
4357
4358
104k
    if (!CheckBlock(block, state, params.GetConsensus()) ||
4359
104k
        !ContextualCheckBlock(block, state, *this, pindex->pprev)) {
4360
17
        if (Assume(state.IsInvalid())) {
4361
17
            ActiveChainstate().InvalidBlockFound(pindex, state);
4362
17
        }
4363
17
        LogError("%s: %s\n", __func__, state.ToString());
4364
17
        return false;
4365
17
    }
4366
4367
    // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
4368
    // (but if it does not build on our best tip, let the SendMessages loop relay it)
4369
104k
    if (!IsInitialBlockDownload() && ActiveTip() == pindex->pprev && m_options.signals) {
4370
80.5k
        m_options.signals->NewPoWValidBlock(pindex, pblock);
4371
80.5k
    }
4372
4373
    // Write block to history file
4374
104k
    if (fNewBlock) *fNewBlock = true;
4375
104k
    try {
4376
104k
        FlatFilePos blockPos{};
4377
104k
        if (dbp) {
4378
2.05k
            blockPos = *dbp;
4379
2.05k
            m_blockman.UpdateBlockInfo(block, pindex->nHeight, blockPos);
4380
102k
        } else {
4381
102k
            blockPos = m_blockman.WriteBlock(block, pindex->nHeight);
4382
102k
            if (blockPos.IsNull()) {
4383
0
                state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
4384
0
                return false;
4385
0
            }
4386
102k
        }
4387
104k
        ReceivedBlockTransactions(block, pindex, blockPos);
4388
104k
    } catch (const std::runtime_error& e) {
4389
0
        return FatalError(GetNotifications(), state, strprintf(_("System error while saving block to disk: %s"), e.what()));
4390
0
    }
4391
4392
    // TODO: FlushStateToDisk() handles flushing of both block and chainstate
4393
    // data, so we should move this to ChainstateManager so that we can be more
4394
    // intelligent about how we flush.
4395
    // For now, since FlushStateMode::NONE is used, all that can happen is that
4396
    // the block files may be pruned, so we can just call this on one
4397
    // chainstate (particularly if we haven't implemented pruning with
4398
    // background validation yet).
4399
    //
4400
    // Flush errors (e.g. low disk space during pruning) are ignored, so that
4401
    // callers can't mistreat a flush failure as a block validation failure.
4402
    // The fatal error notification inside FlushStateToDisk still fires,
4403
    // so the node will shut down on unrecoverable flush errors regardless.
4404
    // For state a dummy value is used, and the return value is ignored.
4405
104k
    BlockValidationState flush_state_ignore;
4406
104k
    (void)ActiveChainstate().FlushStateToDisk(flush_state_ignore, FlushStateMode::NONE);
4407
4408
104k
    CheckBlockIndex();
4409
4410
104k
    return true;
4411
104k
}
4412
4413
bool ChainstateManager::ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block)
4414
113k
{
4415
113k
    AssertLockNotHeld(cs_main);
4416
4417
113k
    {
4418
113k
        CBlockIndex *pindex = nullptr;
4419
113k
        if (new_block) *new_block = false;
4420
113k
        BlockValidationState state;
4421
4422
        // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
4423
        // Therefore, the following critical section must include the CheckBlock() call as well.
4424
113k
        LOCK(cs_main);
4425
4426
        // Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
4427
        // CheckBlock() fails.  This is protective against consensus failure if there are any unknown forms of block
4428
        // malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
4429
        // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html.  Because CheckBlock() is
4430
        // not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
4431
113k
        bool ret = CheckBlock(*block, state, GetConsensus());
4432
113k
        if (ret) {
4433
            // Store to disk
4434
113k
            ret = AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block, min_pow_checked);
4435
113k
        }
4436
113k
        if (!ret) {
4437
509
            if (m_options.signals) {
4438
509
                m_options.signals->BlockChecked(block, state);
4439
509
            }
4440
509
            LogError("%s: AcceptBlock FAILED (%s)\n", __func__, state.ToString());
4441
509
            return false;
4442
509
        }
4443
113k
    }
4444
4445
113k
    NotifyHeaderTip();
4446
4447
113k
    BlockValidationState state; // Only used to report errors, not invalidity - ignore it
4448
113k
    if (!ActiveChainstate().ActivateBestChain(state, block)) {
4449
1
        LogError("%s: ActivateBestChain failed (%s)\n", __func__, state.ToString());
4450
1
        return false;
4451
1
    }
4452
4453
113k
    Chainstate* bg_chain{WITH_LOCK(cs_main, return HistoricalChainstate())};
4454
113k
    BlockValidationState bg_state;
4455
113k
    if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
4456
0
        LogError("%s: [background] ActivateBestChain failed (%s)\n", __func__, bg_state.ToString());
4457
0
        return false;
4458
0
     }
4459
4460
113k
    return true;
4461
113k
}
4462
4463
MempoolAcceptResult ChainstateManager::ProcessTransaction(const CTransactionRef& tx, bool test_accept)
4464
47.6k
{
4465
47.6k
    AssertLockHeld(cs_main);
4466
47.6k
    Chainstate& active_chainstate = ActiveChainstate();
4467
47.6k
    if (!active_chainstate.GetMempool()) {
4468
0
        TxValidationState state;
4469
0
        state.Invalid(TxValidationResult::TX_NO_MEMPOOL, "no-mempool");
4470
0
        return MempoolAcceptResult::Failure(state);
4471
0
    }
4472
47.6k
    auto result = AcceptToMemoryPool(active_chainstate, tx, GetTime(), /*bypass_limits=*/ false, test_accept);
4473
47.6k
    active_chainstate.GetMempool()->check(active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
4474
47.6k
    return result;
4475
47.6k
}
4476
4477
4478
BlockValidationState TestBlockValidity(
4479
    Chainstate& chainstate,
4480
    const CBlock& block,
4481
    const bool check_pow,
4482
    const bool check_merkle_root)
4483
43.9k
{
4484
    // Lock must be held throughout this function for two reasons:
4485
    // 1. We don't want the tip to change during several of the validation steps
4486
    // 2. To prevent a CheckBlock() race condition for fChecked, see ProcessNewBlock()
4487
43.9k
    AssertLockHeld(chainstate.m_chainman.GetMutex());
4488
4489
43.9k
    BlockValidationState state;
4490
43.9k
    CBlockIndex* tip{Assert(chainstate.m_chain.Tip())};
4491
4492
43.9k
    if (block.hashPrevBlock != *Assert(tip->phashBlock)) {
4493
2
        state.Invalid({}, "inconclusive-not-best-prevblk");
4494
2
        return state;
4495
2
    }
4496
4497
    // For signets CheckBlock() verifies the challenge iff fCheckPow is set.
4498
43.9k
    if (!CheckBlock(block, state, chainstate.m_chainman.GetConsensus(), /*fCheckPow=*/check_pow, /*fCheckMerkleRoot=*/check_merkle_root)) {
4499
        // This should never happen, but belt-and-suspenders don't approve the
4500
        // block if it does.
4501
8
        if (state.IsValid()) NONFATAL_UNREACHABLE();
4502
8
        return state;
4503
8
    }
4504
4505
    /**
4506
     * At this point ProcessNewBlock would call AcceptBlock(), but we
4507
     * don't want to store the block or its header. Run individual checks
4508
     * instead:
4509
     * - skip AcceptBlockHeader() because:
4510
     *   - we don't want to update the block index
4511
     *   - we do not care about duplicates
4512
     *   - we already ran CheckBlockHeader() via CheckBlock()
4513
     *   - we already checked for prev-blk-not-found
4514
     *   - we know the tip is valid, so no need to check bad-prevblk
4515
     * - we already ran CheckBlock()
4516
     * - do run ContextualCheckBlockHeader()
4517
     * - do run ContextualCheckBlock()
4518
     */
4519
4520
43.9k
    if (!ContextualCheckBlockHeader(block, state, chainstate.m_chainman, tip)) {
4521
5
        if (state.IsValid()) NONFATAL_UNREACHABLE();
4522
5
        return state;
4523
5
    }
4524
4525
43.9k
    if (!ContextualCheckBlock(block, state, chainstate.m_chainman, tip)) {
4526
1
        if (state.IsValid()) NONFATAL_UNREACHABLE();
4527
1
        return state;
4528
1
    }
4529
4530
    // We don't want ConnectBlock to update the actual chainstate, so create
4531
    // a cache on top of it, along with a dummy block index.
4532
43.9k
    CBlockIndex index_dummy{block};
4533
43.9k
    uint256 block_hash(block.GetHash());
4534
43.9k
    index_dummy.pprev = tip;
4535
43.9k
    index_dummy.nHeight = tip->nHeight + 1;
4536
43.9k
    index_dummy.phashBlock = &block_hash;
4537
43.9k
    CCoinsViewCache view_dummy(&chainstate.CoinsTip());
4538
4539
    // Set fJustCheck to true in order to update, and not clear, validation caches.
4540
43.9k
    if(!chainstate.ConnectBlock(block, state, &index_dummy, view_dummy, /*fJustCheck=*/true)) {
4541
308
        if (state.IsValid()) NONFATAL_UNREACHABLE();
4542
308
        return state;
4543
308
    }
4544
4545
    // Ensure no check returned successfully while also setting an invalid state.
4546
43.6k
    if (!state.IsValid()) NONFATAL_UNREACHABLE();
4547
4548
43.6k
    return state;
4549
43.6k
}
4550
4551
/* This function is called from the RPC code for pruneblockchain */
4552
void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight)
4553
11
{
4554
11
    BlockValidationState state;
4555
11
    if (!active_chainstate.FlushStateToDisk(
4556
11
            state, FlushStateMode::NONE, nManualPruneHeight)) {
4557
0
        LogWarning("Failed to flush state after manual prune (%s)", state.ToString());
4558
0
    }
4559
11
}
4560
4561
bool Chainstate::LoadChainTip()
4562
778
{
4563
778
    AssertLockHeld(cs_main);
4564
778
    const CCoinsViewCache& coins_cache = CoinsTip();
4565
778
    assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
4566
778
    CBlockIndex* tip = m_chain.Tip();
4567
4568
778
    if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
4569
0
        return true;
4570
0
    }
4571
4572
    // Load pointer to end of best chain
4573
778
    CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
4574
778
    if (!pindex) {
4575
2
        return false;
4576
2
    }
4577
776
    m_chain.SetTip(*pindex);
4578
776
    m_chainman.UpdateIBDStatus();
4579
776
    m_last_flushed_block = pindex;
4580
776
    tip = m_chain.Tip();
4581
4582
    // nSequenceId is one of the keys used to sort setBlockIndexCandidates. Ensure all
4583
    // candidate sets are empty to avoid UB, as nSequenceId is about to be modified.
4584
787
    for (const auto& cs : m_chainman.m_chainstates) {
4585
787
        assert(cs->setBlockIndexCandidates.empty());
4586
787
    }
4587
4588
    // Make sure our chain tip before shutting down scores better than any other candidate
4589
    // to maintain a consistent best tip over reboots in case of a tie.
4590
776
    auto target = tip;
4591
143k
    while (target) {
4592
142k
        target->nSequenceId = SEQ_ID_BEST_CHAIN_FROM_DISK;
4593
142k
        target = target->pprev;
4594
142k
    }
4595
4596
776
    LogInfo("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f",
4597
776
              tip->GetBlockHash().ToString(),
4598
776
              m_chain.Height(),
4599
776
              FormatISO8601DateTime(tip->GetBlockTime()),
4600
776
              m_chainman.GuessVerificationProgress(tip));
4601
4602
    // Ensure KernelNotifications m_tip_block is set even if no new block arrives.
4603
776
    if (!this->GetRole().historical) {
4604
        // Ignoring return value for now.
4605
771
        (void)m_chainman.GetNotifications().blockTip(
4606
771
            /*state=*/GetSynchronizationState(/*init=*/true, m_chainman.m_blockman.m_blockfiles_indexed),
4607
771
            /*index=*/*pindex,
4608
771
            /*verification_progress=*/m_chainman.GuessVerificationProgress(tip));
4609
771
    }
4610
4611
776
    CheckForkWarningConditions();
4612
4613
776
    return true;
4614
776
}
4615
4616
CVerifyDB::CVerifyDB(Notifications& notifications)
4617
768
    : m_notifications{notifications}
4618
768
{
4619
768
    m_notifications.progress(_("Verifying blocks…"), 0, false);
4620
768
}
4621
4622
CVerifyDB::~CVerifyDB()
4623
768
{
4624
768
    m_notifications.progress(bilingual_str{}, 100, false);
4625
768
}
4626
4627
VerifyDBResult CVerifyDB::VerifyDB(
4628
    Chainstate& chainstate,
4629
    const Consensus::Params& consensus_params,
4630
    CCoinsView& coinsview,
4631
    int nCheckLevel, int nCheckDepth)
4632
768
{
4633
768
    AssertLockHeld(cs_main);
4634
4635
768
    if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr) {
4636
129
        return VerifyDBResult::SUCCESS;
4637
129
    }
4638
4639
    // Verify blocks in the best chain
4640
639
    if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
4641
18
        nCheckDepth = chainstate.m_chain.Height();
4642
18
    }
4643
639
    nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4644
639
    LogInfo("Verifying last %i blocks at level %i", nCheckDepth, nCheckLevel);
4645
639
    CCoinsViewCache coins(&coinsview);
4646
639
    CBlockIndex* pindex;
4647
639
    CBlockIndex* pindexFailure = nullptr;
4648
639
    int nGoodTransactions = 0;
4649
639
    BlockValidationState state;
4650
639
    int reportDone = 0;
4651
639
    bool skipped_no_block_data{false};
4652
639
    bool skipped_l3_checks{false};
4653
639
    LogInfo("Verification progress: 0%%");
4654
4655
639
    const bool is_snapshot_cs{chainstate.m_from_snapshot_blockhash};
4656
4657
5.76k
    for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
4658
5.74k
        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4659
5.74k
        if (reportDone < percentageDone / 10) {
4660
            // report every 10% step
4661
3.74k
            LogInfo("Verification progress: %d%%", percentageDone);
4662
3.74k
            reportDone = percentageDone / 10;
4663
3.74k
        }
4664
5.74k
        m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
4665
5.74k
        if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
4666
616
            break;
4667
616
        }
4668
5.12k
        if ((chainstate.m_blockman.IsPruneMode() || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4669
            // If pruning or running under an assumeutxo snapshot, only go
4670
            // back as far as we have data.
4671
1
            LogInfo("Block verification stopping at height %d (no data). This could be due to pruning or use of an assumeutxo snapshot.", pindex->nHeight);
4672
1
            skipped_no_block_data = true;
4673
1
            break;
4674
1
        }
4675
5.12k
        CBlock block;
4676
        // check level 0: read from disk
4677
5.12k
        if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
4678
1
            LogError("Verification error: ReadBlock failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4679
1
            return VerifyDBResult::CORRUPTED_BLOCK_DB;
4680
1
        }
4681
        // check level 1: verify block validity
4682
5.12k
        if (nCheckLevel >= 1 && !CheckBlock(block, state, consensus_params)) {
4683
0
            LogError("Verification error: found bad block at %d, hash=%s (%s)",
4684
0
                      pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4685
0
            return VerifyDBResult::CORRUPTED_BLOCK_DB;
4686
0
        }
4687
        // check level 2: verify undo validity
4688
5.12k
        if (nCheckLevel >= 2 && pindex) {
4689
5.12k
            CBlockUndo undo;
4690
5.12k
            if (!pindex->GetUndoPos().IsNull()) {
4691
5.12k
                if (!chainstate.m_blockman.ReadBlockUndo(undo, *pindex)) {
4692
1
                    LogError("Verification error: found bad undo data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4693
1
                    return VerifyDBResult::CORRUPTED_BLOCK_DB;
4694
1
                }
4695
5.12k
            }
4696
5.12k
        }
4697
        // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4698
5.12k
        size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
4699
4700
5.12k
        if (nCheckLevel >= 3) {
4701
4.92k
            if (curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
4702
4.92k
                assert(coins.GetBestBlock() == pindex->GetBlockHash());
4703
4.92k
                DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
4704
4.92k
                if (res == DISCONNECT_FAILED) {
4705
0
                    LogError("Verification error: irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4706
0
                    return VerifyDBResult::CORRUPTED_BLOCK_DB;
4707
0
                }
4708
4.92k
                if (res == DISCONNECT_UNCLEAN) {
4709
0
                    nGoodTransactions = 0;
4710
0
                    pindexFailure = pindex;
4711
4.92k
                } else {
4712
4.92k
                    nGoodTransactions += block.vtx.size();
4713
4.92k
                }
4714
4.92k
            } else {
4715
0
                skipped_l3_checks = true;
4716
0
            }
4717
4.92k
        }
4718
5.12k
        if (chainstate.m_chainman.m_interrupt) return VerifyDBResult::INTERRUPTED;
4719
5.12k
    }
4720
635
    if (pindexFailure) {
4721
0
        LogError("Verification error: coin database inconsistencies found (last %i blocks, %i good transactions before that)", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4722
0
        return VerifyDBResult::CORRUPTED_BLOCK_DB;
4723
0
    }
4724
635
    if (skipped_l3_checks) {
4725
0
        LogWarning("Skipped verification of level >=3 (insufficient database cache size). Consider increasing -dbcache.");
4726
0
    }
4727
4728
    // store block count as we move pindex at check level >= 4
4729
635
    int block_count = chainstate.m_chain.Height() - pindex->nHeight;
4730
4731
    // check level 4: try reconnecting blocks
4732
635
    if (nCheckLevel >= 4 && !skipped_l3_checks) {
4733
604
        while (pindex != chainstate.m_chain.Tip()) {
4734
602
            const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
4735
602
            if (reportDone < percentageDone / 10) {
4736
                // report every 10% step
4737
10
                LogInfo("Verification progress: %d%%", percentageDone);
4738
10
                reportDone = percentageDone / 10;
4739
10
            }
4740
602
            m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
4741
602
            pindex = chainstate.m_chain.Next(*pindex);
4742
602
            CBlock block;
4743
602
            if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
4744
0
                LogError("Verification error: ReadBlock failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4745
0
                return VerifyDBResult::CORRUPTED_BLOCK_DB;
4746
0
            }
4747
602
            if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
4748
0
                LogError("Verification error: found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
4749
0
                return VerifyDBResult::CORRUPTED_BLOCK_DB;
4750
0
            }
4751
602
            if (chainstate.m_chainman.m_interrupt) return VerifyDBResult::INTERRUPTED;
4752
602
        }
4753
2
    }
4754
4755
635
    LogInfo("Verification: checked last %i blocks at level %i", block_count, nCheckLevel);
4756
635
    if (nCheckLevel >= 3 && !skipped_l3_checks) {
4757
634
        LogInfo("Verification: no coin database inconsistencies (%i transactions)", nGoodTransactions);
4758
634
    }
4759
4760
635
    if (skipped_l3_checks) {
4761
0
        return VerifyDBResult::SKIPPED_L3_CHECKS;
4762
0
    }
4763
635
    if (skipped_no_block_data) {
4764
1
        return VerifyDBResult::SKIPPED_MISSING_BLOCKS;
4765
1
    }
4766
634
    return VerifyDBResult::SUCCESS;
4767
635
}
4768
4769
/** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
4770
bool Chainstate::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs)
4771
0
{
4772
0
    AssertLockHeld(cs_main);
4773
    // TODO: merge with ConnectBlock
4774
0
    CBlock block;
4775
0
    if (!m_blockman.ReadBlock(block, *pindex)) {
4776
0
        LogError("ReplayBlock(): ReadBlock failed at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4777
0
        return false;
4778
0
    }
4779
4780
0
    for (const CTransactionRef& tx : block.vtx) {
4781
0
        if (!tx->IsCoinBase()) {
4782
0
            for (const CTxIn &txin : tx->vin) {
4783
0
                inputs.SpendCoin(txin.prevout);
4784
0
            }
4785
0
        }
4786
        // Pass check = true as every addition may be an overwrite.
4787
0
        AddCoins(inputs, *tx, pindex->nHeight, true);
4788
0
    }
4789
0
    return true;
4790
0
}
4791
4792
bool Chainstate::ReplayBlocks()
4793
1.27k
{
4794
1.27k
    LOCK(cs_main);
4795
4796
1.27k
    CCoinsView& db = this->CoinsDB();
4797
1.27k
    CCoinsViewCache cache(&db);
4798
4799
1.27k
    std::vector<uint256> hashHeads = db.GetHeadBlocks();
4800
1.27k
    if (hashHeads.empty()) return true; // We're already in a consistent state.
4801
0
    if (hashHeads.size() != 2) {
4802
0
        LogError("ReplayBlocks(): unknown inconsistent state\n");
4803
0
        return false;
4804
0
    }
4805
4806
0
    m_chainman.GetNotifications().progress(_("Replaying blocks…"), 0, false);
4807
0
    LogInfo("Replaying blocks");
4808
4809
0
    const CBlockIndex* pindexOld = nullptr;  // Old tip during the interrupted flush.
4810
0
    const CBlockIndex* pindexNew;            // New tip during the interrupted flush.
4811
0
    const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4812
4813
0
    if (!m_blockman.m_block_index.contains(hashHeads[0])) {
4814
0
        LogError("ReplayBlocks(): reorganization to unknown block requested\n");
4815
0
        return false;
4816
0
    }
4817
0
    pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
4818
4819
0
    if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4820
0
        if (!m_blockman.m_block_index.contains(hashHeads[1])) {
4821
0
            LogError("ReplayBlocks(): reorganization from unknown block requested\n");
4822
0
            return false;
4823
0
        }
4824
0
        pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
4825
0
        pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4826
0
        assert(pindexFork != nullptr);
4827
0
    }
4828
4829
    // Rollback along the old branch.
4830
0
    const int nForkHeight{pindexFork ? pindexFork->nHeight : 0};
4831
0
    if (pindexOld != pindexFork) {
4832
0
        LogInfo("Rolling back from %s (%i to %i)", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight, nForkHeight);
4833
0
        while (pindexOld != pindexFork) {
4834
0
            if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4835
0
                CBlock block;
4836
0
                if (!m_blockman.ReadBlock(block, *pindexOld)) {
4837
0
                    LogError("RollbackBlock(): ReadBlock() failed at %d, hash=%s\n", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4838
0
                    return false;
4839
0
                }
4840
0
                if (pindexOld->nHeight % 10'000 == 0) {
4841
0
                    LogInfo("Rolling back %s (%i)", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4842
0
                }
4843
0
                DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4844
0
                if (res == DISCONNECT_FAILED) {
4845
0
                    LogError("RollbackBlock(): DisconnectBlock failed at %d, hash=%s\n", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4846
0
                    return false;
4847
0
                }
4848
                // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4849
                // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4850
                // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4851
                // the result is still a version of the UTXO set with the effects of that block undone.
4852
0
            }
4853
0
            pindexOld = pindexOld->pprev;
4854
0
        }
4855
0
        LogInfo("Rolled back to %s", pindexFork->GetBlockHash().ToString());
4856
0
    }
4857
4858
    // Roll forward from the forking point to the new tip.
4859
0
    if (nForkHeight < pindexNew->nHeight) {
4860
0
        LogInfo("Rolling forward to %s (%i to %i)", pindexNew->GetBlockHash().ToString(), nForkHeight, pindexNew->nHeight);
4861
0
        for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4862
0
            const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};
4863
4864
0
            if (nHeight % 10'000 == 0) {
4865
0
                LogInfo("Rolling forward %s (%i)", pindex.GetBlockHash().ToString(), nHeight);
4866
0
            }
4867
0
            m_chainman.GetNotifications().progress(_("Replaying blocks…"), (int)((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)), false);
4868
0
            if (!RollforwardBlock(&pindex, cache)) return false;
4869
0
        }
4870
0
        LogInfo("Rolled forward to %s", pindexNew->GetBlockHash().ToString());
4871
0
    }
4872
4873
0
    cache.SetBestBlock(pindexNew->GetBlockHash());
4874
0
    cache.Flush(/*reallocate_cache=*/false); // local CCoinsViewCache goes out of scope
4875
0
    m_chainman.GetNotifications().progress(bilingual_str{}, 100, false);
4876
0
    return true;
4877
0
}
4878
4879
bool Chainstate::NeedsRedownload() const
4880
1.27k
{
4881
1.27k
    AssertLockHeld(cs_main);
4882
4883
    // At and above m_params.SegwitHeight, segwit consensus rules must be validated
4884
1.27k
    CBlockIndex* block{m_chain.Tip()};
4885
4886
143k
    while (block != nullptr && DeploymentActiveAt(*block, m_chainman, Consensus::DEPLOYMENT_SEGWIT)) {
4887
142k
        if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
4888
            // block is insufficiently validated for a segwit client
4889
1
            return true;
4890
1
        }
4891
142k
        block = block->pprev;
4892
142k
    }
4893
4894
1.27k
    return false;
4895
1.27k
}
4896
4897
void Chainstate::ClearBlockIndexCandidates()
4898
8
{
4899
8
    AssertLockHeld(::cs_main);
4900
8
    setBlockIndexCandidates.clear();
4901
8
}
4902
4903
void Chainstate::PopulateBlockIndexCandidates()
4904
1.29k
{
4905
1.29k
    AssertLockHeld(::cs_main);
4906
4907
150k
    for (CBlockIndex* pindex : m_blockman.GetAllBlockIndices()) {
4908
        // With assumeutxo, the snapshot block is a candidate for the tip, but it
4909
        // may not have BLOCK_VALID_TRANSACTIONS (e.g. if we haven't yet downloaded
4910
        // the block), so we special-case it here.
4911
150k
        if (pindex == SnapshotBase() ||
4912
150k
                (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
4913
150k
                 (pindex->HaveNumChainTxs() || pindex->pprev == nullptr))) {
4914
146k
            TryAddBlockIndexCandidate(pindex);
4915
146k
        }
4916
150k
    }
4917
1.29k
}
4918
4919
bool ChainstateManager::LoadBlockIndex()
4920
1.28k
{
4921
1.28k
    AssertLockHeld(cs_main);
4922
    // Load block index from databases
4923
1.28k
    if (m_blockman.m_blockfiles_indexed) {
4924
1.27k
        bool ret{m_blockman.LoadBlockIndexDB(CurrentChainstate().m_from_snapshot_blockhash)};
4925
1.27k
        if (!ret) return false;
4926
4927
1.26k
        m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
4928
4929
1.26k
        std::vector<CBlockIndex*> vSortedByHeight{m_blockman.GetAllBlockIndices()};
4930
1.26k
        std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
4931
1.26k
                  CBlockIndexHeightOnlyComparator());
4932
4933
144k
        for (CBlockIndex* pindex : vSortedByHeight) {
4934
144k
            if (m_interrupt) return false;
4935
144k
            if (pindex->nStatus & BLOCK_FAILED_VALID && (!m_best_invalid || pindex->nChainWork > m_best_invalid->nChainWork)) {
4936
63
                m_best_invalid = pindex;
4937
63
            }
4938
144k
            if (pindex->IsValid(BLOCK_VALID_TREE) && (m_best_header == nullptr || CBlockIndexWorkComparator()(m_best_header, pindex)))
4939
143k
                m_best_header = pindex;
4940
144k
        }
4941
1.26k
    }
4942
1.27k
    return true;
4943
1.28k
}
4944
4945
bool ChainstateManager::LoadGenesisBlock()
4946
1.27k
{
4947
1.27k
    LOCK(cs_main);
4948
4949
1.27k
    const CBlock& genesis_block{GetParams().GenesisBlock()};
4950
4951
    // Check whether we're already initialized by checking for genesis in
4952
    // m_blockman.m_block_index. Note that we can't use a chainstate's m_chain here, since it is
4953
    // set based on the coins db, not the block index db, which is the only
4954
    // thing loaded at this point.
4955
1.27k
    if (m_blockman.m_block_index.contains(genesis_block.GetHash())) {
4956
796
        return true;
4957
796
    }
4958
4959
479
    try {
4960
479
        FlatFilePos blockPos{m_blockman.WriteBlock(genesis_block, 0)};
4961
479
        if (blockPos.IsNull()) {
4962
0
            LogError("Writing genesis block to disk failed");
4963
0
            return false;
4964
0
        }
4965
479
        CBlockIndex* pindex{m_blockman.AddToBlockIndex(genesis_block, m_best_header)};
4966
479
        ReceivedBlockTransactions(genesis_block, pindex, blockPos);
4967
479
    } catch (const std::runtime_error& e) {
4968
0
        LogError("Failed to write genesis block: %s", e.what());
4969
0
        return false;
4970
0
    }
4971
4972
479
    return true;
4973
479
}
4974
4975
void ChainstateManager::LoadExternalBlockFile(
4976
    AutoFile& file_in,
4977
    FlatFilePos* dbp,
4978
    std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent)
4979
18
{
4980
    // Either both should be specified (-reindex), or neither (-loadblock).
4981
18
    assert(!dbp == !blocks_with_unknown_parent);
4982
4983
18
    const auto start{SteadyClock::now()};
4984
18
    const CChainParams& params{GetParams()};
4985
4986
18
    int nLoaded = 0;
4987
18
    try {
4988
18
        BufferedFile blkdat{file_in, 2 * MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE + 8};
4989
        // nRewind indicates where to resume scanning in case something goes wrong,
4990
        // such as a block fails to deserialize.
4991
18
        uint64_t nRewind = blkdat.GetPos();
4992
2.09M
        while (!blkdat.eof()) {
4993
2.09M
            if (m_interrupt) return;
4994
4995
2.09M
            blkdat.SetPos(nRewind);
4996
2.09M
            nRewind++; // start one byte further next time, in case of failure
4997
2.09M
            blkdat.SetLimit(); // remove former limit
4998
2.09M
            unsigned int nSize = 0;
4999
2.09M
            try {
5000
                // locate a header
5001
2.09M
                MessageStartChars buf;
5002
2.09M
                blkdat.FindByte(std::byte(params.MessageStart()[0]));
5003
2.09M
                nRewind = blkdat.GetPos() + 1;
5004
2.09M
                blkdat >> buf;
5005
2.09M
                if (buf != params.MessageStart()) {
5006
2.09M
                    continue;
5007
2.09M
                }
5008
                // read size
5009
2.17k
                blkdat >> nSize;
5010
2.17k
                if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
5011
0
                    continue;
5012
2.17k
            } catch (const std::exception&) {
5013
                // no valid block header found; don't complain
5014
                // (this happens at the end of every blk.dat file)
5015
14
                break;
5016
14
            }
5017
2.15k
            try {
5018
                // read block header
5019
2.15k
                const uint64_t nBlockPos{blkdat.GetPos()};
5020
2.15k
                if (dbp)
5021
2.05k
                    dbp->nPos = nBlockPos;
5022
2.15k
                blkdat.SetLimit(nBlockPos + nSize);
5023
2.15k
                CBlockHeader header;
5024
2.15k
                blkdat >> header;
5025
2.15k
                const uint256 hash{header.GetHash()};
5026
                // Skip the rest of this block (this may read from disk into memory); position to the marker before the
5027
                // next block, but it's still possible to rewind to the start of the current block (without a disk read).
5028
2.15k
                nRewind = nBlockPos + nSize;
5029
2.15k
                blkdat.SkipTo(nRewind);
5030
5031
2.15k
                std::shared_ptr<CBlock> pblock{}; // needs to remain available after the cs_main lock is released to avoid duplicate reads from disk
5032
5033
2.15k
                {
5034
2.15k
                    LOCK(cs_main);
5035
                    // detect out of order blocks, and store them for later
5036
2.15k
                    if (hash != params.GetConsensus().hashGenesisBlock && !m_blockman.LookupBlockIndex(header.hashPrevBlock)) {
5037
103
                        LogDebug(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
5038
103
                                 header.hashPrevBlock.ToString());
5039
103
                        if (dbp && blocks_with_unknown_parent) {
5040
103
                            blocks_with_unknown_parent->emplace(header.hashPrevBlock, *dbp);
5041
103
                        }
5042
103
                        continue;
5043
103
                    }
5044
5045
                    // process in case the block isn't known yet
5046
2.05k
                    const CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
5047
2.05k
                    if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
5048
                        // This block can be processed immediately; rewind to its start, read and deserialize it.
5049
2.05k
                        blkdat.SetPos(nBlockPos);
5050
2.05k
                        pblock = std::make_shared<CBlock>();
5051
2.05k
                        blkdat >> TX_WITH_WITNESS(*pblock);
5052
2.05k
                        nRewind = blkdat.GetPos();
5053
5054
2.05k
                        BlockValidationState state;
5055
2.05k
                        if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
5056
2.04k
                            nLoaded++;
5057
2.04k
                        }
5058
2.05k
                        if (state.IsError()) {
5059
0
                            break;
5060
0
                        }
5061
2.05k
                    } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
5062
0
                        LogDebug(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
5063
0
                    }
5064
2.05k
                }
5065
5066
                // Activate the genesis block so normal node progress can continue
5067
                // During first -reindex, this will only connect Genesis since
5068
                // ActivateBestChain only connects blocks which are in the block tree db,
5069
                // which only contains blocks whose parents are in it.
5070
                // But do this only if genesis isn't activated yet, to avoid connecting many blocks
5071
                // without assumevalid in the case of a continuation of a reindex that
5072
                // was interrupted by the user.
5073
2.05k
                if (hash == params.GetConsensus().hashGenesisBlock && WITH_LOCK(::cs_main, return ActiveHeight()) == -1) {
5074
14
                    BlockValidationState state;
5075
14
                    if (!ActiveChainstate().ActivateBestChain(state, nullptr)) {
5076
0
                        break;
5077
0
                    }
5078
14
                }
5079
5080
2.05k
                if (m_blockman.IsPruneMode() && m_blockman.m_blockfiles_indexed && pblock) {
5081
                    // must update the tip for pruning to work while importing with -loadblock.
5082
                    // this is a tradeoff to conserve disk space at the expense of time
5083
                    // spent updating the tip to be able to prune.
5084
                    // otherwise, ActivateBestChain won't be called by the import process
5085
                    // until after all of the block files are loaded. ActivateBestChain can be
5086
                    // called by concurrent network message processing. but, that is not
5087
                    // reliable for the purpose of pruning while importing.
5088
0
                    if (auto result{ActivateBestChains()}; !result) {
5089
0
                        LogDebug(BCLog::REINDEX, "%s\n", util::ErrorString(result).original);
5090
0
                        break;
5091
0
                    }
5092
0
                }
5093
5094
2.05k
                NotifyHeaderTip();
5095
5096
2.05k
                if (!blocks_with_unknown_parent) continue;
5097
5098
                // Recursively process earlier encountered successors of this block
5099
1.95k
                std::deque<uint256> queue;
5100
1.95k
                queue.push_back(hash);
5101
4.00k
                while (!queue.empty()) {
5102
2.05k
                    uint256 head = queue.front();
5103
2.05k
                    queue.pop_front();
5104
2.05k
                    auto range = blocks_with_unknown_parent->equal_range(head);
5105
2.15k
                    while (range.first != range.second) {
5106
103
                        std::multimap<uint256, FlatFilePos>::iterator it = range.first;
5107
103
                        std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
5108
103
                        if (m_blockman.ReadBlock(*pblockrecursive, it->second, {})) {
5109
103
                            const auto& block_hash{pblockrecursive->GetHash()};
5110
103
                            LogDebug(BCLog::REINDEX, "%s: Processing out of order child %s of %s", __func__, block_hash.ToString(), head.ToString());
5111
103
                            LOCK(cs_main);
5112
103
                            BlockValidationState dummy;
5113
103
                            if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr, true)) {
5114
103
                                nLoaded++;
5115
103
                                queue.push_back(block_hash);
5116
103
                            }
5117
103
                        }
5118
103
                        range.first++;
5119
103
                        blocks_with_unknown_parent->erase(it);
5120
103
                        NotifyHeaderTip();
5121
103
                    }
5122
2.05k
                }
5123
1.95k
            } catch (const std::exception& e) {
5124
                // historical bugs added extra data to the block files that does not deserialize cleanly.
5125
                // commonly this data is between readable blocks, but it does not really matter. such data is not fatal to the import process.
5126
                // the code that reads the block files deals with invalid data by simply ignoring it.
5127
                // it continues to search for the next {4 byte magic message start bytes + 4 byte length + block} that does deserialize cleanly
5128
                // and passes all of the other block validation checks dealing with POW and the merkle root, etc...
5129
                // we merely note with this informational log message when unexpected data is encountered.
5130
                // we could also be experiencing a storage system read error, or a read of a previous bad write. these are possible, but
5131
                // less likely scenarios. we don't have enough information to tell a difference here.
5132
                // the reindex process is not the place to attempt to clean and/or compact the block files. if so desired, a studious node operator
5133
                // may use knowledge of the fact that the block files are not entirely pristine in order to prepare a set of pristine, and
5134
                // perhaps ordered, block files for later reindexing.
5135
0
                LogDebug(BCLog::REINDEX, "%s: unexpected data at file offset 0x%x - %s. continuing\n", __func__, (nRewind - 1), e.what());
5136
0
            }
5137
2.15k
        }
5138
18
    } catch (const std::runtime_error& e) {
5139
0
        GetNotifications().fatalError(strprintf(_("System error while loading external block file: %s"), e.what()));
5140
0
    }
5141
15
    LogInfo("Loaded %i blocks from external file in %dms", nLoaded, Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
5142
15
}
5143
5144
bool ChainstateManager::ShouldCheckBlockIndex() const
5145
417k
{
5146
    // Assert to verify Flatten() has been called.
5147
417k
    if (!*Assert(m_options.check_block_index)) return false;
5148
315k
    if (FastRandomContext().randrange(*m_options.check_block_index) >= 1) return false;
5149
315k
    return true;
5150
315k
}
5151
5152
void ChainstateManager::CheckBlockIndex() const
5153
417k
{
5154
417k
    if (!ShouldCheckBlockIndex()) {
5155
102k
        return;
5156
102k
    }
5157
5158
315k
    LOCK(cs_main);
5159
5160
    // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
5161
    // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
5162
    // tests when iterating the block tree require that m_chain has been initialized.)
5163
315k
    if (ActiveChain().Height() < 0) {
5164
28
        assert(m_blockman.m_block_index.size() <= 1);
5165
28
        return;
5166
28
    }
5167
5168
    // Build forward-pointing data structure for the entire block tree.
5169
    // For performance reasons, indexes of the best header chain are stored in a vector (within CChain).
5170
    // All remaining blocks are stored in a multimap.
5171
    // The best header chain can differ from the active chain: E.g. its entries may belong to blocks that
5172
    // are not yet validated.
5173
315k
    CChain best_hdr_chain;
5174
315k
    assert(m_best_header);
5175
315k
    assert(!(m_best_header->nStatus & BLOCK_FAILED_VALID));
5176
315k
    best_hdr_chain.SetTip(*m_best_header);
5177
5178
315k
    std::multimap<const CBlockIndex*, const CBlockIndex*> forward;
5179
180M
    for (auto& [_, block_index] : m_blockman.m_block_index) {
5180
        // Only save indexes in forward that are not part of the best header chain.
5181
180M
        if (!best_hdr_chain.Contains(block_index)) {
5182
            // Only genesis, which must be part of the best header chain, can have a nullptr parent.
5183
17.2M
            assert(block_index.pprev);
5184
17.2M
            forward.emplace(block_index.pprev, &block_index);
5185
17.2M
        }
5186
180M
    }
5187
315k
    assert(forward.size() + best_hdr_chain.Height() + 1 == m_blockman.m_block_index.size());
5188
5189
315k
    const CBlockIndex* pindex = best_hdr_chain[0];
5190
315k
    assert(pindex);
5191
    // Iterate over the entire block tree, using depth-first search.
5192
    // Along the way, remember whether there are blocks on the path from genesis
5193
    // block being explored which are the first to have certain properties.
5194
315k
    size_t nNodes = 0;
5195
315k
    int nHeight = 0;
5196
315k
    const CBlockIndex* pindexFirstInvalid = nullptr;              // Oldest ancestor of pindex which is invalid.
5197
315k
    const CBlockIndex* pindexFirstMissing = nullptr;              // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA, since assumeutxo snapshot if used.
5198
315k
    const CBlockIndex* pindexFirstNeverProcessed = nullptr;       // Oldest ancestor of pindex for which nTx == 0, since assumeutxo snapshot if used.
5199
315k
    const CBlockIndex* pindexFirstNotTreeValid = nullptr;         // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
5200
315k
    const CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not), since assumeutxo snapshot if used.
5201
315k
    const CBlockIndex* pindexFirstNotChainValid = nullptr;        // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not), since assumeutxo snapshot if used.
5202
315k
    const CBlockIndex* pindexFirstNotScriptsValid = nullptr;      // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not), since assumeutxo snapshot if used.
5203
5204
    // After checking an assumeutxo snapshot block, reset pindexFirst pointers
5205
    // to earlier blocks that have not been downloaded or validated yet, so
5206
    // checks for later blocks can assume the earlier blocks were validated and
5207
    // be stricter, testing for more requirements.
5208
315k
    const CBlockIndex* snap_base{CurrentChainstate().SnapshotBase()};
5209
315k
    const CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{}, *snap_first_nocv{}, *snap_first_nosv{};
5210
197M
    auto snap_update_firsts = [&] {
5211
197M
        if (pindex == snap_base) {
5212
9.41k
            std::swap(snap_first_missing, pindexFirstMissing);
5213
9.41k
            std::swap(snap_first_notx, pindexFirstNeverProcessed);
5214
9.41k
            std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
5215
9.41k
            std::swap(snap_first_nocv, pindexFirstNotChainValid);
5216
9.41k
            std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
5217
9.41k
        }
5218
197M
    };
5219
5220
180M
    while (pindex != nullptr) {
5221
180M
        nNodes++;
5222
180M
        if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5223
180M
        if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
5224
410k
            pindexFirstMissing = pindex;
5225
410k
        }
5226
180M
        if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
5227
180M
        if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
5228
5229
180M
        if (pindex->pprev != nullptr) {
5230
180M
            if (pindexFirstNotTransactionsValid == nullptr &&
5231
180M
                    (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) {
5232
409k
                pindexFirstNotTransactionsValid = pindex;
5233
409k
            }
5234
5235
180M
            if (pindexFirstNotChainValid == nullptr &&
5236
180M
                    (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) {
5237
13.2M
                pindexFirstNotChainValid = pindex;
5238
13.2M
            }
5239
5240
180M
            if (pindexFirstNotScriptsValid == nullptr &&
5241
180M
                    (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
5242
13.2M
                pindexFirstNotScriptsValid = pindex;
5243
13.2M
            }
5244
180M
        }
5245
5246
        // Begin: actual consistency checks.
5247
180M
        if (pindex->pprev == nullptr) {
5248
            // Genesis block checks.
5249
315k
            assert(pindex->GetBlockHash() == GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
5250
324k
            for (const auto& c : m_chainstates) {
5251
324k
                if (c->m_chain.Genesis() != nullptr) {
5252
324k
                    assert(pindex == c->m_chain.Genesis()); // The chain's genesis block must be this block.
5253
324k
                }
5254
324k
            }
5255
315k
        }
5256
        // nSequenceId can't be set higher than SEQ_ID_INIT_FROM_DISK{1} for blocks that aren't linked
5257
        // (negative is used for preciousblock, SEQ_ID_BEST_CHAIN_FROM_DISK{0} for active chain when loaded from disk)
5258
180M
        if (!pindex->HaveNumChainTxs()) assert(pindex->nSequenceId <= SEQ_ID_INIT_FROM_DISK);
5259
        // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
5260
        // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
5261
180M
        if (!m_blockman.m_have_pruned) {
5262
            // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
5263
178M
            assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
5264
178M
            assert(pindexFirstMissing == pindexFirstNeverProcessed);
5265
178M
        } else {
5266
            // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
5267
1.71M
            if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
5268
1.71M
        }
5269
180M
        if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
5270
180M
        if (snap_base && snap_base->GetAncestor(pindex->nHeight) == pindex) {
5271
            // Assumed-valid blocks should connect to the main chain.
5272
2.48M
            assert((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE);
5273
2.48M
        }
5274
        // There should only be an nTx value if we have
5275
        // actually seen a block's transactions.
5276
180M
        assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
5277
        // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveNumChainTxs().
5278
        // HaveNumChainTxs will also be set in the assumeutxo snapshot block from snapshot metadata.
5279
180M
        assert((pindexFirstNeverProcessed == nullptr || pindex == snap_base) == pindex->HaveNumChainTxs());
5280
180M
        assert((pindexFirstNotTransactionsValid == nullptr || pindex == snap_base) == pindex->HaveNumChainTxs());
5281
180M
        assert(pindex->nHeight == nHeight); // nHeight must be consistent.
5282
180M
        assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
5283
180M
        assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
5284
180M
        assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
5285
180M
        if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
5286
180M
        if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
5287
180M
        if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
5288
180M
        if (pindexFirstInvalid == nullptr) {
5289
            // Checks for not-invalid blocks.
5290
167M
            assert((pindex->nStatus & BLOCK_FAILED_VALID) == 0); // The failed flag cannot be set for blocks without invalid parents.
5291
167M
        } else {
5292
12.9M
            assert(pindex->nStatus & BLOCK_FAILED_VALID); // Invalid blocks and their descendants must be marked as invalid
5293
12.9M
        }
5294
        // Make sure m_chain_tx_count sum is correctly computed.
5295
180M
        if (!pindex->pprev) {
5296
            // If no previous block, nTx and m_chain_tx_count must be the same.
5297
315k
            assert(pindex->m_chain_tx_count == pindex->nTx);
5298
180M
        } else if (pindex->pprev->m_chain_tx_count > 0 && pindex->nTx > 0) {
5299
            // If previous m_chain_tx_count is set and number of transactions in block is known, sum must be set.
5300
121M
            assert(pindex->m_chain_tx_count == pindex->nTx + pindex->pprev->m_chain_tx_count);
5301
121M
        } else {
5302
            // Otherwise m_chain_tx_count should only be set if this is a snapshot
5303
            // block, and must be set if it is.
5304
58.6M
            assert((pindex->m_chain_tx_count != 0) == (pindex == snap_base));
5305
58.6M
        }
5306
        // There should be no block with more work than m_best_header, unless it's known to be invalid
5307
180M
        assert((pindex->nStatus & BLOCK_FAILED_VALID) || pindex->nChainWork <= m_best_header->nChainWork);
5308
5309
        // Chainstate-specific checks on setBlockIndexCandidates
5310
184M
        for (const auto& c : m_chainstates) {
5311
184M
            if (c->m_chain.Tip() == nullptr) continue;
5312
            // Two main factors determine whether pindex is a candidate in
5313
            // setBlockIndexCandidates:
5314
            //
5315
            // - If pindex has less work than the chain tip, it should not be a
5316
            //   candidate, and this will be asserted below. Otherwise it is a
5317
            //   potential candidate.
5318
            //
5319
            // - If pindex or one of its parent blocks back to the genesis block
5320
            //   or an assumeutxo snapshot never downloaded transactions
5321
            //   (pindexFirstNeverProcessed is non-null), it should not be a
5322
            //   candidate, and this will be asserted below. The only exception
5323
            //   is if pindex itself is an assumeutxo snapshot block. Then it is
5324
            //   also a potential candidate.
5325
184M
            if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && (pindexFirstNeverProcessed == nullptr || pindex == snap_base)) {
5326
                // If pindex was detected as invalid (pindexFirstInvalid is
5327
                // non-null), it is not required to be in
5328
                // setBlockIndexCandidates.
5329
1.95M
                if (pindexFirstInvalid == nullptr) {
5330
                    // If pindex and all its parents back to the genesis block
5331
                    // or an assumeutxo snapshot block downloaded transactions,
5332
                    // and the transactions were not pruned (pindexFirstMissing
5333
                    // is null), it is a potential candidate. The check
5334
                    // excludes pruned blocks, because if any blocks were
5335
                    // pruned between pindex and the current chain tip, pindex will
5336
                    // only temporarily be added to setBlockIndexCandidates,
5337
                    // before being moved to m_blocks_unlinked. This check
5338
                    // could be improved to verify that if all blocks between
5339
                    // the chain tip and pindex have data, pindex must be a
5340
                    // candidate.
5341
                    //
5342
                    // If pindex is the chain tip, it also is a potential
5343
                    // candidate.
5344
                    //
5345
                    // If the chainstate was loaded from a snapshot and pindex
5346
                    // is the base of the snapshot, pindex is also a potential
5347
                    // candidate.
5348
1.83M
                    if (pindexFirstMissing == nullptr || pindex == c->m_chain.Tip() || pindex == c->SnapshotBase()) {
5349
                        // If this chainstate is not a historical chainstate
5350
                        // targeting a specific block, pindex must be in
5351
                        // setBlockIndexCandidates. Otherwise, pindex only
5352
                        // needs to be added if it is an ancestor of the target
5353
                        // block.
5354
1.83M
                        if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->nHeight) == pindex) {
5355
904k
                            assert(c->setBlockIndexCandidates.contains(pindex));
5356
904k
                        }
5357
1.83M
                    }
5358
                    // If some parent is missing, then it could be that this block was in
5359
                    // setBlockIndexCandidates but had to be removed because of the missing data.
5360
                    // In this case it must be in m_blocks_unlinked -- see test below.
5361
1.83M
                }
5362
182M
            } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
5363
182M
                assert(!c->setBlockIndexCandidates.contains(pindex));
5364
182M
            }
5365
184M
        }
5366
        // Check whether this block is in m_blocks_unlinked.
5367
180M
        auto rangeUnlinked{m_blockman.m_blocks_unlinked.equal_range(pindex->pprev)};
5368
180M
        bool foundInUnlinked = false;
5369
202M
        for (auto it = rangeUnlinked.first; it != rangeUnlinked.second; ++it) {
5370
22.0M
            assert(it->first == pindex->pprev);
5371
22.0M
            if (it->second == pindex) {
5372
21.9M
                assert(!foundInUnlinked); // No duplicates in m_blocks_unlinked
5373
21.9M
                foundInUnlinked = true;
5374
21.9M
            }
5375
22.0M
        }
5376
180M
        if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
5377
            // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
5378
21.9M
            assert(foundInUnlinked);
5379
21.9M
        }
5380
180M
        if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
5381
180M
        if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
5382
180M
        if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
5383
            // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
5384
965k
            assert(m_blockman.m_have_pruned);
5385
            // This block may have entered m_blocks_unlinked if:
5386
            //  - it has a descendant that at some point had more work than the
5387
            //    tip, and
5388
            //  - we tried switching to that descendant but were missing
5389
            //    data for some intermediate block between m_chain and the
5390
            //    tip.
5391
            // So if this block is itself better than any m_chain.Tip() and it wasn't in
5392
            // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
5393
965k
            for (const auto& c : m_chainstates) {
5394
965k
                if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) && !c->setBlockIndexCandidates.contains(pindex)) {
5395
0
                    if (pindexFirstInvalid == nullptr) {
5396
0
                        if (!c->TargetBlock() || c->TargetBlock()->GetAncestor(pindex->nHeight) == pindex) {
5397
0
                            assert(foundInUnlinked);
5398
0
                        }
5399
0
                    }
5400
0
                }
5401
965k
            }
5402
965k
        }
5403
        // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
5404
        // End: actual consistency checks.
5405
5406
5407
        // Try descending into the first subnode. Always process forks first and the best header chain after.
5408
180M
        snap_update_firsts();
5409
180M
        auto range{forward.equal_range(pindex)};
5410
180M
        if (range.first != range.second) {
5411
            // A subnode not part of the best header chain was found.
5412
11.1M
            pindex = range.first->second;
5413
11.1M
            nHeight++;
5414
11.1M
            continue;
5415
169M
        } else if (best_hdr_chain.Contains(*pindex)) {
5416
            // Descend further into best header chain.
5417
156M
            nHeight++;
5418
156M
            pindex = best_hdr_chain[nHeight];
5419
156M
            if (!pindex) break; // we are finished, since the best header chain is always processed last
5420
155M
            continue;
5421
156M
        }
5422
        // This is a leaf node.
5423
        // Move upwards until we reach a node of which we have not yet visited the last child.
5424
17.2M
        while (pindex) {
5425
            // We are going to either move to a parent or a sibling of pindex.
5426
17.2M
            snap_update_firsts();
5427
            // If pindex was the first with a certain property, unset the corresponding variable.
5428
17.2M
            if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
5429
17.2M
            if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
5430
17.2M
            if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
5431
17.2M
            if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
5432
17.2M
            if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
5433
17.2M
            if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
5434
17.2M
            if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
5435
            // Find our parent.
5436
17.2M
            CBlockIndex* pindexPar = pindex->pprev;
5437
            // Find which child we just visited.
5438
17.2M
            auto rangePar{forward.equal_range(pindexPar)};
5439
27.9M
            while (rangePar.first->second != pindex) {
5440
10.6M
                assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
5441
10.6M
                rangePar.first++;
5442
10.6M
            }
5443
            // Proceed to the next one.
5444
17.2M
            rangePar.first++;
5445
17.2M
            if (rangePar.first != rangePar.second) {
5446
                // Move to a sibling not part of the best header chain.
5447
6.09M
                pindex = rangePar.first->second;
5448
6.09M
                break;
5449
11.1M
            } else if (pindexPar == best_hdr_chain[nHeight - 1]) {
5450
                // Move to pindex's sibling on the best-chain, if it has one.
5451
6.98M
                pindex = best_hdr_chain[nHeight];
5452
                // There will not be a next block if (and only if) parent block is the best header.
5453
6.98M
                assert((pindex == nullptr) == (pindexPar == best_hdr_chain.Tip()));
5454
6.98M
                break;
5455
6.98M
            } else {
5456
                // Move up further.
5457
4.17M
                pindex = pindexPar;
5458
4.17M
                nHeight--;
5459
4.17M
                continue;
5460
4.17M
            }
5461
17.2M
        }
5462
13.0M
    }
5463
5464
    // Check that we actually traversed the entire block index.
5465
315k
    assert(nNodes == forward.size() + best_hdr_chain.Height() + 1);
5466
315k
}
5467
5468
std::string Chainstate::ToString()
5469
1.55k
{
5470
1.55k
    AssertLockHeld(::cs_main);
5471
1.55k
    CBlockIndex* tip = m_chain.Tip();
5472
1.55k
    return strprintf("Chainstate [%s] @ height %d (%s)",
5473
1.55k
                     m_from_snapshot_blockhash ? "snapshot" : "ibd",
5474
1.55k
                     tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
5475
1.55k
}
5476
5477
bool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
5478
1.89k
{
5479
1.89k
    AssertLockHeld(::cs_main);
5480
1.89k
    if (coinstip_size == m_coinstip_cache_size_bytes &&
5481
1.89k
            coinsdb_size == m_coinsdb_cache_size_bytes) {
5482
        // Cache sizes are unchanged, no need to continue.
5483
1.76k
        return true;
5484
1.76k
    }
5485
127
    size_t old_coinstip_size = m_coinstip_cache_size_bytes;
5486
127
    m_coinstip_cache_size_bytes = coinstip_size;
5487
127
    m_coinsdb_cache_size_bytes = coinsdb_size;
5488
127
    CoinsDB().ResizeCache(coinsdb_size);
5489
5490
127
    LogInfo("[%s] resized coinsdb cache to %.1f MiB",
5491
127
        this->ToString(), coinsdb_size / double(1_MiB));
5492
127
    LogInfo("[%s] resized coinstip cache to %.1f MiB",
5493
127
        this->ToString(), coinstip_size / double(1_MiB));
5494
5495
127
    BlockValidationState state;
5496
127
    bool ret;
5497
5498
127
    if (coinstip_size > old_coinstip_size) {
5499
        // Likely no need to flush if cache sizes have grown.
5500
61
        ret = FlushStateToDisk(state, FlushStateMode::IF_NEEDED);
5501
66
    } else {
5502
        // Otherwise, flush state to disk and deallocate the in-memory coins map.
5503
66
        ret = FlushStateToDisk(state, FlushStateMode::FORCE_FLUSH);
5504
66
    }
5505
127
    return ret;
5506
1.89k
}
5507
5508
double ChainstateManager::GuessVerificationProgress(const CBlockIndex* pindex) const
5509
313k
{
5510
313k
    AssertLockHeld(GetMutex());
5511
313k
    const ChainTxData& data{GetParams().TxData()};
5512
313k
    if (pindex == nullptr) {
5513
2
        return 0.0;
5514
2
    }
5515
5516
313k
    if (pindex->m_chain_tx_count == 0) {
5517
198
        LogDebug(BCLog::VALIDATION, "Block %d has unset m_chain_tx_count. Unable to estimate verification progress.\n", pindex->nHeight);
5518
198
        return 0.0;
5519
198
    }
5520
5521
313k
    const int64_t nNow{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())};
5522
313k
    const auto block_time{
5523
313k
        (Assume(m_best_header) && std::abs(nNow - pindex->GetBlockTime()) <= Ticks<std::chrono::seconds>(2h) &&
5524
313k
         Assume(m_best_header->nHeight >= pindex->nHeight)) ?
5525
            // When the header is known to be recent, switch to a height-based
5526
            // approach. This ensures the returned value is quantized when
5527
            // close to "1.0", because some users expect it to be. This also
5528
            // avoids relying too much on the exact miner-set timestamp, which
5529
            // may be off.
5530
260k
            nNow - (m_best_header->nHeight - pindex->nHeight) * GetConsensus().nPowTargetSpacing :
5531
313k
            pindex->GetBlockTime(),
5532
313k
    };
5533
5534
313k
    double fTxTotal;
5535
5536
313k
    if (pindex->m_chain_tx_count <= data.tx_count) {
5537
4.41k
        fTxTotal = data.tx_count + (nNow - data.nTime) * data.dTxRate;
5538
309k
    } else {
5539
309k
        fTxTotal = pindex->m_chain_tx_count + (nNow - block_time) * data.dTxRate;
5540
309k
    }
5541
5542
313k
    return std::min<double>(pindex->m_chain_tx_count / fTxTotal, 1.0);
5543
313k
}
5544
5545
double ChainstateManager::GetBackgroundVerificationProgress(const CBlockIndex& pindex) const
5546
5
{
5547
5
    AssertLockHeld(GetMutex());
5548
5
    Assert(HistoricalChainstate());
5549
5
    auto target_block = HistoricalChainstate()->TargetBlock();
5550
5551
5
    if (pindex.m_chain_tx_count == 0 || target_block->m_chain_tx_count == 0) {
5552
0
        LogDebug(BCLog::VALIDATION, "[background validation] Block %d has unset m_chain_tx_count. Unable to estimate verification progress.", pindex.nHeight);
5553
0
        return 0.0;
5554
0
    }
5555
5
    return static_cast<double>(pindex.m_chain_tx_count) / static_cast<double>(target_block->m_chain_tx_count);
5556
5
}
5557
5558
Chainstate& ChainstateManager::InitializeChainstate(CTxMemPool* mempool)
5559
1.31k
{
5560
1.31k
    AssertLockHeld(::cs_main);
5561
1.31k
    assert(m_chainstates.empty());
5562
1.31k
    m_chainstates.emplace_back(std::make_unique<Chainstate>(mempool, m_blockman, *this));
5563
1.31k
    return *m_chainstates.back();
5564
1.31k
}
5565
5566
[[nodiscard]] static bool DeleteCoinsDBFromDisk(const fs::path db_path, bool is_snapshot)
5567
    EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
5568
30
{
5569
30
    AssertLockHeld(::cs_main);
5570
5571
30
    if (is_snapshot) {
5572
27
        fs::path base_blockhash_path = db_path / node::SNAPSHOT_BLOCKHASH_FILENAME;
5573
5574
27
        try {
5575
27
            bool existed = fs::remove(base_blockhash_path);
5576
27
            if (!existed) {
5577
25
                LogWarning("[snapshot] snapshot chainstate dir being removed lacks %s file",
5578
25
                          fs::PathToString(node::SNAPSHOT_BLOCKHASH_FILENAME));
5579
25
            }
5580
27
        } catch (const fs::filesystem_error& e) {
5581
0
            LogWarning("[snapshot] failed to remove file %s: %s\n",
5582
0
                       fs::PathToString(base_blockhash_path), e.code().message());
5583
0
        }
5584
27
    }
5585
5586
30
    std::string path_str = fs::PathToString(db_path);
5587
30
    LogInfo("Removing leveldb dir at %s\n", path_str);
5588
5589
    // We have to destruct before this call leveldb::DB in order to release the db
5590
    // lock, otherwise `DestroyDB` will fail. See `leveldb::~DBImpl()`.
5591
30
    const bool destroyed = DestroyDB(path_str);
5592
5593
30
    if (!destroyed) {
5594
0
        LogError("leveldb DestroyDB call failed on %s", path_str);
5595
0
    }
5596
5597
    // Datadir should be removed from filesystem; otherwise initialization may detect
5598
    // it on subsequent statups and get confused.
5599
    //
5600
    // If the base_blockhash_path removal above fails in the case of snapshot
5601
    // chainstates, this will return false since leveldb won't remove a non-empty
5602
    // directory.
5603
30
    return destroyed && !fs::exists(db_path);
5604
30
}
5605
5606
util::Result<CBlockIndex*> ChainstateManager::ActivateSnapshot(
5607
        AutoFile& coins_file,
5608
        const SnapshotMetadata& metadata,
5609
        bool in_memory)
5610
64
{
5611
64
    uint256 base_blockhash = metadata.m_base_blockhash;
5612
5613
64
    CBlockIndex* snapshot_start_block{};
5614
5615
64
    {
5616
64
        LOCK(::cs_main);
5617
5618
64
        if (this->CurrentChainstate().m_from_snapshot_blockhash) {
5619
5
            return util::Error{Untranslated("Can't activate a snapshot-based chainstate more than once")};
5620
5
        }
5621
59
        if (!GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
5622
14
            auto available_heights = GetParams().GetAvailableSnapshotHeights();
5623
42
            std::string heights_formatted = util::Join(available_heights, ", ", [&](const auto& i) { return util::ToString(i); });
5624
14
            return util::Error{Untranslated(strprintf("assumeutxo block hash in snapshot metadata not recognized (hash: %s). The following snapshot heights are available: %s",
5625
14
                base_blockhash.ToString(),
5626
14
                heights_formatted))};
5627
14
        }
5628
5629
45
        snapshot_start_block = m_blockman.LookupBlockIndex(base_blockhash);
5630
45
        if (!snapshot_start_block) {
5631
3
            return util::Error{Untranslated(strprintf("The base block header (%s) must appear in the headers chain. Make sure all headers are syncing, and call loadtxoutset again",
5632
3
                          base_blockhash.ToString()))};
5633
3
        }
5634
5635
42
        bool start_block_invalid = snapshot_start_block->nStatus & BLOCK_FAILED_VALID;
5636
42
        if (start_block_invalid) {
5637
2
            return util::Error{Untranslated(strprintf("The base block header (%s) is part of an invalid chain", base_blockhash.ToString()))};
5638
2
        }
5639
5640
40
        if (!m_best_header || m_best_header->GetAncestor(snapshot_start_block->nHeight) != snapshot_start_block) {
5641
1
            return util::Error{Untranslated("A forked headers-chain with more work than the chain with the snapshot base block header exists. Please proceed to sync without AssumeUtxo.")};
5642
1
        }
5643
5644
39
        auto mempool{CurrentChainstate().GetMempool()};
5645
39
        if (mempool && mempool->size() > 0) {
5646
1
            return util::Error{Untranslated("Can't activate a snapshot when mempool not empty")};
5647
1
        }
5648
39
    }
5649
5650
38
    int64_t current_coinsdb_cache_size{0};
5651
38
    int64_t current_coinstip_cache_size{0};
5652
5653
    // Cache percentages to allocate to each chainstate.
5654
    //
5655
    // These particular percentages don't matter so much since they will only be
5656
    // relevant during snapshot activation; caches are rebalanced at the conclusion of
5657
    // this function. We want to give (essentially) all available cache capacity to the
5658
    // snapshot to aid the bulk load later in this function.
5659
38
    static constexpr double IBD_CACHE_PERC = 0.01;
5660
38
    static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
5661
5662
38
    {
5663
38
        LOCK(::cs_main);
5664
        // Resize the coins caches to ensure we're not exceeding memory limits.
5665
        //
5666
        // Allocate the majority of the cache to the incoming snapshot chainstate, since
5667
        // (optimistically) getting to its tip will be the top priority. We'll need to call
5668
        // `MaybeRebalanceCaches()` once we're done with this function to ensure
5669
        // the right allocation (including the possibility that no snapshot was activated
5670
        // and that we should restore the active chainstate caches to their original size).
5671
        //
5672
38
        current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
5673
38
        current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
5674
5675
        // Temporarily resize the active coins cache to make room for the newly-created
5676
        // snapshot chain.
5677
38
        this->ActiveChainstate().ResizeCoinsCaches(
5678
38
            static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
5679
38
            static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
5680
38
    }
5681
5682
38
    auto snapshot_chainstate = WITH_LOCK(::cs_main,
5683
38
        return std::make_unique<Chainstate>(
5684
38
            /*mempool=*/nullptr, m_blockman, *this, base_blockhash));
5685
5686
38
    {
5687
38
        LOCK(::cs_main);
5688
38
        snapshot_chainstate->InitCoinsDB(
5689
38
            static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
5690
38
            in_memory, /*should_wipe=*/false);
5691
38
        snapshot_chainstate->InitCoinsCache(
5692
38
            static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
5693
38
    }
5694
5695
38
    auto cleanup_bad_snapshot = [&](bilingual_str reason) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
5696
24
        this->MaybeRebalanceCaches();
5697
5698
        // PopulateAndValidateSnapshot can return (in error) before the leveldb datadir
5699
        // has been created, so only attempt removal if we got that far.
5700
24
        if (auto snapshot_datadir = node::FindAssumeutxoChainstateDir(m_options.datadir)) {
5701
            // We have to destruct leveldb::DB in order to release the db lock, otherwise
5702
            // DestroyDB() (in DeleteCoinsDBFromDisk()) will fail. See `leveldb::~DBImpl()`.
5703
            // Destructing the chainstate (and so resetting the coinsviews object) does this.
5704
24
            snapshot_chainstate.reset();
5705
24
            bool removed = DeleteCoinsDBFromDisk(*snapshot_datadir, /*is_snapshot=*/true);
5706
24
            if (!removed) {
5707
0
                GetNotifications().fatalError(strprintf(_("Failed to remove snapshot chainstate dir (%s). "
5708
0
                    "Manually remove it before restarting.\n"), fs::PathToString(*snapshot_datadir)));
5709
0
            }
5710
24
        }
5711
24
        return util::Error{std::move(reason)};
5712
24
    };
5713
5714
38
    if (auto res{this->PopulateAndValidateSnapshot(*snapshot_chainstate, coins_file, metadata)}; !res) {
5715
24
        LOCK(::cs_main);
5716
24
        return cleanup_bad_snapshot(Untranslated(strprintf("Population failed: %s", util::ErrorString(res).original)));
5717
24
    }
5718
5719
14
    LOCK(::cs_main);  // cs_main required for rest of snapshot activation.
5720
5721
    // Do a final check to ensure that the snapshot chainstate is actually a more
5722
    // work chain than the active chainstate; a user could have loaded a snapshot
5723
    // very late in the IBD process, and we wouldn't want to load a useless chainstate.
5724
14
    if (!CBlockIndexWorkComparator()(ActiveTip(), snapshot_chainstate->m_chain.Tip())) {
5725
0
        return cleanup_bad_snapshot(Untranslated("work does not exceed active chainstate"));
5726
0
    }
5727
    // If not in-memory, persist the base blockhash for use during subsequent
5728
    // initialization.
5729
14
    if (!in_memory) {
5730
14
        if (!node::WriteSnapshotBaseBlockhash(*snapshot_chainstate)) {
5731
0
            return cleanup_bad_snapshot(Untranslated("could not write base blockhash"));
5732
0
        }
5733
14
    }
5734
5735
14
    Chainstate& chainstate{AddChainstate(std::move(snapshot_chainstate))};
5736
14
    m_blockman.m_snapshot_height = Assert(chainstate.SnapshotBase())->nHeight;
5737
5738
14
    chainstate.PopulateBlockIndexCandidates();
5739
5740
14
    LogInfo("[snapshot] successfully activated snapshot %s", base_blockhash.ToString());
5741
14
    LogInfo("[snapshot] (%.2f MB)",
5742
14
              chainstate.CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
5743
5744
14
    this->MaybeRebalanceCaches();
5745
14
    return snapshot_start_block;
5746
14
}
5747
5748
static void FlushSnapshotToDisk(CCoinsViewCache& coins_cache, bool snapshot_loaded)
5749
22
{
5750
22
    LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(
5751
22
        strprintf("%s (%.2f MB)",
5752
22
                  snapshot_loaded ? "saving snapshot chainstate" : "flushing coins cache",
5753
22
                  coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
5754
22
        BCLog::LogFlags::ALL);
5755
5756
22
    coins_cache.Flush();
5757
22
}
5758
5759
struct StopHashingException : public std::exception
5760
{
5761
    const char* what() const noexcept override
5762
0
    {
5763
0
        return "ComputeUTXOStats interrupted.";
5764
0
    }
5765
};
5766
5767
static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt& interrupt)
5768
8.00k
{
5769
8.00k
    if (interrupt) throw StopHashingException();
5770
8.00k
}
5771
5772
util::Result<void> ChainstateManager::PopulateAndValidateSnapshot(
5773
    Chainstate& snapshot_chainstate,
5774
    AutoFile& coins_file,
5775
    const SnapshotMetadata& metadata)
5776
38
{
5777
    // It's okay to release cs_main before we're done using `coins_cache` because we know
5778
    // that nothing else will be referencing the newly created snapshot_chainstate yet.
5779
38
    CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
5780
5781
38
    uint256 base_blockhash = metadata.m_base_blockhash;
5782
5783
38
    CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
5784
5785
38
    if (!snapshot_start_block) {
5786
        // Needed for ComputeUTXOStats to determine the
5787
        // height and to avoid a crash when base_blockhash.IsNull()
5788
0
        return util::Error{Untranslated(strprintf("Did not find snapshot start blockheader %s",
5789
0
                  base_blockhash.ToString()))};
5790
0
    }
5791
5792
38
    int base_height = snapshot_start_block->nHeight;
5793
38
    const auto& maybe_au_data = GetParams().AssumeutxoForHeight(base_height);
5794
5795
38
    if (!maybe_au_data) {
5796
0
        return util::Error{Untranslated(strprintf("Assumeutxo height in snapshot metadata not recognized "
5797
0
                  "(%d) - refusing to load snapshot", base_height))};
5798
0
    }
5799
5800
38
    const AssumeutxoData& au_data = *maybe_au_data;
5801
5802
    // This work comparison is a duplicate check with the one performed later in
5803
    // ActivateSnapshot(), but is done so that we avoid doing the long work of staging
5804
    // a snapshot that isn't actually usable.
5805
38
    if (WITH_LOCK(::cs_main, return !CBlockIndexWorkComparator()(ActiveTip(), snapshot_start_block))) {
5806
2
        return util::Error{Untranslated("Work does not exceed active chainstate")};
5807
2
    }
5808
5809
36
    const uint64_t coins_count = metadata.m_coins_count;
5810
36
    uint64_t coins_left = metadata.m_coins_count;
5811
5812
36
    LogInfo("[snapshot] loading %d coins from snapshot %s", coins_left, base_blockhash.ToString());
5813
36
    int64_t coins_processed{0};
5814
5815
6.38k
    while (coins_left > 0) {
5816
6.35k
        try {
5817
6.35k
            Txid txid;
5818
6.35k
            coins_file >> txid;
5819
6.35k
            size_t coins_per_txid{0};
5820
6.35k
            coins_per_txid = ReadCompactSize(coins_file);
5821
5822
6.35k
            if (coins_per_txid > coins_left) {
5823
1
                return util::Error{Untranslated("Mismatch in coins count in snapshot metadata and actual snapshot data")};
5824
1
            }
5825
5826
12.7k
            for (size_t i = 0; i < coins_per_txid; i++) {
5827
6.35k
                COutPoint outpoint;
5828
6.35k
                Coin coin;
5829
6.35k
                outpoint.n = static_cast<uint32_t>(ReadCompactSize(coins_file));
5830
6.35k
                outpoint.hash = txid;
5831
6.35k
                coins_file >> coin;
5832
6.35k
                if (coin.nHeight > base_height ||
5833
6.35k
                    outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
5834
6.35k
                ) {
5835
2
                    return util::Error{Untranslated(strprintf("Bad snapshot data after deserializing %d coins",
5836
2
                              coins_count - coins_left))};
5837
2
                }
5838
6.34k
                if (!MoneyRange(coin.out.nValue)) {
5839
1
                    return util::Error{Untranslated(strprintf("Bad snapshot data after deserializing %d coins - bad tx out value",
5840
1
                              coins_count - coins_left))};
5841
1
                }
5842
6.34k
                coins_cache.EmplaceCoinInternalDANGER(outpoint, std::move(coin));
5843
5844
6.34k
                --coins_left;
5845
6.34k
                ++coins_processed;
5846
5847
6.34k
                if (coins_processed % 1000000 == 0) {
5848
0
                    LogInfo("[snapshot] %d coins loaded (%.2f%%, %.2f MB)",
5849
0
                        coins_processed,
5850
0
                        static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
5851
0
                        coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5852
0
                }
5853
5854
                // Batch write and flush (if we need to) every so often.
5855
                //
5856
                // If our average Coin size is roughly 41 bytes, checking every 120,000 coins
5857
                // means <5MB of memory imprecision.
5858
6.34k
                if (coins_processed % 120000 == 0) {
5859
0
                    if (m_interrupt) {
5860
0
                        return util::Error{Untranslated("Aborting after an interrupt was requested")};
5861
0
                    }
5862
5863
0
                    const auto snapshot_cache_state = WITH_LOCK(::cs_main,
5864
0
                        return snapshot_chainstate.GetCoinsCacheSizeState());
5865
5866
0
                    if (snapshot_cache_state >= CoinsCacheSizeState::CRITICAL) {
5867
                        // This is a hack - we don't know what the actual best block is, but that
5868
                        // doesn't matter for the purposes of flushing the cache here. We'll set this
5869
                        // to its correct value (`base_blockhash`) below after the coins are loaded.
5870
0
                        coins_cache.SetBestBlock(GetRandHash());
5871
5872
                        // No need to acquire cs_main since this chainstate isn't being used yet.
5873
0
                        FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/false);
5874
0
                    }
5875
0
                }
5876
6.34k
            }
5877
6.35k
        } catch (const std::ios_base::failure&) {
5878
5
            return util::Error{Untranslated(strprintf("Bad snapshot format or truncated snapshot after deserializing %d coins",
5879
5
                      coins_processed))};
5880
5
        }
5881
6.35k
    }
5882
5883
    // Important that we set this. This and the coins_cache accesses above are
5884
    // sort of a layer violation, but either we reach into the innards of
5885
    // CCoinsViewCache here or we have to invert some of the Chainstate to
5886
    // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
5887
    // method.
5888
27
    coins_cache.SetBestBlock(base_blockhash);
5889
5890
27
    bool out_of_coins{false};
5891
27
    try {
5892
27
        std::byte left_over_byte;
5893
27
        coins_file >> left_over_byte;
5894
27
    } catch (const std::ios_base::failure&) {
5895
        // We expect an exception since we should be out of coins.
5896
22
        out_of_coins = true;
5897
22
    }
5898
27
    if (!out_of_coins) {
5899
5
        return util::Error{Untranslated(strprintf("Bad snapshot - coins left over after deserializing %d coins",
5900
5
            coins_count))};
5901
5
    }
5902
5903
22
    LogInfo("[snapshot] loaded %d (%.2f MB) coins from snapshot %s",
5904
22
        coins_count,
5905
22
        coins_cache.DynamicMemoryUsage() / (1000 * 1000),
5906
22
        base_blockhash.ToString());
5907
5908
    // No need to acquire cs_main since this chainstate isn't being used yet.
5909
22
    FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/true);
5910
5911
22
    assert(coins_cache.GetBestBlock() == base_blockhash);
5912
5913
    // As above, okay to immediately release cs_main here since no other context knows
5914
    // about the snapshot_chainstate.
5915
22
    const CCoinsViewDB& snapshot_coinsdb = WITH_LOCK(::cs_main, return snapshot_chainstate.CoinsDB());
5916
5917
22
    std::optional<CCoinsStats> maybe_stats;
5918
5919
22
    try {
5920
22
        maybe_stats = ComputeUTXOStats(
5921
4.87k
            CoinStatsHashType::HASH_SERIALIZED, snapshot_coinsdb, m_blockman, [&interrupt = m_interrupt] { SnapshotUTXOHashBreakpoint(interrupt); });
5922
22
    } catch (StopHashingException const&) {
5923
0
        return util::Error{Untranslated("Aborting after an interrupt was requested")};
5924
0
    }
5925
22
    if (!maybe_stats.has_value()) {
5926
0
        return util::Error{Untranslated("Failed to generate coins stats")};
5927
0
    }
5928
5929
    // Assert that the deserialized chainstate contents match the expected assumeutxo value.
5930
22
    if (AssumeutxoHash{maybe_stats->hashSerialized} != au_data.hash_serialized) {
5931
8
        return util::Error{Untranslated(strprintf("Bad snapshot content hash: expected %s, got %s",
5932
8
            au_data.hash_serialized.ToString(), maybe_stats->hashSerialized.ToString()))};
5933
8
    }
5934
5935
14
    snapshot_chainstate.m_chain.SetTip(*snapshot_start_block);
5936
5937
    // The remainder of this function requires modifying data protected by cs_main.
5938
14
    LOCK(::cs_main);
5939
5940
    // Fake various pieces of CBlockIndex state:
5941
14
    CBlockIndex* index = nullptr;
5942
5943
    // Don't make any modifications to the genesis block since it shouldn't be
5944
    // necessary, and since the genesis block doesn't have normal flags like
5945
    // BLOCK_VALID_SCRIPTS set.
5946
14
    constexpr int AFTER_GENESIS_START{1};
5947
5948
3.25k
    for (int i = AFTER_GENESIS_START; i <= snapshot_chainstate.m_chain.Height(); ++i) {
5949
3.24k
        index = snapshot_chainstate.m_chain[i];
5950
5951
        // Fake BLOCK_OPT_WITNESS so that Chainstate::NeedsRedownload()
5952
        // won't ask for -reindex on startup.
5953
3.24k
        if (DeploymentActiveAt(*index, *this, Consensus::DEPLOYMENT_SEGWIT)) {
5954
3.24k
            index->nStatus |= BLOCK_OPT_WITNESS;
5955
3.24k
        }
5956
5957
3.24k
        m_blockman.m_dirty_blockindex.insert(index);
5958
        // Changes to the block index will be flushed to disk after this call
5959
        // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
5960
        // called, since we've added a snapshot chainstate and therefore will
5961
        // have to downsize the IBD chainstate, which will result in a call to
5962
        // `FlushStateToDisk(FORCE_FLUSH)`.
5963
3.24k
    }
5964
5965
14
    assert(index);
5966
14
    assert(index == snapshot_start_block);
5967
14
    index->m_chain_tx_count = au_data.m_chain_tx_count;
5968
5969
14
    LogInfo("[snapshot] validated snapshot (%.2f MB)",
5970
14
        coins_cache.DynamicMemoryUsage() / (1000 * 1000));
5971
14
    return {};
5972
14
}
5973
5974
// Currently, this function holds cs_main for its duration, which could be for
5975
// multiple minutes due to the ComputeUTXOStats call. Holding cs_main used to be
5976
// necessary (before d43a1f1a2fa3) to avoid advancing validated_cs farther than
5977
// its target block. Now it should be possible to avoid this, but simply
5978
// releasing cs_main here would not be possible because this function is invoked
5979
// by ConnectTip within ActivateBestChain.
5980
//
5981
// Eventually (TODO) it would be better to call this function outside of
5982
// ActivateBestChain, on a separate thread that should not require cs_main to
5983
// hash, because the UTXO set is only hashed after the historical chainstate
5984
// reaches its target block and is no longer changing.
5985
SnapshotCompletionResult ChainstateManager::MaybeValidateSnapshot(Chainstate& validated_cs, Chainstate& unvalidated_cs)
5986
105k
{
5987
105k
    AssertLockHeld(cs_main);
5988
5989
    // If the snapshot does not need to be validated...
5990
105k
    if (unvalidated_cs.m_assumeutxo != Assumeutxo::UNVALIDATED ||
5991
            // Or if either chainstate is unusable...
5992
105k
            !unvalidated_cs.m_from_snapshot_blockhash ||
5993
105k
            validated_cs.m_assumeutxo != Assumeutxo::VALIDATED ||
5994
105k
            !validated_cs.m_chain.Tip() ||
5995
            // Or the validated chainstate is not targeting the snapshot block...
5996
105k
            !validated_cs.TargetBlockHash() ||
5997
105k
            *validated_cs.TargetBlockHash() != *unvalidated_cs.m_from_snapshot_blockhash ||
5998
            // Or the validated chainstate has not reached the snapshot block yet...
5999
105k
            !validated_cs.ReachedTarget()) {
6000
       // Then the snapshot cannot be validated and there is nothing to do.
6001
105k
       return SnapshotCompletionResult::SKIPPED;
6002
105k
    }
6003
105k
    assert(validated_cs.TargetBlock() == validated_cs.m_chain.Tip());
6004
6005
13
    auto handle_invalid_snapshot = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
6006
1
        bilingual_str user_error = strprintf(_(
6007
1
            "%s failed to validate the -assumeutxo snapshot state. "
6008
1
            "This indicates a hardware problem, or a bug in the software, or a "
6009
1
            "bad software modification that allowed an invalid snapshot to be "
6010
1
            "loaded. As a result of this, the node will shut down and stop using any "
6011
1
            "state that was built on the snapshot, resetting the chain height "
6012
1
            "from %d to %d. On the next "
6013
1
            "restart, the node will resume syncing from %d "
6014
1
            "without using any snapshot data. "
6015
1
            "Please report this incident to %s, including how you obtained the snapshot. "
6016
1
            "The invalid snapshot chainstate will be left on disk in case it is "
6017
1
            "helpful in diagnosing the issue that caused this error."),
6018
1
            CLIENT_NAME, unvalidated_cs.m_chain.Height(),
6019
1
            validated_cs.m_chain.Height(),
6020
1
            validated_cs.m_chain.Height(), CLIENT_BUGREPORT);
6021
6022
1
        LogError("[snapshot] !!! %s\n", user_error.original);
6023
1
        LogError("[snapshot] deleting snapshot, reverting to validated chain, and stopping node\n");
6024
6025
        // Reset chainstate target to network tip instead of snapshot block.
6026
1
        validated_cs.SetTargetBlock(nullptr);
6027
6028
1
        unvalidated_cs.m_assumeutxo = Assumeutxo::INVALID;
6029
6030
1
        auto rename_result = unvalidated_cs.InvalidateCoinsDBOnDisk();
6031
1
        if (!rename_result) {
6032
0
            user_error += Untranslated("\n") + util::ErrorString(rename_result);
6033
0
        }
6034
6035
1
        GetNotifications().fatalError(user_error);
6036
1
    };
6037
6038
13
    CCoinsViewDB& validated_coins_db = validated_cs.CoinsDB();
6039
13
    validated_cs.ForceFlushStateToDisk();
6040
6041
13
    const auto& maybe_au_data = m_options.chainparams.AssumeutxoForHeight(validated_cs.m_chain.Height());
6042
13
    if (!maybe_au_data) {
6043
0
        LogWarning("[snapshot] assumeutxo data not found for height "
6044
0
            "(%d) - refusing to validate snapshot", validated_cs.m_chain.Height());
6045
0
        handle_invalid_snapshot();
6046
0
        return SnapshotCompletionResult::MISSING_CHAINPARAMS;
6047
0
    }
6048
6049
13
    const AssumeutxoData& au_data = *maybe_au_data;
6050
13
    std::optional<CCoinsStats> validated_cs_stats;
6051
13
    LogInfo("[snapshot] computing UTXO stats for background chainstate to validate "
6052
13
        "snapshot - this could take a few minutes");
6053
13
    try {
6054
13
        validated_cs_stats = ComputeUTXOStats(
6055
13
            CoinStatsHashType::HASH_SERIALIZED,
6056
13
            validated_coins_db,
6057
13
            m_blockman,
6058
3.13k
            [&interrupt = m_interrupt] { SnapshotUTXOHashBreakpoint(interrupt); });
6059
13
    } catch (StopHashingException const&) {
6060
0
        return SnapshotCompletionResult::STATS_FAILED;
6061
0
    }
6062
6063
    // XXX note that this function is slow and will hold cs_main for potentially minutes.
6064
13
    if (!validated_cs_stats) {
6065
0
        LogWarning("[snapshot] failed to generate stats for validation coins db");
6066
        // While this isn't a problem with the snapshot per se, this condition
6067
        // prevents us from validating the snapshot, so we should shut down and let the
6068
        // user handle the issue manually.
6069
0
        handle_invalid_snapshot();
6070
0
        return SnapshotCompletionResult::STATS_FAILED;
6071
0
    }
6072
6073
    // Compare the validated chainstate's UTXO set hash against the hard-coded
6074
    // assumeutxo hash we expect.
6075
    //
6076
    // TODO: For belt-and-suspenders, we could cache the UTXO set
6077
    // hash for the snapshot when it's loaded in its chainstate's leveldb. We could then
6078
    // reference that here for an additional check.
6079
13
    if (AssumeutxoHash{validated_cs_stats->hashSerialized} != au_data.hash_serialized) {
6080
1
        LogWarning("[snapshot] hash mismatch: actual=%s, expected=%s",
6081
1
            validated_cs_stats->hashSerialized.ToString(),
6082
1
            au_data.hash_serialized.ToString());
6083
1
        handle_invalid_snapshot();
6084
1
        return SnapshotCompletionResult::HASH_MISMATCH;
6085
1
    }
6086
6087
12
    LogInfo("[snapshot] snapshot beginning at %s has been fully validated",
6088
12
        unvalidated_cs.m_from_snapshot_blockhash->ToString());
6089
6090
12
    unvalidated_cs.m_assumeutxo = Assumeutxo::VALIDATED;
6091
12
    validated_cs.m_target_utxohash = AssumeutxoHash{validated_cs_stats->hashSerialized};
6092
12
    this->MaybeRebalanceCaches();
6093
6094
12
    return SnapshotCompletionResult::SUCCESS;
6095
13
}
6096
6097
Chainstate& ChainstateManager::ActiveChainstate() const
6098
4.18M
{
6099
4.18M
    LOCK(::cs_main);
6100
4.18M
    return CurrentChainstate();
6101
4.18M
}
6102
6103
void ChainstateManager::MaybeRebalanceCaches()
6104
1.82k
{
6105
1.82k
    AssertLockHeld(::cs_main);
6106
1.82k
    Chainstate& current_cs{CurrentChainstate()};
6107
1.82k
    Chainstate* historical_cs{HistoricalChainstate()};
6108
1.82k
    if (!historical_cs && !current_cs.m_from_snapshot_blockhash) {
6109
        // Allocate everything to the IBD chainstate. This will always happen
6110
        // when we are not using a snapshot.
6111
1.79k
        current_cs.ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
6112
1.79k
    } else if (!historical_cs) {
6113
        // If background validation has completed and snapshot is our active chain...
6114
13
        LogInfo("[snapshot] allocating all cache to the snapshot chainstate");
6115
        // Allocate everything to the snapshot chainstate.
6116
13
        current_cs.ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
6117
24
    } else {
6118
        // If both chainstates exist, determine who needs more cache based on IBD status.
6119
        //
6120
        // Note: shrink caches first so that we don't inadvertently overwhelm available memory.
6121
24
        if (IsInitialBlockDownload()) {
6122
12
            historical_cs->ResizeCoinsCaches(
6123
12
                m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
6124
12
            current_cs.ResizeCoinsCaches(
6125
12
                m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
6126
12
        } else {
6127
12
            current_cs.ResizeCoinsCaches(
6128
12
                m_total_coinstip_cache * 0.05, m_total_coinsdb_cache * 0.05);
6129
12
            historical_cs->ResizeCoinsCaches(
6130
12
                m_total_coinstip_cache * 0.95, m_total_coinsdb_cache * 0.95);
6131
12
        }
6132
24
    }
6133
1.82k
}
6134
6135
void ChainstateManager::ResetChainstates()
6136
39
{
6137
39
    m_chainstates.clear();
6138
39
}
6139
6140
/**
6141
 * Apply default chain params to nullopt members.
6142
 * This helps to avoid coding errors around the accidental use of the compare
6143
 * operators that accept nullopt, thus ignoring the intended default value.
6144
 */
6145
static ChainstateManager::Options&& Flatten(ChainstateManager::Options&& opts)
6146
1.29k
{
6147
1.29k
    if (!opts.check_block_index.has_value()) opts.check_block_index = opts.chainparams.DefaultConsistencyChecks();
6148
1.29k
    if (!opts.minimum_chain_work.has_value()) opts.minimum_chain_work = UintToArith256(opts.chainparams.GetConsensus().nMinimumChainWork);
6149
1.29k
    if (!opts.assumed_valid_block.has_value()) opts.assumed_valid_block = opts.chainparams.GetConsensus().defaultAssumeValid;
6150
1.29k
    return std::move(opts);
6151
1.29k
}
6152
6153
ChainstateManager::ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options)
6154
1.29k
    : m_script_check_queue{/*batch_size=*/128, std::clamp(options.worker_threads_num, 0, MAX_SCRIPTCHECK_THREADS)},
6155
1.29k
      m_interrupt{interrupt},
6156
1.29k
      m_options{Flatten(std::move(options))},
6157
1.29k
      m_blockman{interrupt, std::move(blockman_options)},
6158
1.29k
      m_validation_cache{m_options.script_execution_cache_bytes, m_options.signature_cache_bytes}
6159
1.29k
{
6160
1.29k
}
6161
6162
ChainstateManager::~ChainstateManager()
6163
1.29k
{
6164
1.29k
    LOCK(::cs_main);
6165
6166
1.29k
    m_versionbitscache.Clear();
6167
1.29k
}
6168
6169
Chainstate* ChainstateManager::LoadAssumeutxoChainstate()
6170
1.27k
{
6171
1.27k
    assert(!CurrentChainstate().m_from_snapshot_blockhash);
6172
1.27k
    std::optional<fs::path> path = node::FindAssumeutxoChainstateDir(m_options.datadir);
6173
1.27k
    if (!path) {
6174
1.27k
        return nullptr;
6175
1.27k
    }
6176
8
    std::optional<uint256> base_blockhash = node::ReadSnapshotBaseBlockhash(*path);
6177
8
    if (!base_blockhash) {
6178
0
        return nullptr;
6179
0
    }
6180
8
    LogInfo("[snapshot] detected active snapshot chainstate (%s) - loading",
6181
8
        fs::PathToString(*path));
6182
6183
8
    auto snapshot_chainstate{std::make_unique<Chainstate>(nullptr, m_blockman, *this, base_blockhash)};
6184
8
    LogInfo("[snapshot] switching active chainstate to %s", snapshot_chainstate->ToString());
6185
8
    return &this->AddChainstate(std::move(snapshot_chainstate));
6186
8
}
6187
6188
Chainstate& ChainstateManager::AddChainstate(std::unique_ptr<Chainstate> chainstate)
6189
26
{
6190
26
    Chainstate& prev_chainstate{CurrentChainstate()};
6191
26
    assert(prev_chainstate.m_assumeutxo == Assumeutxo::VALIDATED);
6192
    // Set target block for historical chainstate to snapshot block.
6193
26
    assert(!prev_chainstate.TargetBlockHash());
6194
26
    prev_chainstate.SetTargetBlockHash(*Assert(chainstate->m_from_snapshot_blockhash));
6195
26
    m_chainstates.push_back(std::move(chainstate));
6196
26
    Chainstate& curr_chainstate{CurrentChainstate()};
6197
26
    assert(&curr_chainstate == m_chainstates.back().get());
6198
6199
    // Transfer possession of the mempool to the chainstate.
6200
    // Mempool is empty at this point because we're still in IBD.
6201
26
    assert(!prev_chainstate.m_mempool || prev_chainstate.m_mempool->size() == 0);
6202
26
    assert(!curr_chainstate.m_mempool);
6203
26
    std::swap(curr_chainstate.m_mempool, prev_chainstate.m_mempool);
6204
26
    return curr_chainstate;
6205
26
}
6206
6207
bool IsBIP30Repeat(const CBlockIndex& block_index)
6208
153k
{
6209
153k
    return (block_index.nHeight==91842 && block_index.GetBlockHash() == uint256{"00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"}) ||
6210
153k
           (block_index.nHeight==91880 && block_index.GetBlockHash() == uint256{"00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"});
6211
153k
}
6212
6213
bool IsBIP30Unspendable(const uint256& block_hash, int block_height)
6214
4.21k
{
6215
4.21k
    return (block_height==91722 && block_hash == uint256{"00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"}) ||
6216
4.21k
           (block_height==91812 && block_hash == uint256{"00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"});
6217
4.21k
}
6218
6219
util::Result<void> Chainstate::InvalidateCoinsDBOnDisk()
6220
1
{
6221
    // Should never be called on a non-snapshot chainstate.
6222
1
    assert(m_from_snapshot_blockhash);
6223
6224
    // Coins views no longer usable.
6225
1
    m_coins_views.reset();
6226
6227
1
    const fs::path db_path{StoragePath()};
6228
1
    const fs::path invalid_path{db_path + "_INVALID"};
6229
1
    const std::string db_path_str{fs::PathToString(db_path)};
6230
1
    const std::string invalid_path_str{fs::PathToString(invalid_path)};
6231
1
    LogInfo("[snapshot] renaming snapshot datadir %s to %s", db_path_str, invalid_path_str);
6232
6233
    // The invalid storage directory is simply moved and not deleted because we may
6234
    // want to do forensics later during issue investigation. The user is instructed
6235
    // accordingly in MaybeValidateSnapshot().
6236
1
    try {
6237
1
        fs::rename(db_path, invalid_path);
6238
1
    } catch (const fs::filesystem_error& e) {
6239
0
        LogError("While invalidating the coins db: Error renaming file '%s' -> '%s': %s",
6240
0
                 db_path_str, invalid_path_str, e.what());
6241
0
        return util::Error{strprintf(_(
6242
0
            "Rename of '%s' -> '%s' failed. "
6243
0
            "You should resolve this by manually moving or deleting the invalid "
6244
0
            "snapshot directory %s, otherwise you will encounter the same error again "
6245
0
            "on the next startup."),
6246
0
            db_path_str, invalid_path_str, db_path_str)};
6247
0
    }
6248
1
    return {};
6249
1
}
6250
6251
bool ChainstateManager::DeleteChainstate(Chainstate& chainstate)
6252
3
{
6253
3
    AssertLockHeld(::cs_main);
6254
3
    assert(!chainstate.m_coins_views);
6255
3
    const fs::path db_path{chainstate.StoragePath()};
6256
3
    if (!DeleteCoinsDBFromDisk(db_path, /*is_snapshot=*/bool{chainstate.m_from_snapshot_blockhash})) {
6257
0
        LogError("Deletion of %s failed. Please remove it manually to continue reindexing.",
6258
0
                  fs::PathToString(db_path));
6259
0
        return false;
6260
0
    }
6261
3
    std::unique_ptr<Chainstate> prev_chainstate{Assert(RemoveChainstate(chainstate))};
6262
3
    Chainstate& curr_chainstate{CurrentChainstate()};
6263
3
    assert(!prev_chainstate->m_mempool || prev_chainstate->m_mempool->size() == 0);
6264
3
    assert(!curr_chainstate.m_mempool);
6265
3
    std::swap(curr_chainstate.m_mempool, prev_chainstate->m_mempool);
6266
3
    return true;
6267
3
}
6268
6269
ChainstateRole Chainstate::GetRole() const
6270
365k
{
6271
365k
    return ChainstateRole{.validated = m_assumeutxo == Assumeutxo::VALIDATED, .historical = bool{m_target_blockhash}};
6272
365k
}
6273
6274
void ChainstateManager::RecalculateBestHeader()
6275
2.79k
{
6276
2.79k
    AssertLockHeld(cs_main);
6277
2.79k
    m_best_header = ActiveChain().Tip();
6278
5.52M
    for (auto& entry : m_blockman.m_block_index) {
6279
5.52M
        if (!(entry.second.nStatus & BLOCK_FAILED_VALID) && m_best_header->nChainWork < entry.second.nChainWork) {
6280
72
            m_best_header = &entry.second;
6281
72
        }
6282
5.52M
    }
6283
2.79k
}
6284
6285
std::optional<int> ChainstateManager::BlocksAheadOfTip() const
6286
20
{
6287
20
    LOCK(::cs_main);
6288
20
    const CBlockIndex* best_header{m_best_header};
6289
20
    const CBlockIndex* tip{ActiveChain().Tip()};
6290
    // Only consider headers that extend the active tip; ignore competing branches.
6291
20
    if (best_header && tip && best_header->nChainWork > tip->nChainWork &&
6292
20
        best_header->GetAncestor(tip->nHeight) == tip) {
6293
2
        return best_header->nHeight - tip->nHeight;
6294
2
    }
6295
18
    return std::nullopt;
6296
20
}
6297
6298
bool ChainstateManager::ValidatedSnapshotCleanup(Chainstate& validated_cs, Chainstate& unvalidated_cs)
6299
3
{
6300
3
    AssertLockHeld(::cs_main);
6301
3
    if (unvalidated_cs.m_assumeutxo != Assumeutxo::VALIDATED) {
6302
        // No need to clean up.
6303
0
        return false;
6304
0
    }
6305
6306
3
    const fs::path validated_path{validated_cs.StoragePath()};
6307
3
    const fs::path assumed_valid_path{unvalidated_cs.StoragePath()};
6308
3
    const fs::path delete_path{validated_path + "_todelete"};
6309
6310
    // Since we're going to be moving around the underlying leveldb filesystem content
6311
    // for each chainstate, make sure that the chainstates (and their constituent
6312
    // CoinsViews members) have been destructed first.
6313
    //
6314
    // The caller of this method will be responsible for reinitializing chainstates
6315
    // if they want to continue operation.
6316
3
    this->ResetChainstates();
6317
3
    assert(this->m_chainstates.size() == 0);
6318
6319
3
    LogInfo("[snapshot] deleting background chainstate directory (now unnecessary) (%s)",
6320
3
              fs::PathToString(validated_path));
6321
6322
3
    auto rename_failed_abort = [this](
6323
3
                                   fs::path p_old,
6324
3
                                   fs::path p_new,
6325
3
                                   const fs::filesystem_error& err) {
6326
0
        LogError("[snapshot] Error renaming path (%s) -> (%s): %s\n",
6327
0
                  fs::PathToString(p_old), fs::PathToString(p_new), err.what());
6328
0
        GetNotifications().fatalError(strprintf(_(
6329
0
            "Rename of '%s' -> '%s' failed. "
6330
0
            "Cannot clean up the background chainstate leveldb directory."),
6331
0
            fs::PathToString(p_old), fs::PathToString(p_new)));
6332
0
    };
6333
6334
3
    try {
6335
3
        fs::rename(validated_path, delete_path);
6336
3
    } catch (const fs::filesystem_error& e) {
6337
0
        rename_failed_abort(validated_path, delete_path, e);
6338
0
        throw;
6339
0
    }
6340
6341
3
    LogInfo("[snapshot] moving snapshot chainstate (%s) to "
6342
3
              "default chainstate directory (%s)",
6343
3
              fs::PathToString(assumed_valid_path), fs::PathToString(validated_path));
6344
6345
3
    try {
6346
3
        fs::rename(assumed_valid_path, validated_path);
6347
3
    } catch (const fs::filesystem_error& e) {
6348
0
        rename_failed_abort(assumed_valid_path, validated_path, e);
6349
0
        throw;
6350
0
    }
6351
6352
3
    if (!DeleteCoinsDBFromDisk(delete_path, /*is_snapshot=*/false)) {
6353
        // No need to FatalError because once the unneeded bg chainstate data is
6354
        // moved, it will not interfere with subsequent initialization.
6355
0
        LogWarning("Deletion of %s failed. Please remove it manually, as the "
6356
0
                   "directory is now unnecessary.",
6357
0
                   fs::PathToString(delete_path));
6358
3
    } else {
6359
3
        LogInfo("[snapshot] deleted background chainstate directory (%s)",
6360
3
                fs::PathToString(validated_path));
6361
3
    }
6362
3
    return true;
6363
3
}
6364
6365
std::pair<int, int> Chainstate::GetPruneRange(int last_height_can_prune) const
6366
119
{
6367
119
    if (m_chain.Height() <= 0) {
6368
0
        return {0, 0};
6369
0
    }
6370
119
    int prune_start{0};
6371
6372
119
    if (m_from_snapshot_blockhash && m_assumeutxo != Assumeutxo::VALIDATED) {
6373
        // Only prune blocks _after_ the snapshot if this is a snapshot chain
6374
        // that has not been fully validated yet. The earlier blocks need to be
6375
        // kept to validate the snapshot
6376
12
        prune_start = Assert(SnapshotBase())->nHeight + 1;
6377
12
    }
6378
6379
119
    int max_prune = std::max<int>(
6380
119
        0, m_chain.Height() - static_cast<int>(MIN_BLOCKS_TO_KEEP));
6381
6382
    // last block to prune is the lesser of (caller-specified height, MIN_BLOCKS_TO_KEEP from the tip)
6383
    //
6384
    // While you might be tempted to prune the background chainstate more
6385
    // aggressively (i.e. fewer MIN_BLOCKS_TO_KEEP), this won't work with index
6386
    // building - specifically blockfilterindex requires undo data, and if
6387
    // we don't maintain this trailing window, we hit indexing failures.
6388
119
    int prune_end = std::min(last_height_can_prune, max_prune);
6389
6390
119
    return {prune_start, prune_end};
6391
119
}
6392
6393
std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> ChainstateManager::GetHistoricalBlockRange() const
6394
347k
{
6395
347k
    const Chainstate* chainstate{HistoricalChainstate()};
6396
347k
    if (!chainstate) return {};
6397
1.56k
    return std::make_pair(chainstate->m_chain.Tip(), chainstate->TargetBlock());
6398
347k
}
6399
6400
util::Result<void> ChainstateManager::ActivateBestChains()
6401
1.06k
{
6402
    // We can't hold cs_main during ActivateBestChain even though we're accessing
6403
    // the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
6404
    // the relevant pointers before the ABC call.
6405
1.06k
    AssertLockNotHeld(cs_main);
6406
1.06k
    std::vector<Chainstate*> chainstates;
6407
1.06k
    {
6408
1.06k
        LOCK(GetMutex());
6409
1.06k
        chainstates.reserve(m_chainstates.size());
6410
1.06k
        for (const auto& chainstate : m_chainstates) {
6411
1.06k
            if (chainstate && chainstate->m_assumeutxo != Assumeutxo::INVALID && !chainstate->m_target_utxohash) {
6412
1.06k
                chainstates.push_back(chainstate.get());
6413
1.06k
            }
6414
1.06k
        }
6415
1.06k
    }
6416
1.06k
    for (Chainstate* chainstate : chainstates) {
6417
1.06k
        BlockValidationState state;
6418
1.06k
        if (!chainstate->ActivateBestChain(state, nullptr)) {
6419
0
            LOCK(GetMutex());
6420
0
            return util::Error{Untranslated(strprintf("%s Failed to connect best block (%s)", chainstate->ToString(), state.ToString()))};
6421
0
        }
6422
1.06k
    }
6423
1.06k
    return {};
6424
1.06k
}