Bitcoin ABC 0.32.6
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2018 The Bitcoin Core developers
3// Copyright (c) 2017-2020 The Bitcoin developers
4// Distributed under the MIT software license, see the accompanying
5// file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7#include <validation.h>
8
9#include <kernel/chain.h>
10#include <kernel/chainparams.h>
11#include <kernel/coinstats.h>
15
16#include <arith_uint256.h>
17#include <avalanche/avalanche.h>
18#include <avalanche/processor.h>
19#include <blockvalidity.h>
20#include <chainparams.h>
21#include <checkpoints.h>
22#include <checkqueue.h>
23#include <config.h>
25#include <consensus/amount.h>
26#include <consensus/merkle.h>
27#include <consensus/tx_check.h>
28#include <consensus/tx_verify.h>
30#include <hash.h>
32#include <logging.h>
33#include <logging/timer.h>
34#include <minerfund.h>
35#include <node/blockstorage.h>
36#include <node/utxo_snapshot.h>
39#include <policy/block/rtt.h>
41#include <policy/policy.h>
42#include <policy/settings.h>
43#include <pow/pow.h>
44#include <primitives/block.h>
46#include <random.h>
47#include <reverse_iterator.h>
48#include <script/script.h>
49#include <script/scriptcache.h>
50#include <script/sigcache.h>
51#include <shutdown.h>
52#include <tinyformat.h>
53#include <txdb.h>
54#include <txmempool.h>
55#include <undo.h>
56#include <util/check.h>
57#include <util/fs.h>
58#include <util/fs_helpers.h>
60#include <util/strencodings.h>
61#include <util/string.h>
62#include <util/time.h>
63#include <util/trace.h>
64#include <util/translation.h>
65#include <validationinterface.h>
66#include <warnings.h>
67
68#include <algorithm>
69#include <atomic>
70#include <cassert>
71#include <chrono>
72#include <deque>
73#include <numeric>
74#include <optional>
75#include <string>
76#include <thread>
77#include <tuple>
78
84
87using node::BlockMap;
88using node::fReindex;
90
92static constexpr size_t WARN_FLUSH_COINS_SIZE = 1 << 30;
99static constexpr auto DATABASE_WRITE_INTERVAL_MIN{50min};
100static constexpr auto DATABASE_WRITE_INTERVAL_MAX{70min};
101const std::vector<std::string> CHECKLEVEL_DOC{
102 "level 0 reads the blocks from disk",
103 "level 1 verifies block validity",
104 "level 2 verifies undo data",
105 "level 3 checks disconnection of tip blocks",
106 "level 4 tries to reconnect the blocks",
107 "each level includes the checks of the previous levels",
108};
115static constexpr int PRUNE_LOCK_BUFFER{10};
116
117static constexpr uint64_t HEADERS_TIME_VERSION{1};
118
120std::condition_variable g_best_block_cv;
122
124 : excessiveBlockSize(config.GetMaxBlockSize()), checkPoW(true),
125 checkMerkleRoot(true) {}
126
127const CBlockIndex *
130
131 // Find the latest block common to locator and chain - we expect that
132 // locator.vHave is sorted descending by height.
133 for (const BlockHash &hash : locator.vHave) {
134 const CBlockIndex *pindex{m_blockman.LookupBlockIndex(hash)};
135 if (pindex) {
136 if (m_chain.Contains(pindex)) {
137 return pindex;
138 }
139 if (pindex->GetAncestor(m_chain.Height()) == m_chain.Tip()) {
140 return m_chain.Tip();
141 }
142 }
143 }
144 return m_chain.Genesis();
145}
146
147static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex,
148 const ChainstateManager &chainman);
149
150namespace {
162std::optional<std::vector<int>> CalculatePrevHeights(const CBlockIndex &tip,
163 const CCoinsView &coins,
164 const CTransaction &tx) {
165 std::vector<int> prev_heights;
166 prev_heights.resize(tx.vin.size());
167 for (size_t i = 0; i < tx.vin.size(); ++i) {
168 const CTxIn &txin = tx.vin[i];
169 Coin coin;
170 if (!coins.GetCoin(txin.prevout, coin)) {
171 LogPrintf("ERROR: %s: Missing input %d in transaction \'%s\'\n",
172 __func__, i, tx.GetId().GetHex());
173 return std::nullopt;
174 }
175 if (coin.GetHeight() == MEMPOOL_HEIGHT) {
176 // Assume all mempool transaction confirm in the next block.
177 prev_heights[i] = tip.nHeight + 1;
178 } else {
179 prev_heights[i] = coin.GetHeight();
180 }
181 }
182 return prev_heights;
183}
184} // namespace
185
186std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
187 const CCoinsView &coins_view,
188 const CTransaction &tx) {
189 assert(tip);
190
191 auto prev_heights{CalculatePrevHeights(*tip, coins_view, tx)};
192 if (!prev_heights.has_value()) {
193 return std::nullopt;
194 }
195
196 CBlockIndex next_tip;
197 next_tip.pprev = tip;
198 // When SequenceLocks() is called within ConnectBlock(), the height
199 // of the block *being* evaluated is what is used.
200 // Thus if we want to know if a transaction can be part of the
201 // *next* block, we need to use one more than
202 // active_chainstate.m_chain.Height()
203 next_tip.nHeight = tip->nHeight + 1;
204 const auto [min_height, min_time] = CalculateSequenceLocks(
205 tx, STANDARD_LOCKTIME_VERIFY_FLAGS, prev_heights.value(), next_tip);
206
207 return LockPoints{min_height, min_time};
208}
209
210bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points) {
211 assert(tip != nullptr);
212
213 CBlockIndex index;
214 index.pprev = tip;
215 // CheckSequenceLocksAtTip() uses active_chainstate.m_chain.Height()+1 to
216 // evaluate height based locks because when SequenceLocks() is called within
217 // ConnectBlock(), the height of the block *being* evaluated is what is
218 // used. Thus if we want to know if a transaction can be part of the *next*
219 // block, we need to use one more than active_chainstate.m_chain.Height()
220 index.nHeight = tip->nHeight + 1;
221
222 return EvaluateSequenceLocks(index, {lock_points.height, lock_points.time});
223}
224
225// Command-line argument "-replayprotectionactivationtime=<timestamp>" will
226// cause the node to switch to replay protected SigHash ForkID value when the
227// median timestamp of the previous 11 blocks is greater than or equal to
228// <timestamp>. Defaults to the pre-defined timestamp when not set.
229static bool
231 const CBlockIndex *pindexPrev,
232 const std::optional<int64_t> activation_time) {
233 if (pindexPrev == nullptr) {
234 return false;
235 }
236
237 return pindexPrev->GetMedianTimePast() >=
238 activation_time.value_or(params.obolenskyActivationTime);
239}
240
247 const CTransaction &tx, TxValidationState &state,
248 const CCoinsViewCache &view, const CTxMemPool &pool, const uint32_t flags,
249 PrecomputedTransactionData &txdata, ValidationCache &validation_cache,
250 int &nSigChecksOut, CCoinsViewCache &coins_tip)
254
255 assert(!tx.IsCoinBase());
256 for (const CTxIn &txin : tx.vin) {
257 const Coin &coin = view.AccessCoin(txin.prevout);
258
259 // This coin was checked in PreChecks and MemPoolAccept
260 // has been holding cs_main since then.
261 Assume(!coin.IsSpent());
262 if (coin.IsSpent()) {
263 return false;
264 }
265
266 // If the Coin is available, there are 2 possibilities:
267 // it is available in our current ChainstateActive UTXO set,
268 // or it's a UTXO provided by a transaction in our mempool.
269 // Ensure the scriptPubKeys in Coins from CoinsView are correct.
270 const CTransactionRef &txFrom = pool.get(txin.prevout.GetTxId());
271 if (txFrom) {
272 assert(txFrom->GetId() == txin.prevout.GetTxId());
273 assert(txFrom->vout.size() > txin.prevout.GetN());
274 assert(txFrom->vout[txin.prevout.GetN()] == coin.GetTxOut());
275 } else {
276 const Coin &coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
277 assert(!coinFromUTXOSet.IsSpent());
278 assert(coinFromUTXOSet.GetTxOut() == coin.GetTxOut());
279 }
280 }
281
282 // Call CheckInputScripts() to cache signature and script validity against
283 // current tip consensus rules.
284 return CheckInputScripts(tx, state, view, flags, /*sigCacheStore=*/true,
285 /*scriptCacheStore=*/true, txdata,
286 validation_cache, nSigChecksOut);
287}
288
289namespace {
290
291class MemPoolAccept {
292public:
293 MemPoolAccept(CTxMemPool &mempool, Chainstate &active_chainstate)
294 : m_pool(mempool), m_view(&m_dummy),
295 m_viewmempool(&active_chainstate.CoinsTip(), m_pool),
296 m_active_chainstate(active_chainstate) {}
297
298 // We put the arguments we're handed into a struct, so we can pass them
299 // around easier.
300 struct ATMPArgs {
301 const Config &m_config;
302 const int64_t m_accept_time;
303 const bool m_bypass_limits;
304 /*
305 * Return any outpoints which were not previously present in the coins
306 * cache, but were added as a result of validating the tx for mempool
307 * acceptance. This allows the caller to optionally remove the cache
308 * additions if the associated transaction ends up being rejected by
309 * the mempool.
310 */
311 std::vector<COutPoint> &m_coins_to_uncache;
312 const bool m_test_accept;
313 const unsigned int m_heightOverride;
319 const bool m_package_submission;
325 const bool m_package_feerates;
326
328 static ATMPArgs SingleAccept(const Config &config, int64_t accept_time,
329 bool bypass_limits,
330 std::vector<COutPoint> &coins_to_uncache,
331 bool test_accept,
332 unsigned int heightOverride) {
333 return ATMPArgs{
334 config,
335 accept_time,
336 bypass_limits,
337 coins_to_uncache,
338 test_accept,
339 heightOverride,
340 /*package_submission=*/false,
341 /*package_feerates=*/false,
342 };
343 }
344
349 static ATMPArgs
350 PackageTestAccept(const Config &config, int64_t accept_time,
351 std::vector<COutPoint> &coins_to_uncache) {
352 return ATMPArgs{
353 config,
354 accept_time,
355 /*bypass_limits=*/false,
356 coins_to_uncache,
357 /*test_accept=*/true,
358 /*height_override=*/0,
359 // not submitting to mempool
360 /*package_submission=*/false,
361 /*package_feerates=*/false,
362 };
363 }
364
366 static ATMPArgs
367 PackageChildWithParents(const Config &config, int64_t accept_time,
368 std::vector<COutPoint> &coins_to_uncache) {
369 return ATMPArgs{
370 config,
371 accept_time,
372 /*bypass_limits=*/false,
373 coins_to_uncache,
374 /*test_accept=*/false,
375 /*height_override=*/0,
376 /*package_submission=*/true,
377 /*package_feerates=*/true,
378 };
379 }
380
382 static ATMPArgs SingleInPackageAccept(const ATMPArgs &package_args) {
383 return ATMPArgs{
384 /*config=*/package_args.m_config,
385 /*accept_time=*/package_args.m_accept_time,
386 /*bypass_limits=*/false,
387 /*coins_to_uncache=*/package_args.m_coins_to_uncache,
388 /*test_accept=*/package_args.m_test_accept,
389 /*height_override=*/package_args.m_heightOverride,
390 // do not LimitMempoolSize in Finalize()
391 /*package_submission=*/true,
392 // only 1 transaction
393 /*package_feerates=*/false,
394 };
395 }
396
397 private:
398 // Private ctor to avoid exposing details to clients and allowing the
399 // possibility of mixing up the order of the arguments. Use static
400 // functions above instead.
401 ATMPArgs(const Config &config, int64_t accept_time, bool bypass_limits,
402 std::vector<COutPoint> &coins_to_uncache, bool test_accept,
403 unsigned int height_override, bool package_submission,
404 bool package_feerates)
405 : m_config{config}, m_accept_time{accept_time},
406 m_bypass_limits{bypass_limits},
407 m_coins_to_uncache{coins_to_uncache}, m_test_accept{test_accept},
408 m_heightOverride{height_override},
409 m_package_submission{package_submission},
410 m_package_feerates(package_feerates) {}
411 };
412
413 // Single transaction acceptance
414 MempoolAcceptResult AcceptSingleTransaction(const CTransactionRef &ptx,
415 ATMPArgs &args)
417
425 AcceptMultipleTransactions(const std::vector<CTransactionRef> &txns,
426 ATMPArgs &args)
428
442 AcceptSubPackage(const std::vector<CTransactionRef> &subpackage,
443 ATMPArgs &args)
445
451 PackageMempoolAcceptResult AcceptPackage(const Package &package,
452 ATMPArgs &args)
454
455private:
456 // All the intermediate state that gets passed between the various levels
457 // of checking a given transaction.
458 struct Workspace {
459 Workspace(const CTransactionRef &ptx,
460 const uint32_t next_block_script_verify_flags)
461 : m_ptx(ptx),
462 m_next_block_script_verify_flags(next_block_script_verify_flags) {
463 }
469 std::unique_ptr<CTxMemPoolEntry> m_entry;
470
475 int64_t m_vsize;
480 Amount m_base_fees;
481
486 Amount m_modified_fees;
487
494 CFeeRate m_package_feerate{Amount::zero()};
495
496 const CTransactionRef &m_ptx;
497 TxValidationState m_state;
503 PrecomputedTransactionData m_precomputed_txdata;
504
505 // ABC specific flags that are used in both PreChecks and
506 // ConsensusScriptChecks
507 const uint32_t m_next_block_script_verify_flags;
508 int m_sig_checks_standard;
509 };
510
511 // Run the policy checks on a given transaction, excluding any script
512 // checks. Looks up inputs, calculates feerate, considers replacement,
513 // evaluates package limits, etc. As this function can be invoked for "free"
514 // by a peer, only tests that are fast should be done here (to avoid CPU
515 // DoS).
516 bool PreChecks(ATMPArgs &args, Workspace &ws)
518
519 // Re-run the script checks, using consensus flags, and try to cache the
520 // result in the scriptcache. This should be done after
521 // PolicyScriptChecks(). This requires that all inputs either be in our
522 // utxo set or in the mempool.
523 bool ConsensusScriptChecks(const ATMPArgs &args, Workspace &ws)
525
526 // Try to add the transaction to the mempool, removing any conflicts first.
527 // Returns true if the transaction is in the mempool after any size
528 // limiting is performed, false otherwise.
529 bool Finalize(const ATMPArgs &args, Workspace &ws)
531
532 // Submit all transactions to the mempool and call ConsensusScriptChecks to
533 // add to the script cache - should only be called after successful
534 // validation of all transactions in the package.
535 // Does not call LimitMempoolSize(), so mempool max_size_bytes may be
536 // temporarily exceeded.
537 bool SubmitPackage(const ATMPArgs &args, std::vector<Workspace> &workspaces,
538 PackageValidationState &package_state,
539 std::map<TxId, MempoolAcceptResult> &results)
541
542 // Compare a package's feerate against minimum allowed.
543 bool CheckFeeRate(size_t package_size, size_t package_vsize,
544 Amount package_fee, TxValidationState &state)
547 AssertLockHeld(m_pool.cs);
548
549 const Amount mempoolRejectFee =
550 m_pool.GetMinFee().GetFee(package_vsize);
551
552 if (mempoolRejectFee > Amount::zero() &&
553 package_fee < mempoolRejectFee) {
554 return state.Invalid(
556 "mempool min fee not met",
557 strprintf("%d < %d", package_fee, mempoolRejectFee));
558 }
559
560 // Do not change this to use virtualsize without coordinating a network
561 // policy upgrade.
562 if (package_fee < m_pool.m_min_relay_feerate.GetFee(package_size)) {
563 return state.Invalid(
565 "min relay fee not met",
566 strprintf("%d < %d", package_fee,
567 m_pool.m_min_relay_feerate.GetFee(package_size)));
568 }
569
570 return true;
571 }
572
573 ValidationCache &GetValidationCache() {
574 return m_active_chainstate.m_chainman.m_validation_cache;
575 }
576
577private:
578 CTxMemPool &m_pool;
579 CCoinsViewCache m_view;
580 CCoinsViewMemPool m_viewmempool;
581 CCoinsView m_dummy;
582
583 Chainstate &m_active_chainstate;
584};
585
586bool MemPoolAccept::PreChecks(ATMPArgs &args, Workspace &ws) {
588 AssertLockHeld(m_pool.cs);
589 const CTransactionRef &ptx = ws.m_ptx;
590 const CTransaction &tx = *ws.m_ptx;
591 const TxId &txid = ws.m_ptx->GetId();
592
593 // Copy/alias what we need out of args
594 const int64_t nAcceptTime = args.m_accept_time;
595 const bool bypass_limits = args.m_bypass_limits;
596 std::vector<COutPoint> &coins_to_uncache = args.m_coins_to_uncache;
597 const unsigned int heightOverride = args.m_heightOverride;
598
599 // Alias what we need out of ws
600 TxValidationState &state = ws.m_state;
601 // Coinbase is only valid in a block, not as a loose transaction.
602 if (!CheckRegularTransaction(tx, state)) {
603 // state filled in by CheckRegularTransaction.
604 return false;
605 }
606
607 // Rather not work on nonstandard transactions (unless -testnet)
608 std::string reason;
609 if (m_pool.m_require_standard &&
610 !IsStandardTx(tx, m_pool.m_max_datacarrier_bytes,
611 m_pool.m_permit_bare_multisig,
612 m_pool.m_dust_relay_feerate, reason)) {
613 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
614 }
615
616 // Only accept nLockTime-using transactions that can be mined in the next
617 // block; we don't want our mempool filled up with transactions that can't
618 // be mined yet.
619 TxValidationState ctxState;
621 *Assert(m_active_chainstate.m_chain.Tip()),
622 args.m_config.GetChainParams().GetConsensus(), tx, ctxState)) {
623 // We copy the state from a dummy to ensure we don't increase the
624 // ban score of peer for transaction that could be valid in the future.
626 ctxState.GetRejectReason(),
627 ctxState.GetDebugMessage());
628 }
629
630 // Is it already in the memory pool?
631 if (m_pool.exists(txid)) {
633 "txn-already-in-mempool");
634 }
635
636 // Check for conflicts with in-memory transactions
637 for (const CTxIn &txin : tx.vin) {
638 if (const auto ptxConflicting = m_pool.GetConflictTx(txin.prevout)) {
639 if (m_pool.isAvalancheFinalizedPreConsensus(
640 ptxConflicting->GetId())) {
642 "finalized-tx-conflict");
643 }
644
645 return state.Invalid(
647 "txn-mempool-conflict");
648 }
649 }
650
651 m_view.SetBackend(m_viewmempool);
652
653 const CCoinsViewCache &coins_cache = m_active_chainstate.CoinsTip();
654 // Do all inputs exist?
655 for (const CTxIn &txin : tx.vin) {
656 if (!coins_cache.HaveCoinInCache(txin.prevout)) {
657 coins_to_uncache.push_back(txin.prevout);
658 }
659
660 // Note: this call may add txin.prevout to the coins cache
661 // (coins_cache.cacheCoins) by way of FetchCoin(). It should be
662 // removed later (via coins_to_uncache) if this tx turns out to be
663 // invalid.
664 if (!m_view.HaveCoin(txin.prevout)) {
665 // Are inputs missing because we already have the tx?
666 for (size_t out = 0; out < tx.vout.size(); out++) {
667 // Optimistically just do efficient check of cache for
668 // outputs.
669 if (coins_cache.HaveCoinInCache(COutPoint(txid, out))) {
671 "txn-already-known");
672 }
673 }
674
675 // Otherwise assume this might be an orphan tx for which we just
676 // haven't seen parents yet.
678 "bad-txns-inputs-missingorspent");
679 }
680 }
681
682 // Are the actual inputs available?
683 if (!m_view.HaveInputs(tx)) {
685 "bad-txns-inputs-spent");
686 }
687
688 // Bring the best block into scope.
689 m_view.GetBestBlock();
690
691 // we have all inputs cached now, so switch back to dummy (to protect
692 // against bugs where we pull more inputs from disk that miss being
693 // added to coins_to_uncache)
694 m_view.SetBackend(m_dummy);
695
696 assert(m_active_chainstate.m_blockman.LookupBlockIndex(
697 m_view.GetBestBlock()) == m_active_chainstate.m_chain.Tip());
698
699 // Only accept BIP68 sequence locked transactions that can be mined in
700 // the next block; we don't want our mempool filled up with transactions
701 // that can't be mined yet.
702 // Pass in m_view which has all of the relevant inputs cached. Note that,
703 // since m_view's backend was removed, it no longer pulls coins from the
704 // mempool.
705 const std::optional<LockPoints> lock_points{CalculateLockPointsAtTip(
706 m_active_chainstate.m_chain.Tip(), m_view, tx)};
707 if (!lock_points.has_value() ||
708 !CheckSequenceLocksAtTip(m_active_chainstate.m_chain.Tip(),
709 *lock_points)) {
711 "non-BIP68-final");
712 }
713
714 // The mempool holds txs for the next block, so pass height+1 to
715 // CheckTxInputs
716 if (!Consensus::CheckTxInputs(tx, state, m_view,
717 m_active_chainstate.m_chain.Height() + 1,
718 ws.m_base_fees)) {
719 // state filled in by CheckTxInputs
720 return false;
721 }
722
723 // Check for non-standard pay-to-script-hash in inputs
724 if (m_pool.m_require_standard &&
725 !AreInputsStandard(tx, m_view, ws.m_next_block_script_verify_flags)) {
727 "bad-txns-nonstandard-inputs");
728 }
729
730 // ws.m_modified_fess includes any fee deltas from PrioritiseTransaction
731 ws.m_modified_fees = ws.m_base_fees;
732 m_pool.ApplyDelta(txid, ws.m_modified_fees);
733
734 unsigned int nSize = tx.GetTotalSize();
735
736 // Validate input scripts against standard script flags.
737 const uint32_t scriptVerifyFlags =
738 ws.m_next_block_script_verify_flags | STANDARD_SCRIPT_VERIFY_FLAGS;
739 ws.m_precomputed_txdata = PrecomputedTransactionData{tx};
740 if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false,
741 ws.m_precomputed_txdata, GetValidationCache(),
742 ws.m_sig_checks_standard)) {
743 // State filled in by CheckInputScripts
744 return false;
745 }
746
747 ws.m_entry = std::make_unique<CTxMemPoolEntry>(
748 ptx, ws.m_base_fees, nAcceptTime,
749 heightOverride ? heightOverride : m_active_chainstate.m_chain.Height(),
750 ws.m_sig_checks_standard, lock_points.value());
751
752 ws.m_vsize = ws.m_entry->GetTxVirtualSize();
753
754 // No individual transactions are allowed below the min relay feerate except
755 // from disconnected blocks. This requirement, unlike CheckFeeRate, cannot
756 // be bypassed using m_package_feerates because, while a tx could be package
757 // CPFP'd when entering the mempool, we do not have a DoS-resistant method
758 // of ensuring the tx remains bumped. For example, the fee-bumping child
759 // could disappear due to a replacement.
760 if (!bypass_limits &&
761 ws.m_modified_fees <
762 m_pool.m_min_relay_feerate.GetFee(ws.m_ptx->GetTotalSize())) {
763 // Even though this is a fee-related failure, this result is
764 // TX_MEMPOOL_POLICY, not TX_PACKAGE_RECONSIDERABLE, because it cannot
765 // be bypassed using package validation.
766 return state.Invalid(
767 TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met",
768 strprintf("%d < %d", ws.m_modified_fees,
769 m_pool.m_min_relay_feerate.GetFee(nSize)));
770 }
771 // No individual transactions are allowed below the mempool min feerate
772 // except from disconnected blocks and transactions in a package. Package
773 // transactions will be checked using package feerate later.
774 if (!bypass_limits && !args.m_package_feerates &&
775 !CheckFeeRate(nSize, ws.m_vsize, ws.m_modified_fees, state)) {
776 return false;
777 }
778
779 return true;
780}
781
782bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs &args, Workspace &ws) {
784 AssertLockHeld(m_pool.cs);
785 const CTransaction &tx = *ws.m_ptx;
786 const TxId &txid = tx.GetId();
787 TxValidationState &state = ws.m_state;
788
789 // Check again against the next block's script verification flags
790 // to cache our script execution flags.
791 //
792 // This is also useful in case of bugs in the standard flags that cause
793 // transactions to pass as valid when they're actually invalid. For
794 // instance the STRICTENC flag was incorrectly allowing certain CHECKSIG
795 // NOT scripts to pass, even though they were invalid.
796 //
797 // There is a similar check in CreateNewBlock() to prevent creating
798 // invalid blocks (using TestBlockValidity), however allowing such
799 // transactions into the mempool can be exploited as a DoS attack.
800 int nSigChecksConsensus;
802 tx, state, m_view, m_pool, ws.m_next_block_script_verify_flags,
803 ws.m_precomputed_txdata, GetValidationCache(), nSigChecksConsensus,
804 m_active_chainstate.CoinsTip())) {
805 // This can occur under some circumstances, if the node receives an
806 // unrequested tx which is invalid due to new consensus rules not
807 // being activated yet (during IBD).
808 LogPrintf("BUG! PLEASE REPORT THIS! CheckInputScripts failed against "
809 "latest-block but not STANDARD flags %s, %s\n",
810 txid.ToString(), state.ToString());
811 return Assume(false);
812 }
813
814 if (ws.m_sig_checks_standard != nSigChecksConsensus) {
815 // We can't accept this transaction as we've used the standard count
816 // for the mempool/mining, but the consensus count will be enforced
817 // in validation (we don't want to produce bad block templates).
818 LogError(
819 "%s: BUG! PLEASE REPORT THIS! SigChecks count differed between "
820 "standard and consensus flags in %s\n",
821 __func__, txid.ToString());
822 return false;
823 }
824 return true;
825}
826
827bool MemPoolAccept::Finalize(const ATMPArgs &args, Workspace &ws) {
829 AssertLockHeld(m_pool.cs);
830 const TxId &txid = ws.m_ptx->GetId();
831 TxValidationState &state = ws.m_state;
832 const bool bypass_limits = args.m_bypass_limits;
833
834 // Store transaction in memory
835 CTxMemPoolEntry *pentry = ws.m_entry.release();
836 auto entry = CTxMemPoolEntryRef::acquire(pentry);
837 m_pool.addUnchecked(entry);
838
840 ws.m_ptx,
841 std::make_shared<const std::vector<Coin>>(
842 GetSpentCoins(ws.m_ptx, m_view)),
843 m_pool.GetAndIncrementSequence());
844
845 // Trim mempool and check if tx was trimmed.
846 // If we are validating a package, don't trim here because we could evict a
847 // previous transaction in the package. LimitMempoolSize() should be called
848 // at the very end to make sure the mempool is still within limits and
849 // package submission happens atomically.
850 if (!args.m_package_submission && !bypass_limits) {
851 m_pool.LimitSize(m_active_chainstate.CoinsTip());
852 if (!m_pool.exists(txid)) {
853 // The tx no longer meets our (new) mempool minimum feerate but
854 // could be reconsidered in a package.
856 "mempool full");
857 }
858 }
859 return true;
860}
861
862bool MemPoolAccept::SubmitPackage(
863 const ATMPArgs &args, std::vector<Workspace> &workspaces,
864 PackageValidationState &package_state,
865 std::map<TxId, MempoolAcceptResult> &results) {
867 AssertLockHeld(m_pool.cs);
868 // Sanity check: none of the transactions should be in the mempool.
869 assert(std::all_of(
870 workspaces.cbegin(), workspaces.cend(),
871 [this](const auto &ws) { return !m_pool.exists(ws.m_ptx->GetId()); }));
872
873 bool all_submitted = true;
874 // ConsensusScriptChecks adds to the script cache and is therefore
875 // consensus-critical; CheckInputsFromMempoolAndCache asserts that
876 // transactions only spend coins available from the mempool or UTXO set.
877 // Submit each transaction to the mempool immediately after calling
878 // ConsensusScriptChecks to make the outputs available for subsequent
879 // transactions.
880 for (Workspace &ws : workspaces) {
881 if (!ConsensusScriptChecks(args, ws)) {
882 results.emplace(ws.m_ptx->GetId(),
883 MempoolAcceptResult::Failure(ws.m_state));
884 // Since PreChecks() passed, this should never fail.
885 all_submitted = false;
886 package_state.Invalid(
888 strprintf("BUG! PolicyScriptChecks succeeded but "
889 "ConsensusScriptChecks failed: %s",
890 ws.m_ptx->GetId().ToString()));
891 }
892
893 // If we call LimitMempoolSize() for each individual Finalize(), the
894 // mempool will not take the transaction's descendant feerate into
895 // account because it hasn't seen them yet. Also, we risk evicting a
896 // transaction that a subsequent package transaction depends on.
897 // Instead, allow the mempool to temporarily bypass limits, the maximum
898 // package size) while submitting transactions individually and then
899 // trim at the very end.
900 if (!Finalize(args, ws)) {
901 results.emplace(ws.m_ptx->GetId(),
902 MempoolAcceptResult::Failure(ws.m_state));
903 // Since LimitMempoolSize() won't be called, this should never fail.
904 all_submitted = false;
906 strprintf("BUG! Adding to mempool failed: %s",
907 ws.m_ptx->GetId().ToString()));
908 }
909 }
910
911 // It may or may not be the case that all the transactions made it into the
912 // mempool. Regardless, make sure we haven't exceeded max mempool size.
913 m_pool.LimitSize(m_active_chainstate.CoinsTip());
914
915 std::vector<TxId> all_package_txids;
916 all_package_txids.reserve(workspaces.size());
917 std::transform(workspaces.cbegin(), workspaces.cend(),
918 std::back_inserter(all_package_txids),
919 [](const auto &ws) { return ws.m_ptx->GetId(); });
920
921 // Add successful results. The returned results may change later if
922 // LimitMempoolSize() evicts them.
923 for (Workspace &ws : workspaces) {
924 const auto effective_feerate =
925 args.m_package_feerates
926 ? ws.m_package_feerate
927 : CFeeRate{ws.m_modified_fees,
928 static_cast<uint32_t>(ws.m_vsize)};
929 const auto effective_feerate_txids =
930 args.m_package_feerates ? all_package_txids
931 : std::vector<TxId>({ws.m_ptx->GetId()});
932 results.emplace(ws.m_ptx->GetId(),
933 MempoolAcceptResult::Success(ws.m_vsize, ws.m_base_fees,
934 effective_feerate,
935 effective_feerate_txids));
936 }
937 return all_submitted;
938}
939
941MemPoolAccept::AcceptSingleTransaction(const CTransactionRef &ptx,
942 ATMPArgs &args) {
944 // mempool "read lock" (held through
945 // GetMainSignals().TransactionAddedToMempool())
946 LOCK(m_pool.cs);
947
948 const CBlockIndex *tip = m_active_chainstate.m_chain.Tip();
949
950 Workspace ws(ptx,
951 GetNextBlockScriptFlags(tip, m_active_chainstate.m_chainman));
952
953 const std::vector<TxId> single_txid{ws.m_ptx->GetId()};
954
955 // Perform the inexpensive checks first and avoid hashing and signature
956 // verification unless those checks pass, to mitigate CPU exhaustion
957 // denial-of-service attacks.
958 if (!PreChecks(args, ws)) {
959 if (ws.m_state.GetResult() ==
961 // Failed for fee reasons. Provide the effective feerate and which
962 // tx was included.
964 ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize),
965 single_txid);
966 }
967 return MempoolAcceptResult::Failure(ws.m_state);
968 }
969
970 if (!ConsensusScriptChecks(args, ws)) {
971 return MempoolAcceptResult::Failure(ws.m_state);
972 }
973
974 const TxId txid = ptx->GetId();
975
976 // Mempool sanity check -- in our new mempool no tx can be added if its
977 // outputs are already spent in the mempool (that is, no children before
978 // parents allowed; the mempool must be consistent at all times).
979 //
980 // This means that on reorg, the disconnectpool *must* always import
981 // the existing mempool tx's, clear the mempool, and then re-add
982 // remaining tx's in topological order via this function. Our new mempool
983 // has fast adds, so this is ok.
984 if (auto it = m_pool.mapNextTx.lower_bound(COutPoint{txid, 0});
985 it != m_pool.mapNextTx.end() && it->first->GetTxId() == txid) {
986 LogPrintf("%s: BUG! PLEASE REPORT THIS! Attempt to add txid %s, but "
987 "its outputs are already spent in the "
988 "mempool\n",
989 __func__, txid.ToString());
991 "txn-child-before-parent");
992 return MempoolAcceptResult::Failure(ws.m_state);
993 }
994
995 const CFeeRate effective_feerate{ws.m_modified_fees,
996 static_cast<uint32_t>(ws.m_vsize)};
997 // Tx was accepted, but not added
998 if (args.m_test_accept) {
999 return MempoolAcceptResult::Success(ws.m_vsize, ws.m_base_fees,
1000 effective_feerate, single_txid);
1001 }
1002
1003 if (!Finalize(args, ws)) {
1004 // The only possible failure reason is fee-related (mempool full).
1005 // Failed for fee reasons. Provide the effective feerate and which txns
1006 // were included.
1007 Assume(ws.m_state.GetResult() ==
1010 ws.m_state, CFeeRate(ws.m_modified_fees, ws.m_vsize), single_txid);
1011 }
1012
1013 return MempoolAcceptResult::Success(ws.m_vsize, ws.m_base_fees,
1014 effective_feerate, single_txid);
1015}
1016
1017PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactions(
1018 const std::vector<CTransactionRef> &txns, ATMPArgs &args) {
1020
1021 // These context-free package limits can be done before taking the mempool
1022 // lock.
1023 PackageValidationState package_state;
1024 if (!CheckPackage(txns, package_state)) {
1025 return PackageMempoolAcceptResult(package_state, {});
1026 }
1027
1028 std::vector<Workspace> workspaces{};
1029 workspaces.reserve(txns.size());
1030 std::transform(
1031 txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
1032 [this](const auto &tx) {
1033 return Workspace(
1034 tx, GetNextBlockScriptFlags(m_active_chainstate.m_chain.Tip(),
1035 m_active_chainstate.m_chainman));
1036 });
1037 std::map<TxId, MempoolAcceptResult> results;
1038
1039 LOCK(m_pool.cs);
1040
1041 // Do all PreChecks first and fail fast to avoid running expensive script
1042 // checks when unnecessary.
1043 std::vector<TxId> valid_txids;
1044 for (Workspace &ws : workspaces) {
1045 if (!PreChecks(args, ws)) {
1047 "transaction failed");
1048 // Exit early to avoid doing pointless work. Update the failed tx
1049 // result; the rest are unfinished.
1050 results.emplace(ws.m_ptx->GetId(),
1051 MempoolAcceptResult::Failure(ws.m_state));
1052 return PackageMempoolAcceptResult(package_state,
1053 std::move(results));
1054 }
1055 // Make the coins created by this transaction available for subsequent
1056 // transactions in the package to spend.
1057 m_viewmempool.PackageAddTransaction(ws.m_ptx);
1058 valid_txids.push_back(ws.m_ptx->GetId());
1059 }
1060
1061 // Transactions must meet two minimum feerates: the mempool minimum fee and
1062 // min relay fee. For transactions consisting of exactly one child and its
1063 // parents, it suffices to use the package feerate
1064 // (total modified fees / total size or vsize) to check this requirement.
1065 // Note that this is an aggregate feerate; this function has not checked
1066 // that there are transactions too low feerate to pay for themselves, or
1067 // that the child transactions are higher feerate than their parents. Using
1068 // aggregate feerate may allow "parents pay for child" behavior and permit
1069 // a child that is below mempool minimum feerate. To avoid these behaviors,
1070 // callers of AcceptMultipleTransactions need to restrict txns topology
1071 // (e.g. to ancestor sets) and check the feerates of individuals and
1072 // subsets.
1073 const auto m_total_size = std::accumulate(
1074 workspaces.cbegin(), workspaces.cend(), int64_t{0},
1075 [](int64_t sum, auto &ws) { return sum + ws.m_ptx->GetTotalSize(); });
1076 const auto m_total_vsize =
1077 std::accumulate(workspaces.cbegin(), workspaces.cend(), int64_t{0},
1078 [](int64_t sum, auto &ws) { return sum + ws.m_vsize; });
1079 const auto m_total_modified_fees = std::accumulate(
1080 workspaces.cbegin(), workspaces.cend(), Amount::zero(),
1081 [](Amount sum, auto &ws) { return sum + ws.m_modified_fees; });
1082 const CFeeRate package_feerate(m_total_modified_fees, m_total_vsize);
1083 std::vector<TxId> all_package_txids;
1084 all_package_txids.reserve(workspaces.size());
1085 std::transform(workspaces.cbegin(), workspaces.cend(),
1086 std::back_inserter(all_package_txids),
1087 [](const auto &ws) { return ws.m_ptx->GetId(); });
1088 TxValidationState placeholder_state;
1089 if (args.m_package_feerates &&
1090 !CheckFeeRate(m_total_size, m_total_vsize, m_total_modified_fees,
1091 placeholder_state)) {
1093 "transaction failed");
1095 package_state, {{workspaces.back().m_ptx->GetId(),
1097 placeholder_state,
1098 CFeeRate(m_total_modified_fees, m_total_vsize),
1099 all_package_txids)}});
1100 }
1101
1102 for (Workspace &ws : workspaces) {
1103 ws.m_package_feerate = package_feerate;
1104 const TxId &ws_txid = ws.m_ptx->GetId();
1105 if (args.m_test_accept &&
1106 std::find(valid_txids.begin(), valid_txids.end(), ws_txid) !=
1107 valid_txids.end()) {
1108 const auto effective_feerate =
1109 args.m_package_feerates
1110 ? ws.m_package_feerate
1111 : CFeeRate{ws.m_modified_fees,
1112 static_cast<uint32_t>(ws.m_vsize)};
1113 const auto effective_feerate_txids =
1114 args.m_package_feerates ? all_package_txids
1115 : std::vector<TxId>{ws.m_ptx->GetId()};
1116 // When test_accept=true, transactions that pass PreChecks
1117 // are valid because there are no further mempool checks (passing
1118 // PreChecks implies passing ConsensusScriptChecks).
1119 results.emplace(ws_txid,
1121 ws.m_vsize, ws.m_base_fees, effective_feerate,
1122 effective_feerate_txids));
1123 }
1124 }
1125
1126 if (args.m_test_accept) {
1127 return PackageMempoolAcceptResult(package_state, std::move(results));
1128 }
1129
1130 if (!SubmitPackage(args, workspaces, package_state, results)) {
1131 // PackageValidationState filled in by SubmitPackage().
1132 return PackageMempoolAcceptResult(package_state, std::move(results));
1133 }
1134
1135 return PackageMempoolAcceptResult(package_state, std::move(results));
1136}
1137
1139MemPoolAccept::AcceptSubPackage(const std::vector<CTransactionRef> &subpackage,
1140 ATMPArgs &args) {
1142 AssertLockHeld(m_pool.cs);
1143
1144 auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main, m_pool.cs) {
1145 if (subpackage.size() > 1) {
1146 return AcceptMultipleTransactions(subpackage, args);
1147 }
1148 const auto &tx = subpackage.front();
1149 ATMPArgs single_args = ATMPArgs::SingleInPackageAccept(args);
1150 const auto single_res = AcceptSingleTransaction(tx, single_args);
1151 PackageValidationState package_state_wrapped;
1152 if (single_res.m_result_type !=
1154 package_state_wrapped.Invalid(PackageValidationResult::PCKG_TX,
1155 "transaction failed");
1156 }
1157 return PackageMempoolAcceptResult(package_state_wrapped,
1158 {{tx->GetId(), single_res}});
1159 }();
1160
1161 // Clean up m_view and m_viewmempool so that other subpackage evaluations
1162 // don't have access to coins they shouldn't. Keep some coins in order to
1163 // minimize re-fetching coins from the UTXO set.
1164 //
1165 // There are 3 kinds of coins in m_view:
1166 // (1) Temporary coins from the transactions in subpackage, constructed by
1167 // m_viewmempool.
1168 // (2) Mempool coins from transactions in the mempool, constructed by
1169 // m_viewmempool.
1170 // (3) Confirmed coins fetched from our current UTXO set.
1171 //
1172 // (1) Temporary coins need to be removed, regardless of whether the
1173 // transaction was submitted. If the transaction was submitted to the
1174 // mempool, m_viewmempool will be able to fetch them from there. If it
1175 // wasn't submitted to mempool, it is incorrect to keep them - future calls
1176 // may try to spend those coins that don't actually exist.
1177 // (2) Mempool coins also need to be removed. If the mempool contents have
1178 // changed as a result of submitting or replacing transactions, coins
1179 // previously fetched from mempool may now be spent or nonexistent. Those
1180 // coins need to be deleted from m_view.
1181 // (3) Confirmed coins don't need to be removed. The chainstate has not
1182 // changed (we are holding cs_main and no blocks have been processed) so the
1183 // confirmed tx cannot disappear like a mempool tx can. The coin may now be
1184 // spent after we submitted a tx to mempool, but we have already checked
1185 // that the package does not have 2 transactions spending the same coin.
1186 // Keeping them in m_view is an optimization to not re-fetch confirmed coins
1187 // if we later look up inputs for this transaction again.
1188 for (const auto &outpoint : m_viewmempool.GetNonBaseCoins()) {
1189 // In addition to resetting m_viewmempool, we also need to manually
1190 // delete these coins from m_view because it caches copies of the coins
1191 // it fetched from m_viewmempool previously.
1192 m_view.Uncache(outpoint);
1193 }
1194 // This deletes the temporary and mempool coins.
1195 m_viewmempool.Reset();
1196 return result;
1197}
1198
1199PackageMempoolAcceptResult MemPoolAccept::AcceptPackage(const Package &package,
1200 ATMPArgs &args) {
1202 // Used if returning a PackageMempoolAcceptResult directly from this
1203 // function.
1204 PackageValidationState package_state_quit_early;
1205
1206 // Check that the package is well-formed. If it isn't, we won't try to
1207 // validate any of the transactions and thus won't return any
1208 // MempoolAcceptResults, just a package-wide error.
1209
1210 // Context-free package checks.
1211 if (!CheckPackage(package, package_state_quit_early)) {
1212 return PackageMempoolAcceptResult(package_state_quit_early, {});
1213 }
1214
1215 // All transactions in the package must be a parent of the last transaction.
1216 // This is just an opportunity for us to fail fast on a context-free check
1217 // without taking the mempool lock.
1218 if (!IsChildWithParents(package)) {
1219 package_state_quit_early.Invalid(PackageValidationResult::PCKG_POLICY,
1220 "package-not-child-with-parents");
1221 return PackageMempoolAcceptResult(package_state_quit_early, {});
1222 }
1223
1224 // IsChildWithParents() guarantees the package is > 1 transactions.
1225 assert(package.size() > 1);
1226 // The package must be 1 child with all of its unconfirmed parents. The
1227 // package is expected to be sorted, so the last transaction is the child.
1228 const auto &child = package.back();
1229 std::unordered_set<TxId, SaltedTxIdHasher> unconfirmed_parent_txids;
1230 std::transform(
1231 package.cbegin(), package.cend() - 1,
1232 std::inserter(unconfirmed_parent_txids, unconfirmed_parent_txids.end()),
1233 [](const auto &tx) { return tx->GetId(); });
1234
1235 // All child inputs must refer to a preceding package transaction or a
1236 // confirmed UTXO. The only way to verify this is to look up the child's
1237 // inputs in our current coins view (not including mempool), and enforce
1238 // that all parents not present in the package be available at chain tip.
1239 // Since this check can bring new coins into the coins cache, keep track of
1240 // these coins and uncache them if we don't end up submitting this package
1241 // to the mempool.
1242 const CCoinsViewCache &coins_tip_cache = m_active_chainstate.CoinsTip();
1243 for (const auto &input : child->vin) {
1244 if (!coins_tip_cache.HaveCoinInCache(input.prevout)) {
1245 args.m_coins_to_uncache.push_back(input.prevout);
1246 }
1247 }
1248 // Using the MemPoolAccept m_view cache allows us to look up these same
1249 // coins faster later. This should be connecting directly to CoinsTip, not
1250 // to m_viewmempool, because we specifically require inputs to be confirmed
1251 // if they aren't in the package.
1252 m_view.SetBackend(m_active_chainstate.CoinsTip());
1253 const auto package_or_confirmed = [this, &unconfirmed_parent_txids](
1254 const auto &input) {
1255 return unconfirmed_parent_txids.count(input.prevout.GetTxId()) > 0 ||
1256 m_view.HaveCoin(input.prevout);
1257 };
1258 if (!std::all_of(child->vin.cbegin(), child->vin.cend(),
1259 package_or_confirmed)) {
1260 package_state_quit_early.Invalid(
1262 "package-not-child-with-unconfirmed-parents");
1263 return PackageMempoolAcceptResult(package_state_quit_early, {});
1264 }
1265 // Protect against bugs where we pull more inputs from disk that miss being
1266 // added to coins_to_uncache. The backend will be connected again when
1267 // needed in PreChecks.
1268 m_view.SetBackend(m_dummy);
1269
1270 LOCK(m_pool.cs);
1271 // Stores results from which we will create the returned
1272 // PackageMempoolAcceptResult. A result may be changed if a mempool
1273 // transaction is evicted later due to LimitMempoolSize().
1274 std::map<TxId, MempoolAcceptResult> results_final;
1275 // Results from individual validation which will be returned if no other
1276 // result is available for this transaction. "Nonfinal" because if a
1277 // transaction fails by itself but succeeds later (i.e. when evaluated with
1278 // a fee-bumping child), the result in this map may be discarded.
1279 std::map<TxId, MempoolAcceptResult> individual_results_nonfinal;
1280 bool quit_early{false};
1281 std::vector<CTransactionRef> txns_package_eval;
1282 for (const auto &tx : package) {
1283 const auto &txid = tx->GetId();
1284 // An already confirmed tx is treated as one not in mempool, because all
1285 // we know is that the inputs aren't available.
1286 if (m_pool.exists(txid)) {
1287 // Exact transaction already exists in the mempool.
1288 // Node operators are free to set their mempool policies however
1289 // they please, nodes may receive transactions in different orders,
1290 // and malicious counterparties may try to take advantage of policy
1291 // differences to pin or delay propagation of transactions. As such,
1292 // it's possible for some package transaction(s) to already be in
1293 // the mempool, and we don't want to reject the entire package in
1294 // that case (as that could be a censorship vector). De-duplicate
1295 // the transactions that are already in the mempool, and only call
1296 // AcceptMultipleTransactions() with the new transactions. This
1297 // ensures we don't double-count transaction counts and sizes when
1298 // checking ancestor/descendant limits, or double-count transaction
1299 // fees for fee-related policy.
1300 auto iter = m_pool.GetIter(txid);
1301 assert(iter != std::nullopt);
1302 results_final.emplace(txid, MempoolAcceptResult::MempoolTx(
1303 (*iter.value())->GetTxSize(),
1304 (*iter.value())->GetFee()));
1305 } else {
1306 // Transaction does not already exist in the mempool.
1307 // Try submitting the transaction on its own.
1308 const auto single_package_res = AcceptSubPackage({tx}, args);
1309 const auto &single_res = single_package_res.m_tx_results.at(txid);
1310 if (single_res.m_result_type ==
1312 // The transaction succeeded on its own and is now in the
1313 // mempool. Don't include it in package validation, because its
1314 // fees should only be "used" once.
1315 assert(m_pool.exists(txid));
1316 results_final.emplace(txid, single_res);
1317 } else if (single_res.m_state.GetResult() !=
1319 single_res.m_state.GetResult() !=
1321 // Package validation policy only differs from individual policy
1322 // in its evaluation of feerate. For example, if a transaction
1323 // fails here due to violation of a consensus rule, the result
1324 // will not change when it is submitted as part of a package. To
1325 // minimize the amount of repeated work, unless the transaction
1326 // fails due to feerate or missing inputs (its parent is a
1327 // previous transaction in the package that failed due to
1328 // feerate), don't run package validation. Note that this
1329 // decision might not make sense if different types of packages
1330 // are allowed in the future. Continue individually validating
1331 // the rest of the transactions, because some of them may still
1332 // be valid.
1333 quit_early = true;
1334 package_state_quit_early.Invalid(
1335 PackageValidationResult::PCKG_TX, "transaction failed");
1336 individual_results_nonfinal.emplace(txid, single_res);
1337 } else {
1338 individual_results_nonfinal.emplace(txid, single_res);
1339 txns_package_eval.push_back(tx);
1340 }
1341 }
1342 }
1343
1344 auto multi_submission_result =
1345 quit_early || txns_package_eval.empty()
1346 ? PackageMempoolAcceptResult(package_state_quit_early, {})
1347 : AcceptSubPackage(txns_package_eval, args);
1348 PackageValidationState &package_state_final =
1349 multi_submission_result.m_state;
1350
1351 // Make sure we haven't exceeded max mempool size.
1352 // Package transactions that were submitted to mempool or already in mempool
1353 // may be evicted.
1354 m_pool.LimitSize(m_active_chainstate.CoinsTip());
1355
1356 for (const auto &tx : package) {
1357 const auto &txid = tx->GetId();
1358 if (multi_submission_result.m_tx_results.count(txid) > 0) {
1359 // We shouldn't have re-submitted if the tx result was already in
1360 // results_final.
1361 Assume(results_final.count(txid) == 0);
1362 // If it was submitted, check to see if the tx is still in the
1363 // mempool. It could have been evicted due to LimitMempoolSize()
1364 // above.
1365 const auto &txresult =
1366 multi_submission_result.m_tx_results.at(txid);
1367 if (txresult.m_result_type ==
1369 !m_pool.exists(txid)) {
1370 package_state_final.Invalid(PackageValidationResult::PCKG_TX,
1371 "transaction failed");
1372 TxValidationState mempool_full_state;
1373 mempool_full_state.Invalid(
1375 results_final.emplace(
1376 txid, MempoolAcceptResult::Failure(mempool_full_state));
1377 } else {
1378 results_final.emplace(txid, txresult);
1379 }
1380 } else if (const auto final_it{results_final.find(txid)};
1381 final_it != results_final.end()) {
1382 // Already-in-mempool transaction. Check to see if it's still there,
1383 // as it could have been evicted when LimitMempoolSize() was called.
1384 Assume(final_it->second.m_result_type !=
1386 Assume(individual_results_nonfinal.count(txid) == 0);
1387 if (!m_pool.exists(tx->GetId())) {
1388 package_state_final.Invalid(PackageValidationResult::PCKG_TX,
1389 "transaction failed");
1390 TxValidationState mempool_full_state;
1391 mempool_full_state.Invalid(
1393 // Replace the previous result.
1394 results_final.erase(txid);
1395 results_final.emplace(
1396 txid, MempoolAcceptResult::Failure(mempool_full_state));
1397 }
1398 } else if (const auto non_final_it{
1399 individual_results_nonfinal.find(txid)};
1400 non_final_it != individual_results_nonfinal.end()) {
1401 Assume(non_final_it->second.m_result_type ==
1403 // Interesting result from previous processing.
1404 results_final.emplace(txid, non_final_it->second);
1405 }
1406 }
1407 Assume(results_final.size() == package.size());
1408 return PackageMempoolAcceptResult(package_state_final,
1409 std::move(results_final));
1410}
1411} // namespace
1412
1414 const CTransactionRef &tx,
1415 int64_t accept_time, bool bypass_limits,
1416 bool test_accept,
1417 unsigned int heightOverride) {
1419 assert(active_chainstate.GetMempool() != nullptr);
1420 CTxMemPool &pool{*active_chainstate.GetMempool()};
1421
1422 std::vector<COutPoint> coins_to_uncache;
1423 auto args = MemPoolAccept::ATMPArgs::SingleAccept(
1424 active_chainstate.m_chainman.GetConfig(), accept_time, bypass_limits,
1425 coins_to_uncache, test_accept, heightOverride);
1426 MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate)
1427 .AcceptSingleTransaction(tx, args);
1429 // Remove coins that were not present in the coins cache before calling
1430 // ATMPW; this is to prevent memory DoS in case we receive a large
1431 // number of invalid transactions that attempt to overrun the in-memory
1432 // coins cache
1433 // (`CCoinsViewCache::cacheCoins`).
1434
1435 for (const COutPoint &outpoint : coins_to_uncache) {
1436 active_chainstate.CoinsTip().Uncache(outpoint);
1437 }
1438 }
1439
1440 // After we've (potentially) uncached entries, ensure our coins cache is
1441 // still within its size limits
1442 BlockValidationState stateDummy;
1443 active_chainstate.FlushStateToDisk(stateDummy, FlushStateMode::PERIODIC);
1444 return result;
1445}
1446
1448 CTxMemPool &pool,
1449 const Package &package,
1450 bool test_accept) {
1452 assert(!package.empty());
1453 assert(std::all_of(package.cbegin(), package.cend(),
1454 [](const auto &tx) { return tx != nullptr; }));
1455
1456 const Config &config = active_chainstate.m_chainman.GetConfig();
1457
1458 std::vector<COutPoint> coins_to_uncache;
1459 auto result = [&]() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
1461 if (test_accept) {
1462 auto args = MemPoolAccept::ATMPArgs::PackageTestAccept(
1463 config, GetTime(), coins_to_uncache);
1464 return MemPoolAccept(pool, active_chainstate)
1465 .AcceptMultipleTransactions(package, args);
1466 } else {
1467 auto args = MemPoolAccept::ATMPArgs::PackageChildWithParents(
1468 config, GetTime(), coins_to_uncache);
1469 return MemPoolAccept(pool, active_chainstate)
1470 .AcceptPackage(package, args);
1471 }
1472 }();
1473
1474 // Uncache coins pertaining to transactions that were not submitted to the
1475 // mempool.
1476 if (test_accept || result.m_state.IsInvalid()) {
1477 for (const COutPoint &hashTx : coins_to_uncache) {
1478 active_chainstate.CoinsTip().Uncache(hashTx);
1479 }
1480 }
1481 // Ensure the coins cache is still within limits.
1482 BlockValidationState state_dummy;
1483 active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1484 return result;
1485}
1486
1487Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams) {
1488 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1489 // Force block reward to zero when right shift is undefined.
1490 if (halvings >= 64) {
1491 return Amount::zero();
1492 }
1493
1494 Amount nSubsidy = 50 * COIN;
1495 // Subsidy is cut in half every 210,000 blocks which will occur
1496 // approximately every 4 years.
1497 return ((nSubsidy / SATOSHI) >> halvings) * SATOSHI;
1498}
1499
1501 : m_dbview{std::move(db_params), std::move(options)},
1502 m_catcherview(&m_dbview) {}
1503
1504void CoinsViews::InitCache() {
1506 m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1507}
1508
1510 ChainstateManager &chainman,
1511 std::optional<BlockHash> from_snapshot_blockhash)
1512 : m_mempool(mempool), m_blockman(blockman), m_chainman(chainman),
1513 m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1514
1515const CBlockIndex *Chainstate::SnapshotBase() {
1517 return nullptr;
1518 }
1519 if (!m_cached_snapshot_base) {
1520 m_cached_snapshot_base = Assert(
1522 }
1523 return m_cached_snapshot_base;
1524}
1525
1526void Chainstate::InitCoinsDB(size_t cache_size_bytes, bool in_memory,
1527 bool should_wipe, std::string leveldb_name) {
1529 leveldb_name += node::SNAPSHOT_CHAINSTATE_SUFFIX;
1530 }
1531
1532 m_coins_views = std::make_unique<CoinsViews>(
1533 DBParams{.path = m_chainman.m_options.datadir / leveldb_name,
1534 .cache_bytes = cache_size_bytes,
1535 .memory_only = in_memory,
1536 .wipe_data = should_wipe,
1537 .obfuscate = true,
1538 .options = m_chainman.m_options.coins_db},
1540}
1541
1542void Chainstate::InitCoinsCache(size_t cache_size_bytes) {
1544 assert(m_coins_views != nullptr);
1545 m_coinstip_cache_size_bytes = cache_size_bytes;
1546 m_coins_views->InitCache();
1547}
1548
1549// Note that though this is marked const, we may end up modifying
1550// `m_cached_finished_ibd`, which is a performance-related implementation
1551// detail. This function must be marked `const` so that `CValidationInterface`
1552// clients (which are given a `const Chainstate*`) can call it.
1553//
1555 // Optimization: pre-test latch before taking the lock.
1556 if (m_cached_finished_ibd.load(std::memory_order_relaxed)) {
1557 return false;
1558 }
1559
1560 LOCK(cs_main);
1561 if (m_cached_finished_ibd.load(std::memory_order_relaxed)) {
1562 return false;
1563 }
1564 if (m_blockman.LoadingBlocks()) {
1565 return true;
1566 }
1567 CChain &chain{ActiveChain()};
1568 if (chain.Tip() == nullptr) {
1569 return true;
1570 }
1571 if (chain.Tip()->nChainWork < MinimumChainWork()) {
1572 return true;
1573 }
1574 if (chain.Tip()->Time() < Now<NodeSeconds>() - m_options.max_tip_age) {
1575 return true;
1576 }
1577 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1578 m_cached_finished_ibd.store(true, std::memory_order_relaxed);
1579 return false;
1580}
1581
1584
1585 // Before we get past initial download, we cannot reliably alert about forks
1586 // (we assume we don't get stuck on a fork before finishing our initial
1587 // sync)
1589 return;
1590 }
1591
1592 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one
1593 // mines it) of our head, or if it is back on the active chain, drop it
1596 m_best_fork_tip = nullptr;
1597 }
1598
1599 if (m_best_fork_tip ||
1600 (m_chainman.m_best_invalid &&
1601 m_chainman.m_best_invalid->nChainWork >
1602 m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6))) {
1604 std::string warning =
1605 std::string("'Warning: Large-work fork detected, forking after "
1606 "block ") +
1607 m_best_fork_base->phashBlock->ToString() + std::string("'");
1609 }
1610
1612 LogPrintf("%s: Warning: Large fork found\n forking the "
1613 "chain at height %d (%s)\n lasting to height %d "
1614 "(%s).\nChain state database corruption likely.\n",
1615 __func__, m_best_fork_base->nHeight,
1620 } else {
1621 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks "
1622 "longer than our best chain.\nChain state database "
1623 "corruption likely.\n",
1624 __func__);
1626 }
1627 } else {
1630 }
1631}
1632
1634 CBlockIndex *pindexNewForkTip) {
1636
1637 // If we are on a fork that is sufficiently large, set a warning flag.
1638 const CBlockIndex *pfork = m_chain.FindFork(pindexNewForkTip);
1639
1640 // We define a condition where we should warn the user about as a fork of at
1641 // least 7 blocks with a tip within 72 blocks (+/- 12 hours if no one mines
1642 // it) of ours. We use 7 blocks rather arbitrarily as it represents just
1643 // under 10% of sustained network hash rate operating on the fork, or a
1644 // chain that is entirely longer than ours and invalid (note that this
1645 // should be detected by both). We define it this way because it allows us
1646 // to only store the highest fork tip (+ base) which meets the 7-block
1647 // condition and from this always have the most-likely-to-cause-warning fork
1648 if (pfork &&
1649 (!m_best_fork_tip ||
1650 pindexNewForkTip->nHeight > m_best_fork_tip->nHeight) &&
1651 pindexNewForkTip->nChainWork - pfork->nChainWork >
1652 (GetBlockProof(*pfork) * 7) &&
1653 m_chain.Height() - pindexNewForkTip->nHeight < 72) {
1654 m_best_fork_tip = pindexNewForkTip;
1655 m_best_fork_base = pfork;
1656 }
1657
1659}
1660
1661// Called both upon regular invalid block discovery *and* InvalidateBlock
1664 if (!m_chainman.m_best_invalid ||
1665 pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
1666 m_chainman.m_best_invalid = pindexNew;
1667 }
1668 SetBlockFailureFlags(pindexNew);
1669 if (m_chainman.m_best_header != nullptr &&
1670 m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) ==
1671 pindexNew) {
1672 m_chainman.RecalculateBestHeader();
1673 }
1674
1675 // If the invalid chain found is supposed to be finalized, we need to move
1676 // back the finalization point.
1677 if (IsBlockAvalancheFinalized(pindexNew)) {
1679 m_avalancheFinalizedBlockIndex = pindexNew->pprev;
1680 }
1681
1682 LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n",
1683 __func__, pindexNew->GetBlockHash().ToString(),
1684 pindexNew->nHeight,
1685 log(pindexNew->nChainWork.getdouble()) / log(2.0),
1686 FormatISO8601DateTime(pindexNew->GetBlockTime()));
1687 CBlockIndex *tip = m_chain.Tip();
1688 assert(tip);
1689 LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n",
1690 __func__, tip->GetBlockHash().ToString(), m_chain.Height(),
1691 log(tip->nChainWork.getdouble()) / log(2.0),
1693}
1694
1695// Same as InvalidChainFound, above, except not called directly from
1696// InvalidateBlock, which does its own setBlockIndexCandidates management.
1698 const BlockValidationState &state) {
1701 pindex->nStatus = pindex->nStatus.withFailed();
1702 m_chainman.m_failed_blocks.insert(pindex);
1703 m_blockman.m_dirty_blockindex.insert(pindex);
1704 InvalidChainFound(pindex);
1705 }
1706}
1707
1708void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
1709 int nHeight) {
1710 // Mark inputs spent.
1711 if (tx.IsCoinBase()) {
1712 return;
1713 }
1714
1715 txundo.vprevout.reserve(tx.vin.size());
1716 for (const CTxIn &txin : tx.vin) {
1717 txundo.vprevout.emplace_back();
1718 bool is_spent = view.SpendCoin(txin.prevout, &txundo.vprevout.back());
1719 assert(is_spent);
1720 }
1721}
1722
1723void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
1724 int nHeight) {
1725 SpendCoins(view, tx, txundo, nHeight);
1726 AddCoins(view, tx, nHeight);
1727}
1728
1729std::vector<Coin> GetSpentCoins(const CTransactionRef &ptx,
1730 const CCoinsViewCache &coins_view) {
1731 std::vector<Coin> spent_coins;
1732 spent_coins.reserve(ptx->vin.size());
1733 for (const CTxIn &input : ptx->vin) {
1734 Coin coin;
1735 const bool coinFound = coins_view.GetCoin(input.prevout, coin);
1736 Assume(coinFound);
1737 spent_coins.push_back(std::move(coin));
1738 }
1739 return spent_coins;
1740}
1741
1742std::optional<std::pair<ScriptError, std::string>> CScriptCheck::operator()() {
1743 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1745 auto debug_str = strprintf("input %i of %s, spending %s:%i", nIn,
1746 ptxTo->GetId().ToString(),
1747 ptxTo->vin[nIn].prevout.GetTxId().ToString(),
1748 ptxTo->vin[nIn].prevout.GetN());
1749 if (!VerifyScript(scriptSig, m_tx_out.scriptPubKey, nFlags,
1753 metrics, &error)) {
1754 return std::make_pair(error, std::move(debug_str));
1755 }
1756 if ((pTxLimitSigChecks &&
1760 // we can't assign a meaningful script error (since the script
1761 // succeeded), but remove the ScriptError::OK which could be
1762 // misinterpreted.
1763 return std::make_pair(ScriptError::SIGCHECKS_LIMIT_EXCEEDED,
1764 std::move(debug_str));
1765 }
1766 return std::nullopt;
1767}
1768
1769ValidationCache::ValidationCache(const size_t script_execution_cache_bytes,
1770 const size_t signature_cache_bytes)
1771 : m_signature_cache{signature_cache_bytes} {
1772 // Setup the salted hasher
1773 uint256 nonce = GetRandHash();
1774 // We want the nonce to be 64 bytes long to force the hasher to process
1775 // this chunk, which makes later hash computations more efficient. We
1776 // just write our 32-byte entropy twice to fill the 64 bytes.
1779
1780 const auto [num_elems, approx_size_bytes] =
1781 m_script_execution_cache.setup_bytes(script_execution_cache_bytes);
1782 LogPrintf("Using %zu MiB out of %zu MiB requested for script execution "
1783 "cache, able to store %zu elements\n",
1784 approx_size_bytes >> 20, script_execution_cache_bytes >> 20,
1785 num_elems);
1786}
1787
1788bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
1789 const CCoinsViewCache &inputs, const uint32_t flags,
1790 bool sigCacheStore, bool scriptCacheStore,
1791 const PrecomputedTransactionData &txdata,
1792 ValidationCache &validation_cache, int &nSigChecksOut,
1793 TxSigCheckLimiter &txLimitSigChecks,
1794 CheckInputsLimiter *pBlockLimitSigChecks,
1795 std::vector<CScriptCheck> *pvChecks) {
1797 assert(!tx.IsCoinBase());
1798
1799 if (pvChecks) {
1800 pvChecks->reserve(tx.vin.size());
1801 }
1802
1803 // First check if script executions have been cached with the same flags.
1804 // Note that this assumes that the inputs provided are correct (ie that the
1805 // transaction hash which is in tx's prevouts properly commits to the
1806 // scriptPubKey in the inputs view of that transaction).
1807 ScriptCacheKey hashCacheEntry(
1808 tx, flags, validation_cache.ScriptExecutionCacheHasher());
1809 ScriptCacheElement elem(hashCacheEntry, 0);
1810 bool found_in_cache = validation_cache.m_script_execution_cache.get(
1811 elem, /*erase=*/!scriptCacheStore);
1812 nSigChecksOut = elem.nSigChecks;
1813 if (found_in_cache) {
1814 if (!txLimitSigChecks.consume_and_check(nSigChecksOut) ||
1815 (pBlockLimitSigChecks &&
1816 !pBlockLimitSigChecks->consume_and_check(nSigChecksOut))) {
1818 "too-many-sigchecks");
1819 }
1820 return true;
1821 }
1822
1823 int nSigChecksTotal = 0;
1824
1825 for (size_t i = 0; i < tx.vin.size(); i++) {
1826 const COutPoint &prevout = tx.vin[i].prevout;
1827 const Coin &coin = inputs.AccessCoin(prevout);
1828 assert(!coin.IsSpent());
1829
1830 // We very carefully only pass in things to CScriptCheck which are
1831 // clearly committed to by tx's hash. This provides a sanity
1832 // check that our caching is not introducing consensus failures through
1833 // additional data in, eg, the coins being spent being checked as a part
1834 // of CScriptCheck.
1835
1836 // Verify signature
1837 CScriptCheck check(
1838 coin.GetTxOut(), tx, validation_cache.m_signature_cache, i, flags,
1839 sigCacheStore, txdata, &txLimitSigChecks, pBlockLimitSigChecks);
1840
1841 // If pvChecks is not null, defer the check execution to the caller.
1842 if (pvChecks) {
1843 pvChecks->push_back(std::move(check));
1844 continue;
1845 }
1846
1847 if (auto result = check(); result.has_value()) {
1848 // Compute flags without the optional standardness flags.
1849 // This differs from MANDATORY_SCRIPT_VERIFY_FLAGS as it contains
1850 // additional upgrade flags (see AcceptToMemoryPoolWorker variable
1851 // extraFlags).
1852 uint32_t mandatoryFlags =
1853 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS;
1854 if (flags != mandatoryFlags) {
1855 // Check whether the failure was caused by a non-mandatory
1856 // script verification check. If so, ensure we return
1857 // NOT_STANDARD instead of CONSENSUS to avoid downstream users
1858 // splitting the network between upgraded and non-upgraded nodes
1859 // by banning CONSENSUS-failing data providers.
1860 CScriptCheck check2(coin.GetTxOut(), tx,
1861 validation_cache.m_signature_cache, i,
1862 mandatoryFlags, sigCacheStore, txdata);
1863 auto mandatory_result = check2();
1864 if (!mandatory_result.has_value()) {
1865 return state.Invalid(
1867 strprintf("non-mandatory-script-verify-flag (%s)",
1868 ScriptErrorString(result->first)),
1869 result->second);
1870 }
1871 // If the second check failed, it failed due to a mandatory
1872 // script verification flag, but the first check might have
1873 // failed on a non-mandatory script verification flag.
1874 //
1875 // Avoid reporting a mandatory script check failure with a
1876 // non-mandatory error string by reporting the error from the
1877 // second check.
1878 result = mandatory_result;
1879 }
1880
1881 // MANDATORY flag failures correspond to
1882 // TxValidationResult::TX_CONSENSUS. Because CONSENSUS failures are
1883 // the most serious case of validation failures, we may need to
1884 // consider using RECENT_CONSENSUS_CHANGE for any script failure
1885 // that could be due to non-upgraded nodes which we may want to
1886 // support, to avoid splitting the network (but this depends on the
1887 // details of how net_processing handles such errors).
1888 return state.Invalid(
1890 strprintf("mandatory-script-verify-flag-failed (%s)",
1891 ScriptErrorString(result->first)),
1892 result->second);
1893 }
1894
1895 nSigChecksTotal += check.GetScriptExecutionMetrics().nSigChecks;
1896 }
1897
1898 nSigChecksOut = nSigChecksTotal;
1899
1900 if (scriptCacheStore && !pvChecks) {
1901 // We executed all of the provided scripts, and were told to cache the
1902 // result. Do so now.
1903 validation_cache.m_script_execution_cache.insert(
1904 ScriptCacheElement{hashCacheEntry, nSigChecksTotal});
1905 }
1906
1907 return true;
1908}
1909
1911 const std::string &strMessage,
1912 const bilingual_str &userMessage) {
1913 notifications.fatalError(strMessage, userMessage);
1914 return state.Error(strMessage);
1915}
1916
1919 const COutPoint &out) {
1920 bool fClean = true;
1921
1922 if (view.HaveCoin(out)) {
1923 // Overwriting transaction output.
1924 fClean = false;
1925 }
1926
1927 if (undo.GetHeight() == 0) {
1928 // Missing undo metadata (height and coinbase). Older versions included
1929 // this information only in undo records for the last spend of a
1930 // transactions' outputs. This implies that it must be present for some
1931 // other output of the same tx.
1932 const Coin &alternate = AccessByTxid(view, out.GetTxId());
1933 if (alternate.IsSpent()) {
1934 // Adding output for transaction without known metadata
1936 }
1937
1938 // This is somewhat ugly, but hopefully utility is limited. This is only
1939 // useful when working from legacy on disck data. In any case, putting
1940 // the correct information in there doesn't hurt.
1941 const_cast<Coin &>(undo) = Coin(undo.GetTxOut(), alternate.GetHeight(),
1942 alternate.IsCoinBase());
1943 }
1944
1945 // If the coin already exists as an unspent coin in the cache, then the
1946 // possible_overwrite parameter to AddCoin must be set to true. We have
1947 // already checked whether an unspent coin exists above using HaveCoin, so
1948 // we don't need to guess. When fClean is false, an unspent coin already
1949 // existed and it is an overwrite.
1950 view.AddCoin(out, std::move(undo), !fClean);
1951
1953}
1954
1959DisconnectResult Chainstate::DisconnectBlock(const CBlock &block,
1960 const CBlockIndex *pindex,
1961 CCoinsViewCache &view) {
1963 CBlockUndo blockUndo;
1964 if (!m_blockman.ReadBlockUndo(blockUndo, *pindex)) {
1965 LogError("DisconnectBlock(): failure reading undo data\n");
1967 }
1968
1969 return ApplyBlockUndo(std::move(blockUndo), block, pindex, view);
1970}
1971
1973 const CBlockIndex *pindex,
1974 CCoinsViewCache &view) {
1975 bool fClean = true;
1976
1977 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1978 LogError("DisconnectBlock(): block and undo data inconsistent\n");
1980 }
1981
1982 // First, restore inputs.
1983 for (size_t i = 1; i < block.vtx.size(); i++) {
1984 const CTransaction &tx = *(block.vtx[i]);
1985 CTxUndo &txundo = blockUndo.vtxundo[i - 1];
1986 if (txundo.vprevout.size() != tx.vin.size()) {
1987 LogError(
1988 "DisconnectBlock(): transaction and undo data inconsistent\n");
1990 }
1991
1992 for (size_t j = 0; j < tx.vin.size(); j++) {
1993 const COutPoint &out = tx.vin[j].prevout;
1994 DisconnectResult res =
1995 UndoCoinSpend(std::move(txundo.vprevout[j]), view, out);
1996 if (res == DisconnectResult::FAILED) {
1998 }
1999 fClean = fClean && res != DisconnectResult::UNCLEAN;
2000 }
2001 // At this point, all of txundo.vprevout should have been moved out.
2002 }
2003
2004 // Second, revert created outputs.
2005 for (const auto &ptx : block.vtx) {
2006 const CTransaction &tx = *ptx;
2007 const TxId &txid = tx.GetId();
2008 const bool is_coinbase = tx.IsCoinBase();
2009
2010 // Check that all outputs are available and match the outputs in the
2011 // block itself exactly.
2012 for (size_t o = 0; o < tx.vout.size(); o++) {
2013 if (tx.vout[o].scriptPubKey.IsUnspendable()) {
2014 continue;
2015 }
2016
2017 COutPoint out(txid, o);
2018 Coin coin;
2019 bool is_spent = view.SpendCoin(out, &coin);
2020 if (!is_spent || tx.vout[o] != coin.GetTxOut() ||
2021 uint32_t(pindex->nHeight) != coin.GetHeight() ||
2022 is_coinbase != coin.IsCoinBase()) {
2023 // transaction output mismatch
2024 fClean = false;
2025 }
2026 }
2027 }
2028
2029 // Move best block pointer to previous block.
2030 view.SetBestBlock(block.hashPrevBlock);
2031
2033}
2034
2036
2037void StartScriptCheckWorkerThreads(int threads_num) {
2038 scriptcheckqueue.StartWorkerThreads(threads_num);
2039}
2040
2042 scriptcheckqueue.StopWorkerThreads();
2043}
2044
2045// Returns the script flags which should be checked for the block after
2046// the given block.
2047static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex,
2048 const ChainstateManager &chainman) {
2049 const Consensus::Params &consensusparams = chainman.GetConsensus();
2050
2051 uint32_t flags = SCRIPT_VERIFY_NONE;
2052
2053 // Enforce P2SH (BIP16)
2054 if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_P2SH)) {
2056 }
2057
2058 // Enforce the DERSIG (BIP66) rule.
2059 if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_DERSIG)) {
2061 }
2062
2063 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule.
2064 if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_CLTV)) {
2066 }
2067
2068 // Start enforcing CSV (BIP68, BIP112 and BIP113) rule.
2069 if (DeploymentActiveAfter(pindex, chainman, Consensus::DEPLOYMENT_CSV)) {
2071 }
2072
2073 // If the UAHF is enabled, we start accepting replay protected txns
2074 if (IsUAHFenabled(consensusparams, pindex)) {
2077 }
2078
2079 // If the DAA HF is enabled, we start rejecting transaction that use a high
2080 // s in their signature. We also make sure that signature that are supposed
2081 // to fail (for instance in multisig or other forms of smart contracts) are
2082 // null.
2083 if (IsDAAEnabled(consensusparams, pindex)) {
2086 }
2087
2088 // When the magnetic anomaly fork is enabled, we start accepting
2089 // transactions using the OP_CHECKDATASIG opcode and it's verify
2090 // alternative. We also start enforcing push only signatures and
2091 // clean stack.
2092 if (IsMagneticAnomalyEnabled(consensusparams, pindex)) {
2095 }
2096
2097 if (IsGravitonEnabled(consensusparams, pindex)) {
2100 }
2101
2102 if (IsPhononEnabled(consensusparams, pindex)) {
2104 }
2105
2106 // We make sure this node will have replay protection during the next hard
2107 // fork.
2109 consensusparams, pindex,
2112 }
2113
2114 return flags;
2115}
2116
2117static SteadyClock::duration time_check{};
2118static SteadyClock::duration time_forks{};
2119static SteadyClock::duration time_connect{};
2120static SteadyClock::duration time_verify{};
2121static SteadyClock::duration time_index{};
2122static SteadyClock::duration time_total{};
2123static int64_t num_blocks_total = 0;
2124
2131bool Chainstate::ConnectBlock(const CBlock &block, BlockValidationState &state,
2132 CBlockIndex *pindex, CCoinsViewCache &view,
2133 BlockValidationOptions options, Amount *blockFees,
2134 bool fJustCheck) {
2136 assert(pindex);
2137
2138 const BlockHash block_hash{block.GetHash()};
2139 assert(*pindex->phashBlock == block_hash);
2140
2141 const auto time_start{SteadyClock::now()};
2142
2143 const CChainParams &params{m_chainman.GetParams()};
2144 const Consensus::Params &consensusParams = params.GetConsensus();
2145
2146 // Check it again in case a previous version let a bad block in
2147 // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
2148 // ContextualCheckBlockHeader() here. This means that if we add a new
2149 // consensus rule that is enforced in one of those two functions, then we
2150 // may have let in a block that violates the rule prior to updating the
2151 // software, and we would NOT be enforcing the rule here. Fully solving
2152 // upgrade from one software version to the next after a consensus rule
2153 // change is potentially tricky and issue-specific.
2154 // Also, currently the rule against blocks more than 2 hours in the future
2155 // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
2156 // re-enforce that rule here (at least until we make it impossible for
2157 // m_adjusted_time_callback() to go backward).
2158 if (!CheckBlock(block, state, consensusParams,
2159 options.withCheckPoW(!fJustCheck)
2160 .withCheckMerkleRoot(!fJustCheck))) {
2162 // We don't write down blocks to disk if they may have been
2163 // corrupted, so this should be impossible unless we're having
2164 // hardware problems.
2165 return FatalError(m_chainman.GetNotifications(), state,
2166 "Corrupt block found indicating potential "
2167 "hardware failure; shutting down");
2168 }
2169 LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());
2170 return false;
2171 }
2172
2173 // Verify that the view's current state corresponds to the previous block
2174 BlockHash hashPrevBlock =
2175 pindex->pprev == nullptr ? BlockHash() : pindex->pprev->GetBlockHash();
2176 assert(hashPrevBlock == view.GetBestBlock());
2177
2179
2180 // Special case for the genesis block, skipping connection of its
2181 // transactions (its coinbase is unspendable)
2182 if (block_hash == consensusParams.hashGenesisBlock) {
2183 if (!fJustCheck) {
2184 view.SetBestBlock(pindex->GetBlockHash());
2185 }
2186
2187 return true;
2188 }
2189
2190 bool fScriptChecks = true;
2192 // We've been configured with the hash of a block which has been
2193 // externally verified to have a valid history. A suitable default value
2194 // is included with the software and updated from time to time. Because
2195 // validity relative to a piece of software is an objective fact these
2196 // defaults can be easily reviewed. This setting doesn't force the
2197 // selection of any particular chain but makes validating some faster by
2198 // effectively caching the result of part of the verification.
2199 BlockMap::const_iterator it{
2200 m_blockman.m_block_index.find(m_chainman.AssumedValidBlock())};
2201 if (it != m_blockman.m_block_index.end()) {
2202 if (it->second.GetAncestor(pindex->nHeight) == pindex &&
2203 m_chainman.m_best_header->GetAncestor(pindex->nHeight) ==
2204 pindex &&
2205 m_chainman.m_best_header->nChainWork >=
2207 // This block is a member of the assumed verified chain and an
2208 // ancestor of the best header.
2209 // Script verification is skipped when connecting blocks under
2210 // the assumevalid block. Assuming the assumevalid block is
2211 // valid this is safe because block merkle hashes are still
2212 // computed and checked, Of course, if an assumed valid block is
2213 // invalid due to false scriptSigs this optimization would allow
2214 // an invalid chain to be accepted.
2215 // The equivalent time check discourages hash power from
2216 // extorting the network via DOS attack into accepting an
2217 // invalid block through telling users they must manually set
2218 // assumevalid. Requiring a software change or burying the
2219 // invalid block, regardless of the setting, makes it hard to
2220 // hide the implication of the demand. This also avoids having
2221 // release candidates that are hardly doing any signature
2222 // verification at all in testing without having to artificially
2223 // set the default assumed verified block further back. The test
2224 // against the minimum chain work prevents the skipping when
2225 // denied access to any chain at least as good as the expected
2226 // chain.
2227 fScriptChecks = (GetBlockProofEquivalentTime(
2228 *m_chainman.m_best_header, *pindex,
2229 *m_chainman.m_best_header,
2230 consensusParams) <= 60 * 60 * 24 * 7 * 2);
2231 }
2232 }
2233 }
2234
2235 const auto time_1{SteadyClock::now()};
2236 time_check += time_1 - time_start;
2237 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2238 Ticks<MillisecondsDouble>(time_1 - time_start),
2239 Ticks<SecondsDouble>(time_check),
2240 Ticks<MillisecondsDouble>(time_check) / num_blocks_total);
2241
2242 // Do not allow blocks that contain transactions which 'overwrite' older
2243 // transactions, unless those are already completely spent. If such
2244 // overwrites are allowed, coinbases and transactions depending upon those
2245 // can be duplicated to remove the ability to spend the first instance --
2246 // even after being sent to another address.
2247 // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html
2248 // for more information. This rule was originally applied to all blocks
2249 // with a timestamp after March 15, 2012, 0:00 UTC. Now that the whole
2250 // chain is irreversibly beyond that time it is applied to all blocks
2251 // except the two in the chain that violate it. This prevents exploiting
2252 // the issue against nodes during their initial block download.
2253 bool fEnforceBIP30 = !((pindex->nHeight == 91842 &&
2254 pindex->GetBlockHash() ==
2255 uint256S("0x00000000000a4d0a398161ffc163c503763"
2256 "b1f4360639393e0e4c8e300e0caec")) ||
2257 (pindex->nHeight == 91880 &&
2258 pindex->GetBlockHash() ==
2259 uint256S("0x00000000000743f190a18c5577a3c2d2a1f"
2260 "610ae9601ac046a38084ccb7cd721")));
2261
2262 // Once BIP34 activated it was not possible to create new duplicate
2263 // coinbases and thus other than starting with the 2 existing duplicate
2264 // coinbase pairs, not possible to create overwriting txs. But by the time
2265 // BIP34 activated, in each of the existing pairs the duplicate coinbase had
2266 // overwritten the first before the first had been spent. Since those
2267 // coinbases are sufficiently buried it's no longer possible to create
2268 // further duplicate transactions descending from the known pairs either. If
2269 // we're on the known chain at height greater than where BIP34 activated, we
2270 // can save the db accesses needed for the BIP30 check.
2271
2272 // BIP34 requires that a block at height X (block X) has its coinbase
2273 // scriptSig start with a CScriptNum of X (indicated height X). The above
2274 // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
2275 // case that there is a block X before the BIP34 height of 227,931 which has
2276 // an indicated height Y where Y is greater than X. The coinbase for block
2277 // X would also be a valid coinbase for block Y, which could be a BIP30
2278 // violation. An exhaustive search of all mainnet coinbases before the
2279 // BIP34 height which have an indicated height greater than the block height
2280 // reveals many occurrences. The 3 lowest indicated heights found are
2281 // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
2282 // heights would be the first opportunity for BIP30 to be violated.
2283
2284 // The search reveals a great many blocks which have an indicated height
2285 // greater than 1,983,702, so we simply remove the optimization to skip
2286 // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
2287 // that block in another 25 years or so, we should take advantage of a
2288 // future consensus change to do a new and improved version of BIP34 that
2289 // will actually prevent ever creating any duplicate coinbases in the
2290 // future.
2291 static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
2292
2293 // There is no potential to create a duplicate coinbase at block 209,921
2294 // because this is still before the BIP34 height and so explicit BIP30
2295 // checking is still active.
2296
2297 // The final case is block 176,684 which has an indicated height of
2298 // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
2299 // before block 490,897 so there was not much opportunity to address this
2300 // case other than to carefully analyze it and determine it would not be a
2301 // problem. Block 490,897 was, in fact, mined with a different coinbase than
2302 // block 176,684, but it is important to note that even if it hadn't been or
2303 // is remined on an alternate fork with a duplicate coinbase, we would still
2304 // not run into a BIP30 violation. This is because the coinbase for 176,684
2305 // is spent in block 185,956 in transaction
2306 // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
2307 // spending transaction can't be duplicated because it also spends coinbase
2308 // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
2309 // coinbase has an indicated height of over 4.2 billion, and wouldn't be
2310 // duplicatable until that height, and it's currently impossible to create a
2311 // chain that long. Nevertheless we may wish to consider a future soft fork
2312 // which retroactively prevents block 490,897 from creating a duplicate
2313 // coinbase. The two historical BIP30 violations often provide a confusing
2314 // edge case when manipulating the UTXO and it would be simpler not to have
2315 // another edge case to deal with.
2316
2317 // testnet3 has no blocks before the BIP34 height with indicated heights
2318 // post BIP34 before approximately height 486,000,000 and presumably will
2319 // be reset before it reaches block 1,983,702 and starts doing unnecessary
2320 // BIP30 checking again.
2321 assert(pindex->pprev);
2322 CBlockIndex *pindexBIP34height =
2323 pindex->pprev->GetAncestor(consensusParams.BIP34Height);
2324 // Only continue to enforce if we're below BIP34 activation height or the
2325 // block hash at that height doesn't correspond.
2326 fEnforceBIP30 =
2327 fEnforceBIP30 &&
2328 (!pindexBIP34height ||
2329 !(pindexBIP34height->GetBlockHash() == consensusParams.BIP34Hash));
2330
2331 // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have
2332 // a consensus change that ensures coinbases at those heights can not
2333 // duplicate earlier coinbases.
2334 if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
2335 for (const auto &tx : block.vtx) {
2336 for (size_t o = 0; o < tx->vout.size(); o++) {
2337 if (view.HaveCoin(COutPoint(tx->GetId(), o))) {
2339 "bad-txns-BIP30",
2340 "tried to overwrite transaction");
2341 }
2342 }
2343 }
2344 }
2345
2346 // Enforce BIP68 (sequence locks).
2347 int nLockTimeFlags = 0;
2348 if (DeploymentActiveAt(*pindex, consensusParams,
2350 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2351 }
2352
2353 const uint32_t flags = GetNextBlockScriptFlags(pindex->pprev, m_chainman);
2354
2355 const auto time_2{SteadyClock::now()};
2356 time_forks += time_2 - time_1;
2357 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n",
2358 Ticks<MillisecondsDouble>(time_2 - time_1),
2359 Ticks<SecondsDouble>(time_forks),
2360 Ticks<MillisecondsDouble>(time_forks) / num_blocks_total);
2361
2362 std::vector<int> prevheights;
2363 Amount nFees = Amount::zero();
2364 int nInputs = 0;
2365
2366 // Limit the total executed signature operations in the block, a consensus
2367 // rule. Tracking during the CPU-consuming part (validation of uncached
2368 // inputs) is per-input atomic and validation in each thread stops very
2369 // quickly after the limit is exceeded, so an adversary cannot cause us to
2370 // exceed the limit by much at all.
2371 CheckInputsLimiter nSigChecksBlockLimiter(
2373
2374 std::vector<TxSigCheckLimiter> nSigChecksTxLimiters;
2375 nSigChecksTxLimiters.resize(block.vtx.size() - 1);
2376
2377 CBlockUndo blockundo;
2378 blockundo.vtxundo.resize(block.vtx.size() - 1);
2379
2380 CCheckQueueControl<CScriptCheck> control(fScriptChecks ? &scriptcheckqueue
2381 : nullptr);
2382
2383 // Add all outputs
2384 try {
2385 for (const auto &ptx : block.vtx) {
2386 AddCoins(view, *ptx, pindex->nHeight);
2387 }
2388 } catch (const std::logic_error &e) {
2389 // This error will be thrown from AddCoin if we try to connect a block
2390 // containing duplicate transactions. Such a thing should normally be
2391 // caught early nowadays (due to ContextualCheckBlock's CTOR
2392 // enforcement) however some edge cases can escape that:
2393 // - ContextualCheckBlock does not get re-run after saving the block to
2394 // disk, and older versions may have saved a weird block.
2395 // - its checks are not applied to pre-CTOR chains, which we might visit
2396 // with checkpointing off.
2398 "tx-duplicate", "tried to overwrite transaction");
2399 }
2400
2401 size_t txIndex = 0;
2402 // nSigChecksRet may be accurate (found in cache) or 0 (checks were
2403 // deferred into vChecks).
2404 int nSigChecksRet;
2405 for (const auto &ptx : block.vtx) {
2406 const CTransaction &tx = *ptx;
2407 const bool isCoinBase = tx.IsCoinBase();
2408 nInputs += tx.vin.size();
2409
2410 {
2411 Amount txfee = Amount::zero();
2412 TxValidationState tx_state;
2413 if (!isCoinBase &&
2414 !Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight,
2415 txfee)) {
2416 // Any transaction validation failure in ConnectBlock is a block
2417 // consensus failure.
2419 tx_state.GetRejectReason(),
2420 tx_state.GetDebugMessage() + " in transaction " +
2421 tx.GetId().ToString());
2422 break;
2423 }
2424 nFees += txfee;
2425 }
2426
2427 if (!MoneyRange(nFees)) {
2429 "bad-txns-accumulated-fee-outofrange",
2430 "accumulated fee in the block out of range");
2431 break;
2432 }
2433
2434 // The following checks do not apply to the coinbase.
2435 if (isCoinBase) {
2436 continue;
2437 }
2438
2439 // Check that transaction is BIP68 final BIP68 lock checks (as
2440 // opposed to nLockTime checks) must be in ConnectBlock because they
2441 // require the UTXO set.
2442 prevheights.resize(tx.vin.size());
2443 for (size_t j = 0; j < tx.vin.size(); j++) {
2444 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).GetHeight();
2445 }
2446
2447 if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
2449 "bad-txns-nonfinal",
2450 "contains a non-BIP68-final transaction " +
2451 tx.GetHash().ToString());
2452 break;
2453 }
2454
2455 // Don't cache results if we're actually connecting blocks (still
2456 // consult the cache, though).
2457 bool fCacheResults = fJustCheck;
2458
2459 const bool fEnforceSigCheck = flags & SCRIPT_ENFORCE_SIGCHECKS;
2460 if (!fEnforceSigCheck) {
2461 // Historically, there has been transactions with a very high
2462 // sigcheck count, so we need to disable this check for such
2463 // transactions.
2464 nSigChecksTxLimiters[txIndex] = TxSigCheckLimiter::getDisabled();
2465 }
2466
2467 std::vector<CScriptCheck> vChecks;
2468 TxValidationState tx_state;
2469 if (fScriptChecks &&
2470 !CheckInputScripts(tx, tx_state, view, flags, fCacheResults,
2471 fCacheResults, PrecomputedTransactionData(tx),
2472 m_chainman.m_validation_cache, nSigChecksRet,
2473 nSigChecksTxLimiters[txIndex],
2474 &nSigChecksBlockLimiter, &vChecks)) {
2475 // Any transaction validation failure in ConnectBlock is a block
2476 // consensus failure
2478 tx_state.GetRejectReason(),
2479 tx_state.GetDebugMessage());
2480 break;
2481 }
2482
2483 control.Add(std::move(vChecks));
2484
2485 // Note: this must execute in the same iteration as CheckTxInputs (not
2486 // in a separate loop) in order to detect double spends. However,
2487 // this does not prevent double-spending by duplicated transaction
2488 // inputs in the same transaction (cf. CVE-2018-17144) -- that check is
2489 // done in CheckBlock (CheckRegularTransaction).
2490 SpendCoins(view, tx, blockundo.vtxundo.at(txIndex), pindex->nHeight);
2491 txIndex++;
2492 }
2493 const auto time_3{SteadyClock::now()};
2494 time_connect += time_3 - time_2;
2496 " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) "
2497 "[%.2fs (%.2fms/blk)]\n",
2498 (unsigned)block.vtx.size(),
2499 Ticks<MillisecondsDouble>(time_3 - time_2),
2500 Ticks<MillisecondsDouble>(time_3 - time_2) / block.vtx.size(),
2501 nInputs <= 1
2502 ? 0
2503 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
2504 Ticks<SecondsDouble>(time_connect),
2505 Ticks<MillisecondsDouble>(time_connect) / num_blocks_total);
2506
2507 const Amount blockReward =
2508 nFees + GetBlockSubsidy(pindex->nHeight, consensusParams);
2509 if (block.vtx[0]->GetValueOut() > blockReward && state.IsValid()) {
2510 state.Invalid(
2512 strprintf("coinbase pays too much (actual=%d vs limit=%d)",
2513 block.vtx[0]->GetValueOut(), blockReward));
2514 }
2515
2516 if (blockFees) {
2517 *blockFees = nFees;
2518 }
2519
2520 auto parallel_result = control.Complete();
2521 if (parallel_result.has_value() && state.IsValid()) {
2523 strprintf("mandatory-script-verify-flag-failed (%s)",
2524 ScriptErrorString(parallel_result->first)),
2525 parallel_result->second);
2526 }
2527 if (!state.IsValid()) {
2528 LogInfo("Block validation error: %s\n", state.ToString());
2529 return false;
2530 }
2531 const auto time_4{SteadyClock::now()};
2532 time_verify += time_4 - time_2;
2533 LogPrint(
2535 " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n",
2536 nInputs - 1, Ticks<MillisecondsDouble>(time_4 - time_2),
2537 nInputs <= 1
2538 ? 0
2539 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
2540 Ticks<SecondsDouble>(time_verify),
2541 Ticks<MillisecondsDouble>(time_verify) / num_blocks_total);
2542
2543 if (fJustCheck) {
2544 return true;
2545 }
2546
2547 if (!m_blockman.WriteBlockUndo(blockundo, state, *pindex)) {
2548 return false;
2549 }
2550
2551 if (!pindex->IsValid(BlockValidity::SCRIPTS)) {
2553 m_blockman.m_dirty_blockindex.insert(pindex);
2554 }
2555
2556 // add this block to the view's block chain
2557 view.SetBestBlock(pindex->GetBlockHash());
2558
2559 const auto time_5{SteadyClock::now()};
2560 time_index += time_5 - time_4;
2561 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n",
2562 Ticks<MillisecondsDouble>(time_5 - time_4),
2563 Ticks<SecondsDouble>(time_index),
2564 Ticks<MillisecondsDouble>(time_index) / num_blocks_total);
2565
2566 TRACE6(validation, block_connected, block_hash.data(), pindex->nHeight,
2567 block.vtx.size(), nInputs, nSigChecksRet,
2568 // in microseconds (µs)
2569 time_5 - time_start);
2570
2571 return true;
2572}
2573
2574CoinsCacheSizeState Chainstate::GetCoinsCacheSizeState() {
2576 return this->GetCoinsCacheSizeState(m_coinstip_cache_size_bytes,
2578 : 0);
2579}
2580
2582Chainstate::GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
2583 size_t max_mempool_size_bytes) {
2585 int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
2586 int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
2587 int64_t nTotalSpace =
2588 max_coins_cache_size_bytes +
2589 std::max<int64_t>(int64_t(max_mempool_size_bytes) - nMempoolUsage, 0);
2590
2592 static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES =
2593 10 * 1024 * 1024; // 10MB
2594 int64_t large_threshold = std::max(
2595 (9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
2596
2597 if (cacheSize > nTotalSpace) {
2598 LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize,
2599 nTotalSpace);
2601 } else if (cacheSize > large_threshold) {
2603 }
2605}
2606
2608 FlushStateMode mode, int nManualPruneHeight) {
2609 LOCK(cs_main);
2610 assert(this->CanFlushToDisk());
2611 std::set<int> setFilesToPrune;
2612 bool full_flush_completed = false;
2613
2614 const size_t coins_count = CoinsTip().GetCacheSize();
2615 const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
2616
2617 try {
2618 {
2619 bool fFlushForPrune = false;
2620
2621 CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
2623 if (m_blockman.IsPruneMode() &&
2624 (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) &&
2625 !fReindex) {
2626 // Make sure we don't prune any of the prune locks bestblocks.
2627 // Pruning is height-based.
2628 int last_prune{m_chain.Height()};
2629 // prune lock that actually was the limiting factor, only used
2630 // for logging
2631 std::optional<std::string> limiting_lock;
2632
2633 for (const auto &prune_lock : m_blockman.m_prune_locks) {
2634 if (prune_lock.second.height_first ==
2635 std::numeric_limits<int>::max()) {
2636 continue;
2637 }
2638 // Remove the buffer and one additional block here to get
2639 // actual height that is outside of the buffer
2640 const int lock_height{prune_lock.second.height_first -
2641 PRUNE_LOCK_BUFFER - 1};
2642 last_prune = std::max(1, std::min(last_prune, lock_height));
2643 if (last_prune == lock_height) {
2644 limiting_lock = prune_lock.first;
2645 }
2646 }
2647
2648 if (limiting_lock) {
2649 LogPrint(BCLog::PRUNE, "%s limited pruning to height %d\n",
2650 limiting_lock.value(), last_prune);
2651 }
2652
2653 if (nManualPruneHeight > 0) {
2655 "find files to prune (manual)", BCLog::BENCH);
2657 setFilesToPrune,
2658 std::min(last_prune, nManualPruneHeight), *this,
2659 m_chainman);
2660 } else {
2661 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune",
2662 BCLog::BENCH);
2663 m_blockman.FindFilesToPrune(setFilesToPrune, last_prune,
2664 *this, m_chainman);
2666 }
2667 if (!setFilesToPrune.empty()) {
2668 fFlushForPrune = true;
2670 m_blockman.m_block_tree_db->WriteFlag(
2671 "prunedblockfiles", true);
2673 }
2674 }
2675 }
2676 const auto nNow{NodeClock::now()};
2677 // The cache is large and we're within 10% and 10 MiB of the limit,
2678 // but we have time now (not in the middle of a block processing).
2679 bool fCacheLarge = mode == FlushStateMode::PERIODIC &&
2680 cache_state >= CoinsCacheSizeState::LARGE;
2681 // The cache is over the limit, we have to write now.
2682 bool fCacheCritical = mode == FlushStateMode::IF_NEEDED &&
2683 cache_state >= CoinsCacheSizeState::CRITICAL;
2684 // It's been a while since we wrote the block index and chain
2685 // state to disk. Do this frequently, so we don't need to
2686 // redownload or reindex after a crash.
2687 bool fPeriodicWrite =
2688 mode == FlushStateMode::PERIODIC && nNow >= m_next_write;
2689 // Combine all conditions that result in a write to disk.
2690 bool should_write = (mode == FlushStateMode::ALWAYS) ||
2691 fCacheLarge || fCacheCritical ||
2692 fPeriodicWrite || fFlushForPrune;
2693 // Write blocks, block index and best chain related state to disk.
2694 if (should_write) {
2695 // Ensure we can write block index
2697 return FatalError(m_chainman.GetNotifications(), state,
2698 "Disk space is too low!",
2699 _("Disk space is too low!"));
2700 }
2701
2702 {
2704 "write block and undo data to disk", BCLog::BENCH);
2705
2706 // First make sure all block and undo data is flushed to
2707 // disk.
2708 // TODO: Handle return error, or add detailed comment why
2709 // it is safe to not return an error upon failure.
2711 m_chain.Height())) {
2713 "%s: Failed to flush block file.\n",
2714 __func__);
2715 }
2716 }
2717 // Then update all block file information (which may refer to
2718 // block and undo files).
2719 {
2720 LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk",
2721 BCLog::BENCH);
2722
2723 if (!m_blockman.WriteBlockIndexDB()) {
2724 return FatalError(
2726 "Failed to write to block index database");
2727 }
2728 }
2729
2730 // Finally remove any pruned files
2731 if (fFlushForPrune) {
2732 LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files",
2733 BCLog::BENCH);
2734
2735 m_blockman.UnlinkPrunedFiles(setFilesToPrune);
2736 }
2737
2738 if (!CoinsTip().GetBestBlock().IsNull()) {
2739 if (coins_mem_usage >= WARN_FLUSH_COINS_SIZE) {
2740 LogWarning("Flushing large (%d GiB) UTXO set to disk, "
2741 "it may take several minutes\n",
2742 coins_mem_usage >> 30);
2743 }
2745 strprintf(
2746 "write coins cache to disk (%d coins, %.2fKiB)",
2747 coins_count, coins_mem_usage >> 10),
2748 BCLog::BENCH);
2749
2750 // Typical Coin structures on disk are around 48 bytes in
2751 // size. Pushing a new one to the database can cause it to
2752 // be written twice (once in the log, and once in the
2753 // tables). This is already an overestimation, as most will
2754 // delete an existing entry or overwrite one. Still, use a
2755 // conservative safety factor of 2.
2757 48 * 2 * 2 *
2758 CoinsTip().GetCacheSize())) {
2759 return FatalError(m_chainman.GetNotifications(), state,
2760 "Disk space is too low!",
2761 _("Disk space is too low!"));
2762 }
2763
2764 // Flush the chainstate (which may refer to block index
2765 // entries).
2766 const auto empty_cache{(mode == FlushStateMode::ALWAYS) ||
2767 fCacheLarge || fCacheCritical};
2768 if (empty_cache ? !CoinsTip().Flush()
2769 : !CoinsTip().Sync()) {
2770 return FatalError(m_chainman.GetNotifications(), state,
2771 "Failed to write to coin database");
2772 }
2773 full_flush_completed = true;
2774 TRACE5(utxocache, flush,
2775 int64_t{Ticks<std::chrono::microseconds>(
2776 SteadyClock::now() - nNow)},
2777 uint32_t(mode), coins_count,
2778 uint64_t(coins_mem_usage), fFlushForPrune);
2779 }
2780 }
2781
2782 if (should_write || m_next_write == NodeClock::time_point::max()) {
2783 constexpr auto range{DATABASE_WRITE_INTERVAL_MAX -
2787 }
2788 }
2789
2790 if (full_flush_completed) {
2791 // Update best block in wallet (so we can detect restored wallets).
2792 GetMainSignals().ChainStateFlushed(this->GetRole(),
2794 }
2795 } catch (const std::runtime_error &e) {
2796 return FatalError(m_chainman.GetNotifications(), state,
2797 std::string("System error while flushing: ") +
2798 e.what());
2799 }
2800 return true;
2801}
2802
2805 if (!this->FlushStateToDisk(state, FlushStateMode::ALWAYS)) {
2806 LogPrintf("%s: failed to flush state (%s)\n", __func__,
2807 state.ToString());
2808 }
2809}
2810
2814 if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2815 LogPrintf("%s: failed to flush state (%s)\n", __func__,
2816 state.ToString());
2817 }
2818}
2819
2820static void UpdateTipLog(const CCoinsViewCache &coins_tip,
2821 const CBlockIndex *tip, const CChainParams &params,
2822 const std::string &func_name,
2823 const std::string &prefix)
2826
2827 // Disable rate limiting in LogPrintLevel_ so this source location may log
2828 // during IBD.
2830 BCLog::LogFlags::ALL, BCLog::Level::Info,
2831 /*should_ratelimit=*/false,
2832 "%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%ld "
2833 "date='%s' progress=%f cache=%.1fMiB(%utxo)\n",
2834 prefix, func_name, tip->GetBlockHash().ToString(), tip->nHeight,
2835 tip->nVersion, log(tip->nChainWork.getdouble()) / log(2.0),
2837 GuessVerificationProgress(params.TxData(), tip),
2838 coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
2839 coins_tip.GetCacheSize());
2840}
2841
2842void Chainstate::UpdateTip(const CBlockIndex *pindexNew) {
2844 const auto &coins_tip = CoinsTip();
2845
2846 const CChainParams &params{m_chainman.GetParams()};
2847
2848 // The remainder of the function isn't relevant if we are not acting on
2849 // the active chainstate, so return if need be.
2850 if (this != &m_chainman.ActiveChainstate()) {
2851 // Only log every so often so that we don't bury log messages at the
2852 // tip.
2853 constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2854 if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2855 UpdateTipLog(coins_tip, pindexNew, params, __func__,
2856 "[background validation] ");
2857 }
2858 return;
2859 }
2860
2861 // New best block
2862 if (m_mempool) {
2864 }
2865
2866 {
2868 g_best_block = pindexNew;
2869 g_best_block_cv.notify_all();
2870 }
2871
2872 UpdateTipLog(coins_tip, pindexNew, params, __func__, "");
2873}
2874
2887 DisconnectedBlockTransactions *disconnectpool) {
2889 if (m_mempool) {
2891 }
2892
2893 CBlockIndex *pindexDelete = m_chain.Tip();
2894
2895 assert(pindexDelete);
2896 assert(pindexDelete->pprev);
2897
2898 // Read block from disk.
2899 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2900 CBlock &block = *pblock;
2901 if (!m_blockman.ReadBlock(block, *pindexDelete)) {
2902 LogError("DisconnectTip(): Failed to read block\n");
2903 return false;
2904 }
2905
2906 // Apply the block atomically to the chain state.
2907 const auto time_start{SteadyClock::now()};
2908 {
2909 CCoinsViewCache view(&CoinsTip());
2910 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2911 if (DisconnectBlock(block, pindexDelete, view) !=
2913 LogError("DisconnectTip(): DisconnectBlock %s failed\n",
2914 pindexDelete->GetBlockHash().ToString());
2915 return false;
2916 }
2917
2918 bool flushed = view.Flush();
2919 assert(flushed);
2920 }
2921 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n",
2922 Ticks<MillisecondsDouble>(SteadyClock::now() - time_start));
2923
2924 {
2925 // Prune locks that began at or after the tip should be moved backward
2926 // so they get a chance to reorg
2927 const int max_height_first{pindexDelete->nHeight - 1};
2928 for (auto &prune_lock : m_blockman.m_prune_locks) {
2929 if (prune_lock.second.height_first <= max_height_first) {
2930 continue;
2931 }
2932
2933 prune_lock.second.height_first = max_height_first;
2934 LogPrint(BCLog::PRUNE, "%s prune lock moved back to %d\n",
2935 prune_lock.first, max_height_first);
2936 }
2937 }
2938
2939 // Write the chain state to disk, if necessary.
2941 return false;
2942 }
2943
2944 if (m_mempool) {
2945 // If this block is deactivating a fork, we move all mempool
2946 // transactions in front of disconnectpool for reprocessing in a future
2947 // updateMempoolForReorg call
2948 if (pindexDelete->pprev != nullptr &&
2949 GetNextBlockScriptFlags(pindexDelete, m_chainman) !=
2950 GetNextBlockScriptFlags(pindexDelete->pprev, m_chainman)) {
2952 "Disconnecting mempool due to rewind of upgrade block\n");
2953 if (disconnectpool) {
2954 disconnectpool->importMempool(*m_mempool);
2955 }
2956 m_mempool->clear();
2957 }
2958
2959 if (disconnectpool) {
2960 disconnectpool->addForBlock(block.vtx, *m_mempool);
2961 }
2962 }
2963
2964 m_chain.SetTip(*pindexDelete->pprev);
2965
2966 UpdateTip(pindexDelete->pprev);
2967 // Let wallets know transactions went from 1-confirmed to
2968 // 0-confirmed or conflicted:
2969 GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2970 return true;
2971}
2972
2973static SteadyClock::duration time_read_from_disk_total{};
2974static SteadyClock::duration time_connect_total{};
2975static SteadyClock::duration time_flush{};
2976static SteadyClock::duration time_chainstate{};
2977static SteadyClock::duration time_post_connect{};
2978
2984 BlockPolicyValidationState &blockPolicyState,
2985 CBlockIndex *pindexNew,
2986 const std::shared_ptr<const CBlock> &pblock,
2987 DisconnectedBlockTransactions &disconnectpool,
2988 const avalanche::Processor *const avalanche,
2989 const ChainstateRole chainstate_role) {
2991 if (m_mempool) {
2993 }
2994
2995 const Consensus::Params &consensusParams = m_chainman.GetConsensus();
2996
2997 assert(pindexNew->pprev == m_chain.Tip());
2998 // Read block from disk.
2999 const auto time_1{SteadyClock::now()};
3000 std::shared_ptr<const CBlock> pthisBlock;
3001 if (!pblock) {
3002 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3003 if (!m_blockman.ReadBlock(*pblockNew, *pindexNew)) {
3004 return FatalError(m_chainman.GetNotifications(), state,
3005 "Failed to read block");
3006 }
3007 pthisBlock = pblockNew;
3008 } else {
3009 pthisBlock = pblock;
3010 }
3011
3012 const CBlock &blockConnecting = *pthisBlock;
3013
3014 // Apply the block atomically to the chain state.
3015 const auto time_2{SteadyClock::now()};
3016 time_read_from_disk_total += time_2 - time_1;
3017 SteadyClock::time_point time_3;
3019 " - Load block from disk: %.2fms [%.2fs (%.2fms/blk)]\n",
3020 Ticks<MillisecondsDouble>(time_2 - time_1),
3021 Ticks<SecondsDouble>(time_read_from_disk_total),
3022 Ticks<MillisecondsDouble>(time_read_from_disk_total) /
3024 {
3025 Amount blockFees{Amount::zero()};
3026 CCoinsViewCache view(&CoinsTip());
3027 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view,
3029 &blockFees);
3030 GetMainSignals().BlockChecked(blockConnecting, state);
3031 if (!rv) {
3032 if (state.IsInvalid()) {
3033 InvalidBlockFound(pindexNew, state);
3034 }
3035
3036 LogError("%s: ConnectBlock %s failed, %s\n", __func__,
3037 pindexNew->GetBlockHash().ToString(), state.ToString());
3038 return false;
3039 }
3040
3052 const BlockHash blockhash = pindexNew->GetBlockHash();
3056
3057 const Amount blockReward =
3058 blockFees +
3059 GetBlockSubsidy(pindexNew->nHeight, consensusParams);
3060
3061 std::vector<std::unique_ptr<ParkingPolicy>> parkingPolicies;
3062 parkingPolicies.emplace_back(std::make_unique<MinerFundPolicy>(
3063 consensusParams, *pindexNew, blockConnecting, blockReward));
3064
3065 if (avalanche) {
3066 // Only enable the RTT policy if the node already finalized a
3067 // block. This is because it's very possible that new blocks
3068 // will be parked after a node restart (but after IBD) if the
3069 // node is behind by a few blocks. We want to make sure that the
3070 // node will be able to switch back to the right tip in this
3071 // case.
3072 if (avalanche->hasFinalizedTip()) {
3073 // Special case for testnet, don't reject blocks mined with
3074 // the min difficulty
3075 if (!consensusParams.fPowAllowMinDifficultyBlocks ||
3076 (blockConnecting.GetBlockTime() <=
3077 pindexNew->pprev->GetBlockTime() +
3078 2 * consensusParams.nPowTargetSpacing)) {
3079 parkingPolicies.emplace_back(
3080 std::make_unique<RTTPolicy>(consensusParams,
3081 *pindexNew));
3082 }
3083 }
3084
3085 parkingPolicies.emplace_back(
3086 std::make_unique<StakingRewardsPolicy>(
3087 *avalanche, consensusParams, *pindexNew,
3088 blockConnecting, blockReward));
3089
3090 if (m_mempool) {
3091 parkingPolicies.emplace_back(
3092 std::make_unique<PreConsensusPolicy>(
3093 *avalanche, *pindexNew, blockConnecting,
3094 m_mempool));
3095 }
3096 }
3097
3098 // If any block policy is violated, bail on the first one found
3099 if (std::find_if_not(parkingPolicies.begin(), parkingPolicies.end(),
3100 [&](const auto &policy) {
3101 bool ret = (*policy)(blockPolicyState);
3102 if (!ret) {
3103 LogPrintf(
3104 "Park block because it "
3105 "violated a block policy: %s\n",
3106 blockPolicyState.ToString());
3107 }
3108 return ret;
3109 }) != parkingPolicies.end()) {
3110 pindexNew->nStatus = pindexNew->nStatus.withParked();
3111 m_blockman.m_dirty_blockindex.insert(pindexNew);
3112 return false;
3113 }
3114 }
3115
3116 time_3 = SteadyClock::now();
3117 time_connect_total += time_3 - time_2;
3119 LogPrint(
3120 BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n",
3121 Ticks<MillisecondsDouble>(time_3 - time_2),
3122 Ticks<SecondsDouble>(time_connect_total),
3123 Ticks<MillisecondsDouble>(time_connect_total) / num_blocks_total);
3124 bool flushed = view.Flush();
3125 assert(flushed);
3126 }
3127
3128 const auto time_4{SteadyClock::now()};
3129 time_flush += time_4 - time_3;
3130 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n",
3131 Ticks<MillisecondsDouble>(time_4 - time_3),
3132 Ticks<SecondsDouble>(time_flush),
3133 Ticks<MillisecondsDouble>(time_flush) / num_blocks_total);
3134 // Write the chain state to disk, if necessary.
3135 if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
3136 return false;
3137 }
3138 const auto time_5{SteadyClock::now()};
3139 time_chainstate += time_5 - time_4;
3141 " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n",
3142 Ticks<MillisecondsDouble>(time_5 - time_4),
3143 Ticks<SecondsDouble>(time_chainstate),
3144 Ticks<MillisecondsDouble>(time_chainstate) / num_blocks_total);
3145 // Remove conflicting transactions from the mempool.
3146 if (m_mempool) {
3147 disconnectpool.removeForBlock(blockConnecting.vtx, *m_mempool);
3148
3149 // If this block is activating a fork, we move all mempool transactions
3150 // in front of disconnectpool for reprocessing in a future
3151 // updateMempoolForReorg call
3152 if (pindexNew->pprev != nullptr &&
3153 GetNextBlockScriptFlags(pindexNew, m_chainman) !=
3154 GetNextBlockScriptFlags(pindexNew->pprev, m_chainman)) {
3155 LogPrint(
3157 "Disconnecting mempool due to acceptance of upgrade block\n");
3158 disconnectpool.importMempool(*m_mempool);
3159 }
3160 }
3161
3162 // Update m_chain & related variables.
3163 m_chain.SetTip(*pindexNew);
3164 UpdateTip(pindexNew);
3165
3166 const auto time_6{SteadyClock::now()};
3167 time_post_connect += time_6 - time_5;
3168 time_total += time_6 - time_1;
3170 " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n",
3171 Ticks<MillisecondsDouble>(time_6 - time_5),
3172 Ticks<SecondsDouble>(time_post_connect),
3173 Ticks<MillisecondsDouble>(time_post_connect) / num_blocks_total);
3174 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n",
3175 Ticks<MillisecondsDouble>(time_6 - time_1),
3176 Ticks<SecondsDouble>(time_total),
3177 Ticks<MillisecondsDouble>(time_total) / num_blocks_total);
3178
3179 // If we are the background validation chainstate, check to see if we are
3180 // done validating the snapshot (i.e. our tip has reached the snapshot's
3181 // base block).
3182 if (this != &m_chainman.ActiveChainstate()) {
3183 // This call may set `m_disabled`, which is referenced immediately
3184 // afterwards in ActivateBestChain, so that we stop connecting blocks
3185 // past the snapshot base.
3186 m_chainman.MaybeCompleteSnapshotValidation();
3187 }
3188
3189 GetMainSignals().BlockConnected(chainstate_role, pthisBlock, pindexNew);
3190 return true;
3191}
3192
3198 std::vector<const CBlockIndex *> &blocksToReconcile, bool fAutoUnpark) {
3200 do {
3201 CBlockIndex *pindexNew = nullptr;
3202
3203 // Find the best candidate header.
3204 {
3205 std::set<CBlockIndex *, CBlockIndexWorkComparator>::reverse_iterator
3206 it = setBlockIndexCandidates.rbegin();
3207 if (it == setBlockIndexCandidates.rend()) {
3208 return nullptr;
3209 }
3210 pindexNew = *it;
3211 }
3212
3213 // If this block will cause an avalanche finalized block to be reorged,
3214 // then we park it.
3215 {
3217 if (m_avalancheFinalizedBlockIndex &&
3218 !AreOnTheSameFork(pindexNew, m_avalancheFinalizedBlockIndex)) {
3219 LogPrintf("Park block %s because it forks prior to the "
3220 "avalanche finalized chaintip.\n",
3221 pindexNew->GetBlockHash().ToString());
3222 pindexNew->nStatus = pindexNew->nStatus.withParked();
3223 m_blockman.m_dirty_blockindex.insert(pindexNew);
3224 }
3225 }
3226
3227 const CBlockIndex *pindexFork = m_chain.FindFork(pindexNew);
3228
3229 // Check whether all blocks on the path between the currently active
3230 // chain and the candidate are valid. Just going until the active chain
3231 // is an optimization, as we know all blocks in it are valid already.
3232 CBlockIndex *pindexTest = pindexNew;
3233 bool hasValidAncestor = true;
3234 while (hasValidAncestor && pindexTest && pindexTest != pindexFork) {
3235 assert(pindexTest->HaveNumChainTxs() || pindexTest->nHeight == 0);
3236
3237 // If this is a parked chain, but it has enough PoW, clear the park
3238 // state.
3239 bool fParkedChain = pindexTest->nStatus.isOnParkedChain();
3240 if (fAutoUnpark && fParkedChain) {
3241 const CBlockIndex *pindexTip = m_chain.Tip();
3242
3243 // During initialization, pindexTip and/or pindexFork may be
3244 // null. In this case, we just ignore the fact that the chain is
3245 // parked.
3246 if (!pindexTip || !pindexFork) {
3247 UnparkBlock(pindexTest);
3248 continue;
3249 }
3250
3251 // A parked chain can be unparked if it has twice as much PoW
3252 // accumulated as the main chain has since the fork block.
3253 CBlockIndex const *pindexExtraPow = pindexTip;
3254 arith_uint256 requiredWork = pindexTip->nChainWork;
3255 switch (pindexTip->nHeight - pindexFork->nHeight) {
3256 // Limit the penality for depth 1, 2 and 3 to half a block
3257 // worth of work to ensure we don't fork accidentally.
3258 case 3:
3259 case 2:
3260 pindexExtraPow = pindexExtraPow->pprev;
3261 // FALLTHROUGH
3262 case 1: {
3263 const arith_uint256 deltaWork =
3264 pindexExtraPow->nChainWork - pindexFork->nChainWork;
3265 requiredWork += (deltaWork >> 1);
3266 break;
3267 }
3268 default:
3269 requiredWork +=
3270 pindexExtraPow->nChainWork - pindexFork->nChainWork;
3271 break;
3272 }
3273
3274 if (pindexNew->nChainWork > requiredWork) {
3275 // We have enough, clear the parked state.
3276 LogPrintf("Unpark chain up to block %s as it has "
3277 "accumulated enough PoW.\n",
3278 pindexNew->GetBlockHash().ToString());
3279 fParkedChain = false;
3280 UnparkBlock(pindexTest);
3281 }
3282 }
3283
3284 // Pruned nodes may have entries in setBlockIndexCandidates for
3285 // which block files have been deleted. Remove those as candidates
3286 // for the most work chain if we come across them; we can't switch
3287 // to a chain unless we have all the non-active-chain parent blocks.
3288 bool fInvalidChain = pindexTest->nStatus.isInvalid();
3289 bool fMissingData = !pindexTest->nStatus.hasData();
3290 if (!(fInvalidChain || fParkedChain || fMissingData)) {
3291 // The current block is acceptable, move to the parent, up to
3292 // the fork point.
3293 pindexTest = pindexTest->pprev;
3294 continue;
3295 }
3296
3297 // Candidate chain is not usable (either invalid or parked or
3298 // missing data)
3299 hasValidAncestor = false;
3300 setBlockIndexCandidates.erase(pindexTest);
3301
3302 if (fInvalidChain && (m_chainman.m_best_invalid == nullptr ||
3303 pindexNew->nChainWork >
3304 m_chainman.m_best_invalid->nChainWork)) {
3305 m_chainman.m_best_invalid = pindexNew;
3306 }
3307
3308 if (fParkedChain && (m_chainman.m_best_parked == nullptr ||
3309 pindexNew->nChainWork >
3310 m_chainman.m_best_parked->nChainWork)) {
3311 m_chainman.m_best_parked = pindexNew;
3312 }
3313
3314 LogPrintf("Considered switching to better tip %s but that chain "
3315 "contains a%s%s%s block.\n",
3316 pindexNew->GetBlockHash().ToString(),
3317 fInvalidChain ? "n invalid" : "",
3318 fParkedChain ? " parked" : "",
3319 fMissingData ? " missing-data" : "");
3320
3321 CBlockIndex *pindexFailed = pindexNew;
3322 // Remove the entire chain from the set.
3323 while (pindexTest != pindexFailed) {
3324 if (fInvalidChain || fParkedChain) {
3325 pindexFailed->nStatus =
3326 pindexFailed->nStatus.withFailedParent(fInvalidChain)
3327 .withParkedParent(fParkedChain);
3328 } else if (fMissingData) {
3329 // If we're missing data, then add back to
3330 // m_blocks_unlinked, so that if the block arrives in the
3331 // future we can try adding to setBlockIndexCandidates
3332 // again.
3334 std::make_pair(pindexFailed->pprev, pindexFailed));
3335 }
3336 setBlockIndexCandidates.erase(pindexFailed);
3337 pindexFailed = pindexFailed->pprev;
3338 }
3339
3340 if (fInvalidChain || fParkedChain) {
3341 // We discovered a new chain tip that is either parked or
3342 // invalid, we may want to warn.
3344 }
3345 }
3346
3347 blocksToReconcile.push_back(pindexNew);
3348
3349 // We found a candidate that has valid ancestors. This is our guy.
3350 if (hasValidAncestor) {
3351 return pindexNew;
3352 }
3353 } while (true);
3354}
3355
3361 // Note that we can't delete the current block itself, as we may need to
3362 // return to it later in case a reorganization to a better block fails.
3363 auto it = setBlockIndexCandidates.begin();
3364 while (it != setBlockIndexCandidates.end() &&
3365 setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
3366 setBlockIndexCandidates.erase(it++);
3367 }
3368
3369 // Either the current tip or a successor of it we're working towards is left
3370 // in setBlockIndexCandidates.
3372}
3373
3382 BlockValidationState &state, CBlockIndex *pindexMostWork,
3383 const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
3384 const avalanche::Processor *const avalanche,
3385 const ChainstateRole chainstate_role) {
3387 if (m_mempool) {
3389 }
3390
3391 const CBlockIndex *pindexOldTip = m_chain.Tip();
3392 const CBlockIndex *pindexFork = m_chain.FindFork(pindexMostWork);
3393
3394 // Disconnect active blocks which are no longer in the best chain.
3395 bool fBlocksDisconnected = false;
3396 DisconnectedBlockTransactions disconnectpool;
3397 while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
3398 if (m_mempool && !fBlocksDisconnected) {
3399 // Import and clear mempool; we must do this to preserve
3400 // topological ordering in the mempool index. This is ok since
3401 // inserts into the mempool are very fast now in our new
3402 // implementation.
3403 disconnectpool.importMempool(*m_mempool);
3404 }
3405
3406 if (!DisconnectTip(state, &disconnectpool)) {
3407 // This is likely a fatal error, but keep the mempool consistent,
3408 // just in case. Only remove from the mempool in this case.
3409 if (m_mempool) {
3410 disconnectpool.updateMempoolForReorg(*this, false, *m_mempool);
3411 }
3412
3413 // If we're unable to disconnect a block during normal operation,
3414 // then that is a failure of our local system -- we should abort
3415 // rather than stay on a less work chain.
3417 "Failed to disconnect block; see debug.log for details");
3418 return false;
3419 }
3420
3421 fBlocksDisconnected = true;
3422 }
3423
3424 // Build list of new blocks to connect.
3425 std::vector<CBlockIndex *> vpindexToConnect;
3426 bool fContinue = true;
3427 int nHeight = pindexFork ? pindexFork->nHeight : -1;
3428 while (fContinue && nHeight != pindexMostWork->nHeight) {
3429 // Don't iterate the entire list of potential improvements toward the
3430 // best tip, as we likely only need a few blocks along the way.
3431 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3432 vpindexToConnect.clear();
3433 vpindexToConnect.reserve(nTargetHeight - nHeight);
3434 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3435 while (pindexIter && pindexIter->nHeight != nHeight) {
3436 vpindexToConnect.push_back(pindexIter);
3437 pindexIter = pindexIter->pprev;
3438 }
3439
3440 nHeight = nTargetHeight;
3441
3442 // Connect new blocks.
3443 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
3444 BlockPolicyValidationState blockPolicyState;
3445 if (!ConnectTip(state, blockPolicyState, pindexConnect,
3446 pindexConnect == pindexMostWork
3447 ? pblock
3448 : std::shared_ptr<const CBlock>(),
3449 disconnectpool, avalanche, chainstate_role)) {
3450 if (state.IsInvalid()) {
3451 // The block violates a consensus rule.
3452 if (state.GetResult() !=
3454 InvalidChainFound(vpindexToConnect.front());
3455 }
3456 state = BlockValidationState();
3457 fInvalidFound = true;
3458 fContinue = false;
3459 break;
3460 }
3461
3462 if (blockPolicyState.IsInvalid()) {
3463 // The block violates a policy rule.
3464 fContinue = false;
3465 break;
3466 }
3467
3468 // A system error occurred (disk space, database error, ...).
3469 // Make the mempool consistent with the current tip, just in
3470 // case any observers try to use it before shutdown.
3471 if (m_mempool) {
3472 disconnectpool.updateMempoolForReorg(*this, false,
3473 *m_mempool);
3474 }
3475 return false;
3476 } else {
3478 if (!pindexOldTip ||
3479 m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
3480 // We're in a better position than we were. Return
3481 // temporarily to release the lock.
3482 fContinue = false;
3483 break;
3484 }
3485 }
3486 }
3487 }
3488
3489 if (m_mempool) {
3490 if (fBlocksDisconnected || !disconnectpool.isEmpty()) {
3491 // If any blocks were disconnected, we need to update the mempool
3492 // even if disconnectpool is empty. The disconnectpool may also be
3493 // non-empty if the mempool was imported due to new validation rules
3494 // being in effect.
3496 "Updating mempool due to reorganization or "
3497 "rules upgrade/downgrade\n");
3498 disconnectpool.updateMempoolForReorg(*this, true, *m_mempool);
3499 }
3500
3501 m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
3502 }
3503
3504 // Callbacks/notifications for a new best chain.
3505 if (fInvalidFound) {
3507 } else {
3509 }
3510
3511 return true;
3512}
3513
3515 if (!init) {
3517 }
3518 if (::fReindex) {
3520 }
3522}
3523
3526 bool fNotify = false;
3527 bool fInitialBlockDownload = false;
3528 static CBlockIndex *pindexHeaderOld = nullptr;
3529 CBlockIndex *pindexHeader = nullptr;
3530 {
3531 LOCK(cs_main);
3532 pindexHeader = chainman.m_best_header;
3533
3534 if (pindexHeader != pindexHeaderOld) {
3535 fNotify = true;
3536 fInitialBlockDownload = chainman.IsInitialBlockDownload();
3537 pindexHeaderOld = pindexHeader;
3538 }
3539 }
3540
3541 // Send block tip changed notifications without cs_main
3542 if (fNotify) {
3543 chainman.GetNotifications().headerTip(
3544 GetSynchronizationState(fInitialBlockDownload),
3545 pindexHeader->nHeight, pindexHeader->nTime, false);
3546 }
3547 return fNotify;
3548}
3549
3552
3553 if (GetMainSignals().CallbacksPending() > 10) {
3555 }
3556}
3557
3559 std::shared_ptr<const CBlock> pblock,
3562
3563 // Note that while we're often called here from ProcessNewBlock, this is
3564 // far from a guarantee. Things in the P2P/RPC will often end up calling
3565 // us in the middle of ProcessNewBlock - do not assume pblock is set
3566 // sanely for performance or correctness!
3568
3569 // ABC maintains a fair degree of expensive-to-calculate internal state
3570 // because this function periodically releases cs_main so that it does not
3571 // lock up other threads for too long during large connects - and to allow
3572 // for e.g. the callback queue to drain we use m_chainstate_mutex to enforce
3573 // mutual exclusion so that only one caller may execute this function at a
3574 // time
3576
3577 // Belt-and-suspenders check that we aren't attempting to advance the
3578 // background chainstate past the snapshot base block.
3579 if (WITH_LOCK(::cs_main, return m_disabled)) {
3580 LogPrintf("m_disabled is set - this chainstate should not be in "
3581 "operation. Please report this as a bug. %s\n",
3582 PACKAGE_BUGREPORT);
3583 return false;
3584 }
3585
3586 CBlockIndex *pindexMostWork = nullptr;
3587 CBlockIndex *pindexNewTip = nullptr;
3588 bool exited_ibd{false};
3589 do {
3590 // Block until the validation queue drains. This should largely
3591 // never happen in normal operation, however may happen during
3592 // reindex, causing memory blowup if we run too far ahead.
3593 // Note that if a validationinterface callback ends up calling
3594 // ActivateBestChain this may lead to a deadlock! We should
3595 // probably have a DEBUG_LOCKORDER test for this in the future.
3597
3598 std::vector<const CBlockIndex *> blocksToReconcile;
3599 bool blocks_connected = false;
3600
3601 {
3602 LOCK(cs_main);
3603 // Lock transaction pool for at least as long as it takes for
3604 // updateMempoolForReorg to be executed if needed
3605 LOCK(MempoolMutex());
3606 const bool was_in_ibd = m_chainman.IsInitialBlockDownload();
3607 CBlockIndex *starting_tip = m_chain.Tip();
3608 do {
3609 // We absolutely may not unlock cs_main until we've made forward
3610 // progress (with the exception of shutdown due to hardware
3611 // issues, low disk space, etc).
3612
3613 if (pindexMostWork == nullptr) {
3614 pindexMostWork = FindMostWorkChain(
3615 blocksToReconcile,
3617 }
3618
3619 // Whether we have anything to do at all.
3620 if (pindexMostWork == nullptr ||
3621 pindexMostWork == m_chain.Tip()) {
3622 break;
3623 }
3624
3625 bool fInvalidFound = false;
3626 std::shared_ptr<const CBlock> nullBlockPtr;
3627 // BlockConnected signals must be sent for the original role;
3628 // in case snapshot validation is completed during
3629 // ActivateBestChainStep, the result of GetRole() changes from
3630 // BACKGROUND to NORMAL.
3631 const ChainstateRole chainstate_role{this->GetRole()};
3633 state, pindexMostWork,
3634 pblock && pblock->GetHash() ==
3635 pindexMostWork->GetBlockHash()
3636 ? pblock
3637 : nullBlockPtr,
3638 fInvalidFound, avalanche, chainstate_role)) {
3639 // A system error occurred
3640 return false;
3641 }
3642 blocks_connected = true;
3643
3644 if (fInvalidFound ||
3645 (pindexMostWork && pindexMostWork->nStatus.isParked())) {
3646 // Wipe cache, we may need another branch now.
3647 pindexMostWork = nullptr;
3648 }
3649
3650 pindexNewTip = m_chain.Tip();
3651
3652 // This will have been toggled in
3653 // ActivateBestChainStep -> ConnectTip ->
3654 // MaybeCompleteSnapshotValidation, if at all, so we should
3655 // catch it here.
3656 //
3657 // Break this do-while to ensure we don't advance past the base
3658 // snapshot.
3659 if (m_disabled) {
3660 break;
3661 }
3662 } while (!m_chain.Tip() ||
3663 (starting_tip && CBlockIndexWorkComparator()(
3664 m_chain.Tip(), starting_tip)));
3665
3666 // Check the index once we're done with the above loop, since
3667 // we're going to release cs_main soon. If the index is in a bad
3668 // state now, then it's better to know immediately rather than
3669 // randomly have it cause a problem in a race.
3671
3672 if (blocks_connected) {
3673 const CBlockIndex *pindexFork = m_chain.FindFork(starting_tip);
3674 bool still_in_ibd = m_chainman.IsInitialBlockDownload();
3675
3676 if (was_in_ibd && !still_in_ibd) {
3677 // Active chainstate has exited IBD
3678 exited_ibd = true;
3679 }
3680
3681 // Notify external listeners about the new tip.
3682 // Enqueue while holding cs_main to ensure that UpdatedBlockTip
3683 // is called in the order in which blocks are connected
3684 if (this == &m_chainman.ActiveChainstate() &&
3685 pindexFork != pindexNewTip) {
3686 // Notify ValidationInterface subscribers
3687 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork,
3688 still_in_ibd);
3689
3690 // Always notify the UI if a new block tip was connected
3692 GetSynchronizationState(still_in_ibd), *pindexNewTip);
3693 }
3694 }
3695 }
3696 // When we reach this point, we switched to a new tip (stored in
3697 // pindexNewTip).
3698 if (avalanche) {
3699 const CBlockIndex *pfinalized =
3701 return m_avalancheFinalizedBlockIndex);
3702 for (const CBlockIndex *pindex : blocksToReconcile) {
3703 avalanche->addToReconcile(pindex);
3704
3705 // Compute staking rewards for all blocks with more chainwork to
3706 // just after the finalized block. We could stop at the fork
3707 // point, but this is more robust.
3708 if (blocks_connected) {
3709 const CBlockIndex *pindexTest = pindex;
3710 while (pindexTest && pindexTest != pfinalized) {
3711 if (pindexTest->nHeight < pindex->nHeight - 3) {
3712 // Only compute up to some max depth
3713 break;
3714 }
3715 avalanche->computeStakingReward(pindexTest);
3716 pindexTest = pindexTest->pprev;
3717 }
3718 }
3719 }
3720 }
3721
3722 if (!blocks_connected) {
3723 return true;
3724 }
3725
3726 if (m_chainman.StopAtHeight() && pindexNewTip &&
3727 pindexNewTip->nHeight >= m_chainman.StopAtHeight()) {
3728 StartShutdown();
3729 }
3730
3731 if (exited_ibd) {
3732 // If a background chainstate is in use, we may need to rebalance
3733 // our allocation of caches once a chainstate exits initial block
3734 // download.
3735 LOCK(::cs_main);
3736 m_chainman.MaybeRebalanceCaches();
3737 }
3738
3739 if (WITH_LOCK(::cs_main, return m_disabled)) {
3740 // Background chainstate has reached the snapshot base block, so
3741 // exit.
3742
3743 // Restart indexes to resume indexing for all blocks unique to the
3744 // snapshot chain. This resumes indexing "in order" from where the
3745 // indexing on the background validation chain left off.
3746 //
3747 // This cannot be done while holding cs_main (within
3748 // MaybeCompleteSnapshotValidation) or a cs_main deadlock will
3749 // occur.
3752 }
3753 break;
3754 }
3755
3756 // We check interrupt only after giving ActivateBestChainStep a chance
3757 // to run once so that we never interrupt before connecting the genesis
3758 // block during LoadChainTip(). Previously this caused an assert()
3759 // failure during interrupt in such cases as the UTXO DB flushing checks
3760 // that the best block hash is non-null.
3761 if (m_chainman.m_interrupt) {
3762 break;
3763 }
3764 } while (pindexNewTip != pindexMostWork);
3765
3766 // Write changes periodically to disk, after relay.
3768 return false;
3769 }
3770
3771 return true;
3772}
3773
3778 {
3779 LOCK(cs_main);
3780 if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
3781 // Nothing to do, this block is not at the tip.
3782 return true;
3783 }
3784
3786 // The chain has been extended since the last call, reset the
3787 // counter.
3789 }
3790
3792 setBlockIndexCandidates.erase(pindex);
3795 std::numeric_limits<int32_t>::min()) {
3796 // We can't keep reducing the counter if somebody really wants to
3797 // call preciousblock 2**31-1 times on the same set of tips...
3799 }
3800
3801 // In case this was parked, unpark it.
3802 UnparkBlock(pindex);
3803
3804 // Make sure it is added to the candidate list if appropriate.
3805 if (pindex->IsValid(BlockValidity::TRANSACTIONS) &&
3806 pindex->HaveNumChainTxs()) {
3807 setBlockIndexCandidates.insert(pindex);
3809 }
3810 }
3811
3812 return ActivateBestChain(state, /*pblock=*/nullptr, avalanche);
3813}
3814
3815namespace {
3816// Leverage RAII to run a functor at scope end
3817template <typename Func> struct Defer {
3818 Func func;
3819 Defer(Func &&f) : func(std::move(f)) {}
3820 ~Defer() { func(); }
3821};
3822} // namespace
3823
3825 bool invalidate) {
3826 // Genesis block can't be invalidated or parked
3827 assert(pindex);
3828 if (pindex->nHeight == 0) {
3829 return false;
3830 }
3831
3832 CBlockIndex *to_mark_failed_or_parked = pindex;
3833 bool pindex_was_in_chain = false;
3834 int disconnected = 0;
3835
3836 // We do not allow ActivateBestChain() to run while UnwindBlock() is
3837 // running, as that could cause the tip to change while we disconnect
3838 // blocks. (Note for backport of Core PR16849: we acquire
3839 // LOCK(m_chainstate_mutex) in the Park, Invalidate and FinalizeBlock
3840 // functions due to differences in our code)
3842
3843 // We'll be acquiring and releasing cs_main below, to allow the validation
3844 // callbacks to run. However, we should keep the block index in a
3845 // consistent state as we disconnect blocks -- in particular we need to
3846 // add equal-work blocks to setBlockIndexCandidates as we disconnect.
3847 // To avoid walking the block index repeatedly in search of candidates,
3848 // build a map once so that we can look up candidate blocks by chain
3849 // work as we go.
3850 std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
3851
3852 {
3853 LOCK(cs_main);
3854 for (auto &entry : m_blockman.m_block_index) {
3855 CBlockIndex *candidate = &entry.second;
3856 // We don't need to put anything in our active chain into the
3857 // multimap, because those candidates will be found and considered
3858 // as we disconnect.
3859 // Instead, consider only non-active-chain blocks that have at
3860 // least as much work as where we expect the new tip to end up.
3861 if (!m_chain.Contains(candidate) &&
3862 !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
3864 candidate->HaveNumChainTxs()) {
3865 candidate_blocks_by_work.insert(
3866 std::make_pair(candidate->nChainWork, candidate));
3867 }
3868 }
3869 }
3870
3871 {
3872 LOCK(cs_main);
3873 // Lock for as long as disconnectpool is in scope to make sure
3874 // UpdateMempoolForReorg is called after DisconnectTip without unlocking
3875 // in between
3876 LOCK(MempoolMutex());
3877
3878 constexpr int maxDisconnectPoolBlocks = 10;
3879 bool ret = false;
3880 DisconnectedBlockTransactions disconnectpool;
3881 // After 10 blocks this becomes nullptr, so that DisconnectTip will
3882 // stop giving us unwound block txs if we are doing a deep unwind.
3883 DisconnectedBlockTransactions *optDisconnectPool = &disconnectpool;
3884
3885 // Disable thread safety analysis because we can't require m_mempool->cs
3886 // as m_mempool can be null. We keep the runtime analysis though.
3887 Defer deferred([&]() NO_THREAD_SAFETY_ANALYSIS {
3889 if (m_mempool && !disconnectpool.isEmpty()) {
3891 // DisconnectTip will add transactions to disconnectpool.
3892 // When all unwinding is done and we are on a new tip, we must
3893 // add all transactions back to the mempool against the new tip.
3894 disconnectpool.updateMempoolForReorg(*this,
3895 /* fAddToMempool = */ ret,
3896 *m_mempool);
3897 }
3898 });
3899
3900 // Disconnect (descendants of) pindex, and mark them invalid.
3901 while (true) {
3902 if (m_chainman.m_interrupt) {
3903 break;
3904 }
3905
3906 // Make sure the queue of validation callbacks doesn't grow
3907 // unboundedly.
3908 // FIXME this commented code is a regression and could cause OOM if
3909 // a very old block is invalidated via the invalidateblock RPC.
3910 // This can be uncommented if the main signals are moved away from
3911 // cs_main or this code is refactored so that cs_main can be
3912 // released at this point.
3913 //
3914 // LimitValidationInterfaceQueue();
3915
3916 if (!m_chain.Contains(pindex)) {
3917 break;
3918 }
3919
3920 if (m_mempool && disconnected == 0) {
3921 // On first iteration, we grab all the mempool txs to preserve
3922 // topological ordering. This has the side-effect of temporarily
3923 // clearing the mempool, but we will re-add later in
3924 // updateMempoolForReorg() (above). This technique guarantees
3925 // mempool consistency as well as ensures that our topological
3926 // entry_id index is always correct.
3927 disconnectpool.importMempool(*m_mempool);
3928 }
3929
3930 pindex_was_in_chain = true;
3931 CBlockIndex *invalid_walk_tip = m_chain.Tip();
3932
3933 // ActivateBestChain considers blocks already in m_chain
3934 // unconditionally valid already, so force disconnect away from it.
3935
3936 ret = DisconnectTip(state, optDisconnectPool);
3937 ++disconnected;
3938
3939 if (optDisconnectPool && disconnected > maxDisconnectPoolBlocks) {
3940 // Stop using the disconnect pool after 10 blocks. After 10
3941 // blocks we no longer add block tx's to the disconnectpool.
3942 // However, when this scope ends we will reconcile what's
3943 // in the pool with the new tip (in the deferred d'tor above).
3944 optDisconnectPool = nullptr;
3945 }
3946
3947 if (!ret) {
3948 return false;
3949 }
3950
3951 assert(invalid_walk_tip->pprev == m_chain.Tip());
3952
3953 // We immediately mark the disconnected blocks as invalid.
3954 // This prevents a case where pruned nodes may fail to
3955 // invalidateblock and be left unable to start as they have no tip
3956 // candidates (as there are no blocks that meet the "have data and
3957 // are not invalid per nStatus" criteria for inclusion in
3958 // setBlockIndexCandidates).
3959
3960 invalid_walk_tip->nStatus =
3961 invalidate ? invalid_walk_tip->nStatus.withFailed()
3962 : invalid_walk_tip->nStatus.withParked();
3963
3964 m_blockman.m_dirty_blockindex.insert(invalid_walk_tip);
3965 setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
3966
3967 if (invalid_walk_tip == to_mark_failed_or_parked->pprev &&
3968 (invalidate ? to_mark_failed_or_parked->nStatus.hasFailed()
3969 : to_mark_failed_or_parked->nStatus.isParked())) {
3970 // We only want to mark the last disconnected block as
3971 // Failed (or Parked); its children need to be FailedParent (or
3972 // ParkedParent) instead.
3973 to_mark_failed_or_parked->nStatus =
3974 (invalidate
3975 ? to_mark_failed_or_parked->nStatus.withFailed(false)
3976 .withFailedParent()
3977 : to_mark_failed_or_parked->nStatus.withParked(false)
3978 .withParkedParent());
3979
3980 m_blockman.m_dirty_blockindex.insert(to_mark_failed_or_parked);
3981 }
3982
3983 // Add any equal or more work headers to setBlockIndexCandidates
3984 auto candidate_it = candidate_blocks_by_work.lower_bound(
3985 invalid_walk_tip->pprev->nChainWork);
3986 while (candidate_it != candidate_blocks_by_work.end()) {
3987 if (!CBlockIndexWorkComparator()(candidate_it->second,
3988 invalid_walk_tip->pprev)) {
3989 setBlockIndexCandidates.insert(candidate_it->second);
3990 candidate_it = candidate_blocks_by_work.erase(candidate_it);
3991 } else {
3992 ++candidate_it;
3993 }
3994 }
3995
3996 // Track the last disconnected block, so we can correct its
3997 // FailedParent (or ParkedParent) status in future iterations, or,
3998 // if it's the last one, call InvalidChainFound on it.
3999 to_mark_failed_or_parked = invalid_walk_tip;
4000 }
4001 }
4002
4004
4005 {
4006 LOCK(cs_main);
4007 if (m_chain.Contains(to_mark_failed_or_parked)) {
4008 // If the to-be-marked invalid block is in the active chain,
4009 // something is interfering and we can't proceed.
4010 return false;
4011 }
4012
4013 // Mark pindex (or the last disconnected block) as invalid (or parked),
4014 // even when it never was in the main chain.
4015 to_mark_failed_or_parked->nStatus =
4016 invalidate ? to_mark_failed_or_parked->nStatus.withFailed()
4017 : to_mark_failed_or_parked->nStatus.withParked();
4018 m_blockman.m_dirty_blockindex.insert(to_mark_failed_or_parked);
4019 if (invalidate) {
4020 m_chainman.m_failed_blocks.insert(to_mark_failed_or_parked);
4021 }
4022
4023 // If any new blocks somehow arrived while we were disconnecting
4024 // (above), then the pre-calculation of what should go into
4025 // setBlockIndexCandidates may have missed entries. This would
4026 // technically be an inconsistency in the block index, but if we clean
4027 // it up here, this should be an essentially unobservable error.
4028 // Loop back over all block index entries and add any missing entries
4029 // to setBlockIndexCandidates.
4030 for (auto &[_, block_index] : m_blockman.m_block_index) {
4031 if (block_index.IsValid(BlockValidity::TRANSACTIONS) &&
4032 block_index.HaveNumChainTxs() &&
4033 !setBlockIndexCandidates.value_comp()(&block_index,
4034 m_chain.Tip())) {
4035 setBlockIndexCandidates.insert(&block_index);
4036 }
4037 }
4038
4039 if (invalidate) {
4040 InvalidChainFound(to_mark_failed_or_parked);
4041 }
4042 }
4043
4044 // Only notify about a new block tip if the active chain was modified.
4045 if (pindex_was_in_chain) {
4048 *to_mark_failed_or_parked->pprev);
4049 }
4050 return true;
4051}
4052
4054 CBlockIndex *pindex) {
4057 // See 'Note for backport of Core PR16849' in Chainstate::UnwindBlock
4059
4060 return UnwindBlock(state, pindex, true);
4061}
4062
4066 // See 'Note for backport of Core PR16849' in Chainstate::UnwindBlock
4068
4069 return UnwindBlock(state, pindex, false);
4070}
4071
4072template <typename F>
4074 CBlockIndex *pindex, F f) {
4075 BlockStatus newStatus = f(pindex->nStatus);
4076 if (pindex->nStatus != newStatus &&
4077 (!pindexBase ||
4078 pindex->GetAncestor(pindexBase->nHeight) == pindexBase)) {
4079 pindex->nStatus = newStatus;
4080 m_blockman.m_dirty_blockindex.insert(pindex);
4081 if (newStatus.isValid()) {
4082 m_chainman.m_failed_blocks.erase(pindex);
4083 }
4084
4085 if (pindex->IsValid(BlockValidity::TRANSACTIONS) &&
4086 pindex->HaveNumChainTxs() &&
4087 setBlockIndexCandidates.value_comp()(m_chain.Tip(), pindex)) {
4088 setBlockIndexCandidates.insert(pindex);
4089 }
4090 return true;
4091 }
4092 return false;
4093}
4094
4095template <typename F, typename C, typename AC>
4097 F f, C fChild, AC fAncestorWasChanged) {
4099
4100 // Update the current block and ancestors; while we're doing this, identify
4101 // which was the deepest ancestor we changed.
4102 CBlockIndex *pindexDeepestChanged = pindex;
4103 for (auto pindexAncestor = pindex; pindexAncestor != nullptr;
4104 pindexAncestor = pindexAncestor->pprev) {
4105 if (UpdateFlagsForBlock(nullptr, pindexAncestor, f)) {
4106 pindexDeepestChanged = pindexAncestor;
4107 }
4108 }
4109
4110 if (pindexReset &&
4111 pindexReset->GetAncestor(pindexDeepestChanged->nHeight) ==
4112 pindexDeepestChanged) {
4113 // reset pindexReset if it had a modified ancestor.
4114 pindexReset = nullptr;
4115 }
4116
4117 // Update all blocks under modified blocks.
4118 for (auto &[_, block_index] : m_blockman.m_block_index) {
4119 UpdateFlagsForBlock(pindex, &block_index, fChild);
4120 UpdateFlagsForBlock(pindexDeepestChanged, &block_index,
4121 fAncestorWasChanged);
4122 }
4123}
4124
4125void Chainstate::SetBlockFailureFlags(CBlockIndex *invalid_block) {
4127
4128 for (auto &[_, block_index] : m_blockman.m_block_index) {
4129 if (block_index.GetAncestor(invalid_block->nHeight) == invalid_block &&
4130 !block_index.nStatus.isInvalid()) {
4131 block_index.nStatus = block_index.nStatus.withFailedParent();
4132 }
4133 }
4134}
4135
4138
4140 pindex, m_chainman.m_best_invalid,
4141 [](const BlockStatus status) {
4142 return status.withClearedFailureFlags();
4143 },
4144 [](const BlockStatus status) {
4145 return status.withClearedFailureFlags();
4146 },
4147 [](const BlockStatus status) {
4148 return status.withFailedParent(false);
4149 });
4150}
4151
4154 // The block only is a candidate for the most-work-chain if it has the same
4155 // or more work than our current tip.
4156 if (m_chain.Tip() != nullptr &&
4157 setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
4158 return;
4159 }
4160
4161 bool is_active_chainstate = this == &m_chainman.ActiveChainstate();
4162 if (is_active_chainstate) {
4163 // The active chainstate should always add entries that have more
4164 // work than the tip.
4165 setBlockIndexCandidates.insert(pindex);
4166 } else if (!m_disabled) {
4167 // For the background chainstate, we only consider connecting blocks
4168 // towards the snapshot base (which can't be nullptr or else we'll
4169 // never make progress).
4170 const CBlockIndex *snapshot_base{
4171 Assert(m_chainman.GetSnapshotBaseBlock())};
4172 if (snapshot_base->GetAncestor(pindex->nHeight) == pindex) {
4173 setBlockIndexCandidates.insert(pindex);
4174 }
4175 }
4176}
4177
4178void Chainstate::UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren) {
4180
4182 pindex, m_chainman.m_best_parked,
4183 [](const BlockStatus status) {
4184 return status.withClearedParkedFlags();
4185 },
4186 [fClearChildren](const BlockStatus status) {
4187 return fClearChildren ? status.withClearedParkedFlags()
4188 : status.withParkedParent(false);
4189 },
4190 [](const BlockStatus status) {
4191 return status.withParkedParent(false);
4192 });
4193}
4194
4196 return UnparkBlockImpl(pindex, true);
4197}
4198
4200 return UnparkBlockImpl(pindex, false);
4201}
4202
4203bool Chainstate::AvalancheFinalizeBlock(CBlockIndex *pindex,
4207
4208 if (!pindex) {
4209 return false;
4210 }
4211
4212 if (!m_chain.Contains(pindex)) {
4214 "The block to mark finalized by avalanche is not on the "
4215 "active chain: %s\n",
4216 pindex->GetBlockHash().ToString());
4217 return false;
4218 }
4219
4220 if (IsBlockAvalancheFinalized(pindex)) {
4221 return true;
4222 }
4223
4224 {
4226 m_avalancheFinalizedBlockIndex = pindex;
4227 }
4228
4230
4231 return true;
4232}
4233
4236 m_avalancheFinalizedBlockIndex = nullptr;
4237}
4238
4241 return pindex && m_avalancheFinalizedBlockIndex &&
4242 m_avalancheFinalizedBlockIndex->GetAncestor(pindex->nHeight) ==
4243 pindex;
4244}
4245
4251 CBlockIndex *pindexNew,
4252 const FlatFilePos &pos) {
4253 pindexNew->nTx = block.vtx.size();
4254 // Typically nChainTX will be 0 at this point, but it can be nonzero if this
4255 // is a pruned block which is being downloaded again, or if this is an
4256 // assumeutxo snapshot block which has a hardcoded m_chain_tx_count value
4257 // from the snapshot metadata. If the pindex is not the snapshot block and
4258 // the nChainTx value is not zero, assert that value is actually correct.
4259 auto prev_tx_sum = [](CBlockIndex &block) {
4260 return block.nTx + (block.pprev ? block.pprev->nChainTx : 0);
4261 };
4262 if (!Assume(pindexNew->nChainTx == 0 ||
4263 pindexNew->nChainTx == prev_tx_sum(*pindexNew) ||
4264 pindexNew == GetSnapshotBaseBlock())) {
4265 LogPrintf("Internal bug detected: block %d has unexpected nChainTx %i "
4266 "that should be %i. Please report this issue here: %s\n",
4267 pindexNew->nHeight, pindexNew->nChainTx,
4268 prev_tx_sum(*pindexNew), PACKAGE_BUGREPORT);
4269 pindexNew->nChainTx = 0;
4270 }
4271 pindexNew->nSize = ::GetSerializeSize(block);
4272 pindexNew->nFile = pos.nFile;
4273 pindexNew->nDataPos = pos.nPos;
4274 pindexNew->nUndoPos = 0;
4275 pindexNew->nStatus = pindexNew->nStatus.withData();
4277 m_blockman.m_dirty_blockindex.insert(pindexNew);
4278
4279 if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveNumChainTxs()) {
4280 // If pindexNew is the genesis block or all parents are
4281 // BLOCK_VALID_TRANSACTIONS.
4282 std::deque<CBlockIndex *> queue;
4283 queue.push_back(pindexNew);
4284
4285 // Recursively process any descendant blocks that now may be eligible to
4286 // be connected.
4287 while (!queue.empty()) {
4288 CBlockIndex *pindex = queue.front();
4289 queue.pop_front();
4290 // Before setting nChainTx, assert that it is 0 or already set to
4291 // the correct value. This assert will fail after receiving the
4292 // assumeutxo snapshot block if assumeutxo snapshot metadata has an
4293 // incorrect hardcoded AssumeutxoData::nChainTx value.
4294 if (!Assume(pindex->nChainTx == 0 ||
4295 pindex->nChainTx == prev_tx_sum(*pindex))) {
4296 LogPrintf(
4297 "Internal bug detected: block %d has unexpected nChainTx "
4298 "%i that should be %i. Please report this issue here: %s\n",
4299 pindex->nHeight, pindex->nChainTx, prev_tx_sum(*pindex),
4300 PACKAGE_BUGREPORT);
4301 }
4302 pindex->nChainTx = prev_tx_sum(*pindex);
4303 if (pindex->nSequenceId == 0) {
4304 // We assign a sequence is when transaction are received to
4305 // prevent a miner from being able to broadcast a block but not
4306 // its content. However, a sequence id may have been set
4307 // manually, for instance via PreciousBlock, in which case, we
4308 // don't need to assign one.
4309 pindex->nSequenceId = nBlockSequenceId++;
4310 }
4311 for (Chainstate *c : GetAll()) {
4312 c->TryAddBlockIndexCandidate(pindex);
4313 }
4314
4315 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
4316 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
4317 range = m_blockman.m_blocks_unlinked.equal_range(pindex);
4318 while (range.first != range.second) {
4319 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it =
4320 range.first;
4321 queue.push_back(it->second);
4322 range.first++;
4323 m_blockman.m_blocks_unlinked.erase(it);
4324 }
4325 }
4326 } else if (pindexNew->pprev &&
4327 pindexNew->pprev->IsValid(BlockValidity::TREE)) {
4329 std::make_pair(pindexNew->pprev, pindexNew));
4330 }
4331}
4332
4341static bool CheckBlockHeader(const CBlockHeader &block,
4342 BlockValidationState &state,
4343 const Consensus::Params &params,
4344 BlockValidationOptions validationOptions) {
4345 // Check proof of work matches claimed amount
4346 if (validationOptions.shouldValidatePoW() &&
4347 !CheckProofOfWork(block.GetHash(), block.nBits, params)) {
4349 "high-hash", "proof of work failed");
4350 }
4351
4352 return true;
4353}
4354
4355static bool CheckMerkleRoot(const CBlock &block, BlockValidationState &state) {
4356 if (block.m_checked_merkle_root) {
4357 return true;
4358 }
4359
4360 bool mutated;
4361 uint256 merkle_root = BlockMerkleRoot(block, &mutated);
4362 if (block.hashMerkleRoot != merkle_root) {
4363 return state.Invalid(
4365 /*reject_reason=*/"bad-txnmrklroot",
4366 /*debug_message=*/"hashMerkleRoot mismatch");
4367 }
4368
4369 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
4370 // of transactions in a block without affecting the merkle root of a block,
4371 // while still invalidating it.
4372 if (mutated) {
4373 return state.Invalid(
4375 /*reject_reason=*/"bad-txns-duplicate",
4376 /*debug_message=*/"duplicate transaction");
4377 }
4378
4379 block.m_checked_merkle_root = true;
4380 return true;
4381}
4382
4383bool CheckBlock(const CBlock &block, BlockValidationState &state,
4384 const Consensus::Params &params,
4385 BlockValidationOptions validationOptions) {
4386 // These are checks that are independent of context.
4387 if (block.fChecked) {
4388 return true;
4389 }
4390
4391 // Check that the header is valid (particularly PoW). This is mostly
4392 // redundant with the call in AcceptBlockHeader.
4393 if (!CheckBlockHeader(block, state, params, validationOptions)) {
4394 return false;
4395 }
4396
4397 // Check the merkle root.
4398 if (validationOptions.shouldValidateMerkleRoot() &&
4399 !CheckMerkleRoot(block, state)) {
4400 return false;
4401 }
4402
4403 // All potential-corruption validation must be done before we do any
4404 // transaction validation, as otherwise we may mark the header as invalid
4405 // because we receive the wrong transactions for it.
4406
4407 // First transaction must be coinbase.
4408 if (block.vtx.empty()) {
4410 "bad-cb-missing", "first tx is not coinbase");
4411 }
4412
4413 // Size limits.
4414 auto nMaxBlockSize = validationOptions.getExcessiveBlockSize();
4415
4416 // Bail early if there is no way this block is of reasonable size.
4417 if ((block.vtx.size() * MIN_TRANSACTION_SIZE) > nMaxBlockSize) {
4419 "bad-blk-length", "size limits failed");
4420 }
4421
4422 auto currentBlockSize = ::GetSerializeSize(block);
4423 if (currentBlockSize > nMaxBlockSize) {
4425 "bad-blk-length", "size limits failed");
4426 }
4427
4428 // And a valid coinbase.
4429 TxValidationState tx_state;
4430 if (!CheckCoinbase(*block.vtx[0], tx_state)) {
4432 tx_state.GetRejectReason(),
4433 strprintf("Coinbase check failed (txid %s) %s",
4434 block.vtx[0]->GetId().ToString(),
4435 tx_state.GetDebugMessage()));
4436 }
4437
4438 // Check transactions for regularity, skipping the first. Note that this
4439 // is the first time we check that all after the first are !IsCoinBase.
4440 for (size_t i = 1; i < block.vtx.size(); i++) {
4441 auto *tx = block.vtx[i].get();
4442 if (!CheckRegularTransaction(*tx, tx_state)) {
4443 return state.Invalid(
4445 tx_state.GetRejectReason(),
4446 strprintf("Transaction check failed (txid %s) %s",
4447 tx->GetId().ToString(), tx_state.GetDebugMessage()));
4448 }
4449 }
4450
4451 if (validationOptions.shouldValidatePoW() &&
4452 validationOptions.shouldValidateMerkleRoot()) {
4453 block.fChecked = true;
4454 }
4455
4456 return true;
4457}
4458
4459bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
4460 const Consensus::Params &consensusParams) {
4461 return std::all_of(headers.cbegin(), headers.cend(),
4462 [&](const auto &header) {
4463 return CheckProofOfWork(
4464 header.GetHash(), header.nBits, consensusParams);
4465 });
4466}
4467
4468bool IsBlockMutated(const CBlock &block) {
4470 if (!CheckMerkleRoot(block, state)) {
4472 "Block mutated: %s\n", state.ToString());
4473 return true;
4474 }
4475
4476 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
4477 // Consider the block mutated if any transaction is 64 bytes in size
4478 // (see 3.1 in "Weaknesses in Bitcoin’s Merkle Root Construction":
4479 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20190225/a27d8837/attachment-0001.pdf).
4480 //
4481 // Note: This is not a consensus change as this only applies to blocks
4482 // that don't have a coinbase transaction and would therefore already be
4483 // invalid.
4484 return std::any_of(block.vtx.begin(), block.vtx.end(),
4485 [](auto &tx) { return GetSerializeSize(tx) == 64; });
4486 } else {
4487 // Theoretically it is still possible for a block with a 64 byte
4488 // coinbase transaction to be mutated but we neglect that possibility
4489 // here as it requires at least 224 bits of work.
4490 }
4491
4492 return false;
4493}
4494
4495arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader> &headers) {
4496 arith_uint256 total_work{0};
4497 for (const CBlockHeader &header : headers) {
4498 CBlockIndex dummy(header);
4499 total_work += GetBlockProof(dummy);
4500 }
4501 return total_work;
4502}
4503
4515 const CBlockHeader &block, BlockValidationState &state,
4516 BlockManager &blockman, ChainstateManager &chainman,
4517 const CBlockIndex *pindexPrev, NodeClock::time_point now,
4518 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
4521 assert(pindexPrev != nullptr);
4522 const int nHeight = pindexPrev->nHeight + 1;
4523
4524 const CChainParams &params = chainman.GetParams();
4525
4526 // Check proof of work
4527 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, params)) {
4528 LogPrintf("bad bits after height: %d\n", pindexPrev->nHeight);
4530 "bad-diffbits", "incorrect proof of work");
4531 }
4532
4533 // Check against checkpoints
4534 if (chainman.m_options.checkpoints_enabled) {
4535 const CCheckpointData &checkpoints =
4536 test_checkpoints ? test_checkpoints.value() : params.Checkpoints();
4537
4538 // Check that the block chain matches the known block chain up to a
4539 // checkpoint.
4540 if (!Checkpoints::CheckBlock(checkpoints, nHeight, block.GetHash())) {
4542 "ERROR: %s: rejected by checkpoint lock-in at %d\n",
4543 __func__, nHeight);
4545 "checkpoint mismatch");
4546 }
4547
4548 // Don't accept any forks from the main chain prior to last checkpoint.
4549 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's
4550 // in our BlockIndex().
4551
4552 const CBlockIndex *pcheckpoint =
4553 blockman.GetLastCheckpoint(checkpoints);
4554 if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
4556 "ERROR: %s: forked chain older than last checkpoint "
4557 "(height %d)\n",
4558 __func__, nHeight);
4560 "bad-fork-prior-to-checkpoint");
4561 }
4562 }
4563
4564 // Check timestamp against prev
4565 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) {
4567 "time-too-old", "block's timestamp is too early");
4568 }
4569
4570 // Check timestamp
4571 if (block.Time() > now + std::chrono::seconds{MAX_FUTURE_BLOCK_TIME}) {
4573 "time-too-new",
4574 "block timestamp too far in the future");
4575 }
4576
4577 // Reject blocks with outdated version
4578 if ((block.nVersion < 2 &&
4579 DeploymentActiveAfter(pindexPrev, chainman,
4581 (block.nVersion < 3 &&
4582 DeploymentActiveAfter(pindexPrev, chainman,
4584 (block.nVersion < 4 &&
4585 DeploymentActiveAfter(pindexPrev, chainman,
4587 return state.Invalid(
4589 strprintf("bad-version(0x%08x)", block.nVersion),
4590 strprintf("rejected nVersion=0x%08x block", block.nVersion));
4591 }
4592
4593 return true;
4594}
4595
4603static bool ContextualCheckBlock(const CBlock &block,
4604 BlockValidationState &state,
4605 const ChainstateManager &chainman,
4606 const CBlockIndex *pindexPrev) {
4607 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
4608
4609 // Enforce BIP113 (Median Time Past).
4610 bool enforce_locktime_median_time_past{false};
4611 if (DeploymentActiveAfter(pindexPrev, chainman,
4613 assert(pindexPrev != nullptr);
4614 enforce_locktime_median_time_past = true;
4615 }
4616
4617 const int64_t nMedianTimePast =
4618 pindexPrev == nullptr ? 0 : pindexPrev->GetMedianTimePast();
4619
4620 const int64_t nLockTimeCutoff{enforce_locktime_median_time_past
4621 ? nMedianTimePast
4622 : block.GetBlockTime()};
4623
4624 const Consensus::Params params = chainman.GetConsensus();
4625 const bool fIsMagneticAnomalyEnabled =
4626 IsMagneticAnomalyEnabled(params, pindexPrev);
4627
4628 // Check transactions:
4629 // - canonical ordering
4630 // - ensure they are finalized
4631 // - check they have the minimum size
4632 const CTransaction *prevTx = nullptr;
4633 for (const auto &ptx : block.vtx) {
4634 const CTransaction &tx = *ptx;
4635 if (fIsMagneticAnomalyEnabled) {
4636 if (prevTx && (tx.GetId() <= prevTx->GetId())) {
4637 if (tx.GetId() == prevTx->GetId()) {
4639 "tx-duplicate",
4640 strprintf("Duplicated transaction %s",
4641 tx.GetId().ToString()));
4642 }
4643
4644 return state.Invalid(
4646 strprintf("Transaction order is invalid (%s < %s)",
4647 tx.GetId().ToString(),
4648 prevTx->GetId().ToString()));
4649 }
4650
4651 if (prevTx || !tx.IsCoinBase()) {
4652 prevTx = &tx;
4653 }
4654 }
4655
4656 TxValidationState tx_state;
4657 if (!ContextualCheckTransaction(params, tx, tx_state, nHeight,
4658 nLockTimeCutoff)) {
4660 tx_state.GetRejectReason(),
4661 tx_state.GetDebugMessage());
4662 }
4663 }
4664
4665 // Enforce rule that the coinbase starts with serialized block height
4666 if (DeploymentActiveAfter(pindexPrev, chainman,
4668 CScript expect = CScript() << nHeight;
4669 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
4670 !std::equal(expect.begin(), expect.end(),
4671 block.vtx[0]->vin[0].scriptSig.begin())) {
4673 "bad-cb-height",
4674 "block height mismatch in coinbase");
4675 }
4676 }
4677
4678 return true;
4679}
4680
4687 const CBlockHeader &block, BlockValidationState &state,
4688 CBlockIndex **ppindex, bool min_pow_checked,
4689 const std::optional<CCheckpointData> &test_checkpoints) {
4691 const Config &config = this->GetConfig();
4692 const CChainParams &chainparams = config.GetChainParams();
4693
4694 // Check for duplicate
4695 BlockHash hash = block.GetHash();
4696 BlockMap::iterator miSelf{m_blockman.m_block_index.find(hash)};
4697 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
4698 if (miSelf != m_blockman.m_block_index.end()) {
4699 // Block header is already known.
4700 CBlockIndex *pindex = &(miSelf->second);
4701 if (ppindex) {
4702 *ppindex = pindex;
4703 }
4704
4705 if (pindex->nStatus.isInvalid()) {
4706 LogPrint(BCLog::VALIDATION, "%s: block %s is marked invalid\n",
4707 __func__, hash.ToString());
4708 return state.Invalid(
4710 }
4711
4712 return true;
4713 }
4714
4715 if (!CheckBlockHeader(block, state, chainparams.GetConsensus(),
4716 BlockValidationOptions(config))) {
4718 "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__,
4719 hash.ToString(), state.ToString());
4720 return false;
4721 }
4722
4723 // Get prev block index
4724 BlockMap::iterator mi{
4725 m_blockman.m_block_index.find(block.hashPrevBlock)};
4726 if (mi == m_blockman.m_block_index.end()) {
4728 "header %s has prev block not found: %s\n",
4729 hash.ToString(), block.hashPrevBlock.ToString());
4731 "prev-blk-not-found");
4732 }
4733
4734 CBlockIndex *pindexPrev = &((*mi).second);
4735 assert(pindexPrev);
4736 if (pindexPrev->nStatus.isInvalid()) {
4738 "header %s has prev block invalid: %s\n", hash.ToString(),
4739 block.hashPrevBlock.ToString());
4741 "bad-prevblk");
4742 }
4743
4745 block, state, m_blockman, *this, pindexPrev,
4746 m_options.adjusted_time_callback(), test_checkpoints)) {
4748 "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n",
4749 __func__, hash.ToString(), state.ToString());
4750 return false;
4751 }
4752
4753 /* Determine if this block descends from any block which has been found
4754 * invalid (m_failed_blocks), then mark pindexPrev and any blocks
4755 * between them as failed. For example:
4756 *
4757 * D3
4758 * /
4759 * B2 - C2
4760 * / \
4761 * A D2 - E2 - F2
4762 * \
4763 * B1 - C1 - D1 - E1
4764 *
4765 * In the case that we attempted to reorg from E1 to F2, only to find
4766 * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
4767 * but NOT D3 (it was not in any of our candidate sets at the time).
4768 *
4769 * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
4770 * in LoadBlockIndex.
4771 */
4772 if (!pindexPrev->IsValid(BlockValidity::SCRIPTS)) {
4773 // The above does not mean "invalid": it checks if the previous
4774 // block hasn't been validated up to BlockValidity::SCRIPTS. This is
4775 // a performance optimization, in the common case of adding a new
4776 // block to the tip, we don't need to iterate over the failed blocks
4777 // list.
4778 for (const CBlockIndex *failedit : m_failed_blocks) {
4779 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
4780 assert(failedit->nStatus.hasFailed());
4781 CBlockIndex *invalid_walk = pindexPrev;
4782 while (invalid_walk != failedit) {
4783 invalid_walk->nStatus =
4784 invalid_walk->nStatus.withFailedParent();
4785 m_blockman.m_dirty_blockindex.insert(invalid_walk);
4786 invalid_walk = invalid_walk->pprev;
4787 }
4789 "header %s has prev block invalid: %s\n",
4790 hash.ToString(), block.hashPrevBlock.ToString());
4791 return state.Invalid(
4793 "bad-prevblk");
4794 }
4795 }
4796 }
4797 }
4798 if (!min_pow_checked) {
4800 "%s: not adding new block header %s, missing anti-dos "
4801 "proof-of-work validation\n",
4802 __func__, hash.ToString());
4804 "too-little-chainwork");
4805 }
4806 CBlockIndex *pindex{m_blockman.AddToBlockIndex(block, m_best_header)};
4807
4808 if (ppindex) {
4809 *ppindex = pindex;
4810 }
4811
4812 // Since this is the earliest point at which we have determined that a
4813 // header is both new and valid, log here.
4814 //
4815 // These messages are valuable for detecting potential selfish mining
4816 // behavior; if multiple displacing headers are seen near simultaneously
4817 // across many nodes in the network, this might be an indication of selfish
4818 // mining. Having this log by default when not in IBD ensures broad
4819 // availability of this data in case investigation is merited.
4820 const auto msg = strprintf("Saw new header hash=%s height=%d",
4821 hash.ToString(), pindex->nHeight);
4822
4823 if (IsInitialBlockDownload()) {
4825 } else {
4826 LogPrintf("%s\n", msg);
4827 }
4828
4829 return true;
4830}
4831
4832// Exposed wrapper for AcceptBlockHeader
4834 const std::vector<CBlockHeader> &headers, bool min_pow_checked,
4835 BlockValidationState &state, const CBlockIndex **ppindex,
4836 const std::optional<CCheckpointData> &test_checkpoints) {
4838 {
4839 LOCK(cs_main);
4840 for (const CBlockHeader &header : headers) {
4841 // Use a temp pindex instead of ppindex to avoid a const_cast
4842 CBlockIndex *pindex = nullptr;
4843 bool accepted = AcceptBlockHeader(
4844 header, state, &pindex, min_pow_checked, test_checkpoints);
4846
4847 if (!accepted) {
4848 return false;
4849 }
4850
4851 if (ppindex) {
4852 *ppindex = pindex;
4853 }
4854 }
4855 }
4856
4857 if (NotifyHeaderTip(*this)) {
4858 if (IsInitialBlockDownload() && ppindex && *ppindex) {
4859 const CBlockIndex &last_accepted{**ppindex};
4860 const int64_t blocks_left{
4861 (GetTime() - last_accepted.GetBlockTime()) /
4863 const double progress{100.0 * last_accepted.nHeight /
4864 (last_accepted.nHeight + blocks_left)};
4865 LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n",
4866 last_accepted.nHeight, progress);
4867 }
4868 }
4869 return true;
4870}
4871
4873 int64_t height,
4874 int64_t timestamp) {
4876 {
4877 LOCK(cs_main);
4878 // Don't report headers presync progress if we already have a
4879 // post-minchainwork header chain.
4880 // This means we lose reporting for potentially legimate, but unlikely,
4881 // deep reorgs, but prevent attackers that spam low-work headers from
4882 // filling our logs.
4883 if (m_best_header->nChainWork >=
4884 UintToArith256(GetConsensus().nMinimumChainWork)) {
4885 return;
4886 }
4887 // Rate limit headers presync updates to 4 per second, as these are not
4888 // subject to DoS protection.
4889 auto now = Now<SteadyMilliseconds>();
4890 if (now < m_last_presync_update + 250ms) {
4891 return;
4892 }
4893 m_last_presync_update = now;
4894 }
4895 bool initial_download = IsInitialBlockDownload();
4897 height, timestamp, /*presync=*/true);
4898 if (initial_download) {
4899 const int64_t blocks_left{(GetTime() - timestamp) /
4901 const double progress{100.0 * height / (height + blocks_left)};
4902 LogPrintf("Pre-synchronizing blockheaders, height: %d (~%.2f%%)\n",
4903 height, progress);
4904 }
4905}
4906
4907bool ChainstateManager::AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
4908 BlockValidationState &state,
4909 bool fRequested, const FlatFilePos *dbp,
4910 bool *fNewBlock, bool min_pow_checked) {
4912
4913 const CBlock &block = *pblock;
4914 if (fNewBlock) {
4915 *fNewBlock = false;
4916 }
4917
4918 CBlockIndex *pindex = nullptr;
4919
4920 bool accepted_header{
4921 AcceptBlockHeader(block, state, &pindex, min_pow_checked)};
4923
4924 if (!accepted_header) {
4925 return false;
4926 }
4927
4928 // Check all requested blocks that we do not already have for validity and
4929 // save them to disk. Skip processing of unrequested blocks as an anti-DoS
4930 // measure, unless the blocks have more work than the active chain tip, and
4931 // aren't too far ahead of it, so are likely to be attached soon.
4932 bool fAlreadyHave = pindex->nStatus.hasData();
4933
4934 // TODO: deal better with return value and error conditions for duplicate
4935 // and unrequested blocks.
4936 if (fAlreadyHave) {
4937 return true;
4938 }
4939
4940 // Compare block header timestamps and received times of the block and the
4941 // chaintip. If they have the same chain height, use these diffs as a
4942 // tie-breaker, attempting to pick the more honestly-mined block.
4943 int64_t newBlockTimeDiff = std::llabs(pindex->GetReceivedTimeDiff());
4944 int64_t chainTipTimeDiff =
4945 ActiveTip() ? std::llabs(ActiveTip()->GetReceivedTimeDiff()) : 0;
4946
4947 bool isSameHeight =
4948 ActiveTip() && (pindex->nChainWork == ActiveTip()->nChainWork);
4949 if (isSameHeight) {
4950 LogPrintf("Chain tip timestamp-to-received-time difference: hash=%s, "
4951 "diff=%d\n",
4952 ActiveTip()->GetBlockHash().ToString(), chainTipTimeDiff);
4953 LogPrintf("New block timestamp-to-received-time difference: hash=%s, "
4954 "diff=%d\n",
4955 pindex->GetBlockHash().ToString(), newBlockTimeDiff);
4956 }
4957
4958 bool fHasMoreOrSameWork =
4959 (ActiveTip() ? pindex->nChainWork >= ActiveTip()->nChainWork : true);
4960
4961 // Blocks that are too out-of-order needlessly limit the effectiveness of
4962 // pruning, because pruning will not delete block files that contain any
4963 // blocks which are too close in height to the tip. Apply this test
4964 // regardless of whether pruning is enabled; it should generally be safe to
4965 // not process unrequested blocks.
4966 bool fTooFarAhead{pindex->nHeight >
4968
4969 // TODO: Decouple this function from the block download logic by removing
4970 // fRequested
4971 // This requires some new chain data structure to efficiently look up if a
4972 // block is in a chain leading to a candidate for best tip, despite not
4973 // being such a candidate itself.
4974 // Note that this would break the getblockfrompeer RPC
4975
4976 // If we didn't ask for it:
4977 if (!fRequested) {
4978 // This is a previously-processed block that was pruned.
4979 if (pindex->nTx != 0) {
4980 return true;
4981 }
4982
4983 // Don't process less-work chains.
4984 if (!fHasMoreOrSameWork) {
4985 return true;
4986 }
4987
4988 // Block height is too high.
4989 if (fTooFarAhead) {
4990 return true;
4991 }
4992
4993 // Protect against DoS attacks from low-work chains.
4994 // If our tip is behind, a peer could try to send us
4995 // low-work blocks on a fake chain that we would never
4996 // request; don't process these.
4997 if (pindex->nChainWork < MinimumChainWork()) {
4998 return true;
4999 }
5000 }
5001
5002 if (!CheckBlock(block, state,
5005 !ContextualCheckBlock(block, state, *this, pindex->pprev)) {
5006 if (state.IsInvalid() &&
5008 pindex->nStatus = pindex->nStatus.withFailed();
5009 m_blockman.m_dirty_blockindex.insert(pindex);
5010 }
5011
5012 LogError("%s: %s (block %s)\n", __func__, state.ToString(),
5013 block.GetHash().ToString());
5014 return false;
5015 }
5016
5017 // If connecting the new block would require rewinding more than one block
5018 // from the active chain (i.e., a "deep reorg"), then mark the new block as
5019 // parked. If it has enough work then it will be automatically unparked
5020 // later, during FindMostWorkChain. We mark the block as parked at the very
5021 // last minute so we can make sure everything is ready to be reorged if
5022 // needed.
5024 // Blocks that are below the snapshot height can't cause reorgs, as the
5025 // active tip is at least thousands of blocks higher. Don't park them,
5026 // they will most likely connect on the tip of the background chain.
5027 std::optional<int> snapshot_base_height = GetSnapshotBaseHeight();
5028 const bool is_background_block =
5029 snapshot_base_height && BackgroundSyncInProgress() &&
5030 pindex->nHeight <= snapshot_base_height;
5031 const CBlockIndex *pindexFork = ActiveChain().FindFork(pindex);
5032 if (!is_background_block && pindexFork &&
5033 pindexFork->nHeight + 1 < ActiveHeight()) {
5034 LogPrintf("Park block %s as it would cause a deep reorg.\n",
5035 pindex->GetBlockHash().ToString());
5036 pindex->nStatus = pindex->nStatus.withParked();
5037 m_blockman.m_dirty_blockindex.insert(pindex);
5038 }
5039 }
5040
5041 // Header is valid/has work and the merkle tree is good.
5042 // Relay now, but if it does not build on our best tip, let the
5043 // SendMessages loop relay it.
5044 if (!IsInitialBlockDownload() && ActiveTip() == pindex->pprev) {
5045 GetMainSignals().NewPoWValidBlock(pindex, pblock);
5046 }
5047
5048 // Write block to history file
5049 if (fNewBlock) {
5050 *fNewBlock = true;
5051 }
5052 try {
5053 FlatFilePos blockPos{};
5054 if (dbp) {
5055 blockPos = *dbp;
5056 m_blockman.UpdateBlockInfo(block, pindex->nHeight, blockPos);
5057 } else {
5058 blockPos = m_blockman.WriteBlock(block, pindex->nHeight);
5059 if (blockPos.IsNull()) {
5060 state.Error(strprintf(
5061 "%s: Failed to find position to write new block to disk",
5062 __func__));
5063 return false;
5064 }
5065 }
5066 ReceivedBlockTransactions(block, pindex, blockPos);
5067 } catch (const std::runtime_error &e) {
5068 return FatalError(GetNotifications(), state,
5069 std::string("System error: ") + e.what());
5070 }
5071
5072 // TODO: FlushStateToDisk() handles flushing of both block and chainstate
5073 // data, so we should move this to ChainstateManager so that we can be more
5074 // intelligent about how we flush.
5075 // For now, since FlushStateMode::NONE is used, all that can happen is that
5076 // the block files may be pruned, so we can just call this on one
5077 // chainstate (particularly if we haven't implemented pruning with
5078 // background validation yet).
5079 ActiveChainstate().FlushStateToDisk(state, FlushStateMode::NONE);
5080
5082
5083 return true;
5084}
5085
5087 const std::shared_ptr<const CBlock> &block, bool force_processing,
5088 bool min_pow_checked, bool *new_block,
5091
5092 {
5093 if (new_block) {
5094 *new_block = false;
5095 }
5096
5098
5099 // CheckBlock() does not support multi-threaded block validation
5100 // because CBlock::fChecked can cause data race.
5101 // Therefore, the following critical section must include the
5102 // CheckBlock() call as well.
5103 LOCK(cs_main);
5104
5105 // Skipping AcceptBlock() for CheckBlock() failures means that we will
5106 // never mark a block as invalid if CheckBlock() fails. This is
5107 // protective against consensus failure if there are any unknown form
5108 // s of block malleability that cause CheckBlock() to fail; see e.g.
5109 // CVE-2012-2459 and
5110 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html.
5111 // Because CheckBlock() is not very expensive, the anti-DoS benefits of
5112 // caching failure (of a definitely-invalid block) are not substantial.
5113 bool ret = CheckBlock(*block, state, this->GetConsensus(),
5115 if (ret) {
5116 // Store to disk
5117 ret = AcceptBlock(block, state, force_processing, nullptr,
5118 new_block, min_pow_checked);
5119 }
5120
5121 if (!ret) {
5122 GetMainSignals().BlockChecked(*block, state);
5123 LogError("%s: AcceptBlock FAILED (%s)\n", __func__,
5124 state.ToString());
5125 return false;
5126 }
5127 }
5128
5129 NotifyHeaderTip(*this);
5130
5131 // Only used to report errors, not invalidity - ignore it
5133 if (!ActiveChainstate().ActivateBestChain(state, block, avalanche)) {
5134 LogError("%s: ActivateBestChain failed (%s)\n", __func__,
5135 state.ToString());
5136 return false;
5137 }
5138
5140 ? m_ibd_chainstate.get()
5141 : nullptr)};
5142 BlockValidationState bg_state;
5143 if (bg_chain && !bg_chain->ActivateBestChain(bg_state, block)) {
5144 LogError("%s: [background] ActivateBestChain failed (%s)\n", __func__,
5145 bg_state.ToString());
5146 return false;
5147 }
5148
5149 return true;
5150}
5151
5154 bool test_accept) {
5156 Chainstate &active_chainstate = ActiveChainstate();
5157 if (!active_chainstate.GetMempool()) {
5158 TxValidationState state;
5159 state.Invalid(TxValidationResult::TX_NO_MEMPOOL, "no-mempool");
5160 return MempoolAcceptResult::Failure(state);
5161 }
5162 auto result = AcceptToMemoryPool(active_chainstate, tx, GetTime(),
5163 /*bypass_limits=*/false, test_accept);
5164 active_chainstate.GetMempool()->check(
5165 active_chainstate.CoinsTip(), active_chainstate.m_chain.Height() + 1);
5166 return result;
5167}
5168
5170 BlockValidationState &state, const CChainParams &params,
5171 Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
5172 const std::function<NodeClock::time_point()> &adjusted_time_callback,
5173 BlockValidationOptions validationOptions) {
5175 assert(pindexPrev && pindexPrev == chainstate.m_chain.Tip());
5176 CCoinsViewCache viewNew(&chainstate.CoinsTip());
5177 BlockHash block_hash(block.GetHash());
5178 CBlockIndex indexDummy(block);
5179 indexDummy.pprev = pindexPrev;
5180 indexDummy.nHeight = pindexPrev->nHeight + 1;
5181 indexDummy.phashBlock = &block_hash;
5182
5183 // NOTE: CheckBlockHeader is called by CheckBlock
5184 if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman,
5185 chainstate.m_chainman, pindexPrev,
5186 adjusted_time_callback())) {
5187 LogError("%s: Consensus::ContextualCheckBlockHeader: %s\n", __func__,
5188 state.ToString());
5189 return false;
5190 }
5191
5192 if (!CheckBlock(block, state, params.GetConsensus(), validationOptions)) {
5193 LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());
5194 return false;
5195 }
5196
5197 if (!ContextualCheckBlock(block, state, chainstate.m_chainman,
5198 pindexPrev)) {
5199 LogError("%s: Consensus::ContextualCheckBlock: %s\n", __func__,
5200 state.ToString());
5201 return false;
5202 }
5203
5204 if (!chainstate.ConnectBlock(block, state, &indexDummy, viewNew,
5205 validationOptions, nullptr, true)) {
5206 return false;
5207 }
5208
5209 assert(state.IsValid());
5210 return true;
5211}
5212
5213/* This function is called from the RPC code for pruneblockchain */
5214void PruneBlockFilesManual(Chainstate &active_chainstate,
5215 int nManualPruneHeight) {
5217 if (active_chainstate.FlushStateToDisk(state, FlushStateMode::NONE,
5218 nManualPruneHeight)) {
5219 LogPrintf("%s: failed to flush state (%s)\n", __func__,
5220 state.ToString());
5221 }
5222}
5223
5224void Chainstate::LoadMempool(const fs::path &load_path,
5225 FopenFn mockable_fopen_function) {
5226 if (!m_mempool) {
5227 return;
5228 }
5229 ::LoadMempool(*m_mempool, load_path, *this, mockable_fopen_function);
5231}
5232
5235 const CCoinsViewCache &coins_cache = CoinsTip();
5236 // Never called when the coins view is empty
5237 assert(!coins_cache.GetBestBlock().IsNull());
5238 const CBlockIndex *tip = m_chain.Tip();
5239
5240 if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
5241 return true;
5242 }
5243
5244 // Load pointer to end of best chain
5245 CBlockIndex *pindex =
5247 if (!pindex) {
5248 return false;
5249 }
5250 m_chain.SetTip(*pindex);
5252
5253 tip = m_chain.Tip();
5254 LogPrintf(
5255 "Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
5256 tip->GetBlockHash().ToString(), m_chain.Height(),
5259 return true;
5260}
5261
5263 : m_notifications{notifications} {
5264 m_notifications.progress(_("Verifying blocks…"), 0, false);
5265}
5266
5268 m_notifications.progress(bilingual_str{}, 100, false);
5269}
5270
5272 CCoinsView &coinsview, int nCheckLevel,
5273 int nCheckDepth) {
5275
5276 const Config &config = chainstate.m_chainman.GetConfig();
5277 const CChainParams &params = config.GetChainParams();
5278 const Consensus::Params &consensusParams = params.GetConsensus();
5279
5280 if (chainstate.m_chain.Tip() == nullptr ||
5281 chainstate.m_chain.Tip()->pprev == nullptr) {
5283 }
5284
5285 // Verify blocks in the best chain
5286 if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
5287 nCheckDepth = chainstate.m_chain.Height();
5288 }
5289
5290 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
5291 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth,
5292 nCheckLevel);
5293
5294 CCoinsViewCache coins(&coinsview);
5295 CBlockIndex *pindex;
5296 CBlockIndex *pindexFailure = nullptr;
5297 int nGoodTransactions = 0;
5299 int reportDone = 0;
5300 bool skipped_no_block_data{false};
5301 bool skipped_l3_checks{false};
5302 LogPrintf("Verification progress: 0%%\n");
5303
5304 const bool is_snapshot_cs{chainstate.m_from_snapshot_blockhash};
5305
5306 for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev;
5307 pindex = pindex->pprev) {
5308 const int percentageDone = std::max(
5309 1, std::min(99, (int)(((double)(chainstate.m_chain.Height() -
5310 pindex->nHeight)) /
5311 (double)nCheckDepth *
5312 (nCheckLevel >= 4 ? 50 : 100))));
5313 if (reportDone < percentageDone / 10) {
5314 // report every 10% step
5315 LogPrintf("Verification progress: %d%%\n", percentageDone);
5316 reportDone = percentageDone / 10;
5317 }
5318
5319 m_notifications.progress(_("Verifying blocks…"), percentageDone, false);
5320 if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
5321 break;
5322 }
5323
5324 if ((chainstate.m_blockman.IsPruneMode() || is_snapshot_cs) &&
5325 !pindex->nStatus.hasData()) {
5326 // If pruning or running under an assumeutxo snapshot, only go
5327 // back as far as we have data.
5328 LogPrintf("VerifyDB(): block verification stopping at height %d "
5329 "(no data). This could be due to pruning or use of an "
5330 "assumeutxo snapshot.\n",
5331 pindex->nHeight);
5332 skipped_no_block_data = true;
5333 break;
5334 }
5335
5336 CBlock block;
5337
5338 // check level 0: read from disk
5339 if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
5340 LogPrintf("Verification error: ReadBlock failed at %d, hash=%s\n",
5341 pindex->nHeight, pindex->GetBlockHash().ToString());
5343 }
5344
5345 // check level 1: verify block validity
5346 if (nCheckLevel >= 1 && !CheckBlock(block, state, consensusParams,
5347 BlockValidationOptions(config))) {
5348 LogPrintf(
5349 "Verification error: found bad block at %d, hash=%s (%s)\n",
5350 pindex->nHeight, pindex->GetBlockHash().ToString(),
5351 state.ToString());
5353 }
5354
5355 // check level 2: verify undo validity
5356 if (nCheckLevel >= 2 && pindex) {
5357 CBlockUndo undo;
5358 if (!pindex->GetUndoPos().IsNull()) {
5359 if (!chainstate.m_blockman.ReadBlockUndo(undo, *pindex)) {
5360 LogPrintf("Verification error: found bad undo data at %d, "
5361 "hash=%s\n",
5362 pindex->nHeight,
5363 pindex->GetBlockHash().ToString());
5365 }
5366 }
5367 }
5368 // check level 3: check for inconsistencies during memory-only
5369 // disconnect of tip blocks
5370 size_t curr_coins_usage = coins.DynamicMemoryUsage() +
5371 chainstate.CoinsTip().DynamicMemoryUsage();
5372
5373 if (nCheckLevel >= 3) {
5374 if (curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
5375 assert(coins.GetBestBlock() == pindex->GetBlockHash());
5376 DisconnectResult res =
5377 chainstate.DisconnectBlock(block, pindex, coins);
5378 if (res == DisconnectResult::FAILED) {
5379 LogPrintf("Verification error: irrecoverable inconsistency "
5380 "in block data at %d, hash=%s\n",
5381 pindex->nHeight,
5382 pindex->GetBlockHash().ToString());
5384 }
5385 if (res == DisconnectResult::UNCLEAN) {
5386 nGoodTransactions = 0;
5387 pindexFailure = pindex;
5388 } else {
5389 nGoodTransactions += block.vtx.size();
5390 }
5391 } else {
5392 skipped_l3_checks = true;
5393 }
5394 }
5395
5396 if (chainstate.m_chainman.m_interrupt) {
5398 }
5399 }
5400
5401 if (pindexFailure) {
5402 LogPrintf("Verification error: coin database inconsistencies found "
5403 "(last %i blocks, %i good transactions before that)\n",
5404 chainstate.m_chain.Height() - pindexFailure->nHeight + 1,
5405 nGoodTransactions);
5407 }
5408 if (skipped_l3_checks) {
5409 LogPrintf("Skipped verification of level >=3 (insufficient database "
5410 "cache size). Consider increasing -dbcache.\n");
5411 }
5412
5413 // store block count as we move pindex at check level >= 4
5414 int block_count = chainstate.m_chain.Height() - pindex->nHeight;
5415
5416 // check level 4: try reconnecting blocks
5417 if (nCheckLevel >= 4 && !skipped_l3_checks) {
5418 while (pindex != chainstate.m_chain.Tip()) {
5419 const int percentageDone = std::max(
5420 1, std::min(99, 100 - int(double(chainstate.m_chain.Height() -
5421 pindex->nHeight) /
5422 double(nCheckDepth) * 50)));
5423 if (reportDone < percentageDone / 10) {
5424 // report every 10% step
5425 LogPrintf("Verification progress: %d%%\n", percentageDone);
5426 reportDone = percentageDone / 10;
5427 }
5428 m_notifications.progress(_("Verifying blocks…"), percentageDone,
5429 false);
5430 pindex = chainstate.m_chain.Next(pindex);
5431 CBlock block;
5432 if (!chainstate.m_blockman.ReadBlock(block, *pindex)) {
5433 LogPrintf("Verification error: ReadBlock failed at %d, "
5434 "hash=%s\n",
5435 pindex->nHeight, pindex->GetBlockHash().ToString());
5437 }
5438 if (!chainstate.ConnectBlock(block, state, pindex, coins,
5439 BlockValidationOptions(config))) {
5440 LogPrintf("Verification error: found unconnectable block at "
5441 "%d, hash=%s (%s)\n",
5442 pindex->nHeight, pindex->GetBlockHash().ToString(),
5443 state.ToString());
5445 }
5446 if (chainstate.m_chainman.m_interrupt) {
5448 }
5449 }
5450 }
5451
5452 LogPrintf("Verification: No coin database inconsistencies in last %i "
5453 "blocks (%i transactions)\n",
5454 block_count, nGoodTransactions);
5455
5456 if (skipped_l3_checks) {
5458 }
5459 if (skipped_no_block_data) {
5461 }
5463}
5464
5470 CCoinsViewCache &view) {
5472 // TODO: merge with ConnectBlock
5473 CBlock block;
5474 if (!m_blockman.ReadBlock(block, *pindex)) {
5475 LogError("ReplayBlock(): ReadBlock failed at %d, hash=%s\n",
5476 pindex->nHeight, pindex->GetBlockHash().ToString());
5477 return false;
5478 }
5479
5480 for (const CTransactionRef &tx : block.vtx) {
5481 // Pass check = true as every addition may be an overwrite.
5482 AddCoins(view, *tx, pindex->nHeight, true);
5483 }
5484
5485 for (const CTransactionRef &tx : block.vtx) {
5486 if (tx->IsCoinBase()) {
5487 continue;
5488 }
5489
5490 for (const CTxIn &txin : tx->vin) {
5491 view.SpendCoin(txin.prevout);
5492 }
5493 }
5494
5495 return true;
5496}
5497
5499 LOCK(cs_main);
5500
5501 CCoinsView &db = this->CoinsDB();
5502 CCoinsViewCache cache(&db);
5503
5504 std::vector<BlockHash> hashHeads = db.GetHeadBlocks();
5505 if (hashHeads.empty()) {
5506 // We're already in a consistent state.
5507 return true;
5508 }
5509 if (hashHeads.size() != 2) {
5510 LogError("ReplayBlocks(): unknown inconsistent state\n");
5511 return false;
5512 }
5513
5514 m_chainman.GetNotifications().progress(_("Replaying blocks…"), 0, false);
5515 LogPrintf("Replaying blocks\n");
5516
5517 // Old tip during the interrupted flush.
5518 const CBlockIndex *pindexOld = nullptr;
5519 // New tip during the interrupted flush.
5520 const CBlockIndex *pindexNew;
5521 // Latest block common to both the old and the new tip.
5522 const CBlockIndex *pindexFork = nullptr;
5523
5524 if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
5525 LogError("ReplayBlocks(): reorganization to unknown block requested\n");
5526 return false;
5527 }
5528
5529 pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
5530
5531 if (!hashHeads[1].IsNull()) {
5532 // The old tip is allowed to be 0, indicating it's the first flush.
5533 if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
5534 LogError("ReplayBlocks(): reorganization from unknown block "
5535 "requested\n");
5536 return false;
5537 }
5538
5539 pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
5540 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
5541 assert(pindexFork != nullptr);
5542 }
5543
5544 // Rollback along the old branch.
5545 while (pindexOld != pindexFork) {
5546 if (pindexOld->nHeight > 0) {
5547 // Never disconnect the genesis block.
5548 CBlock block;
5549 if (!m_blockman.ReadBlock(block, *pindexOld)) {
5550 LogError("RollbackBlock(): ReadBlock() failed at "
5551 "%d, hash=%s\n",
5552 pindexOld->nHeight,
5553 pindexOld->GetBlockHash().ToString());
5554 return false;
5555 }
5556
5557 LogPrintf("Rolling back %s (%i)\n",
5558 pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
5559 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
5560 if (res == DisconnectResult::FAILED) {
5561 LogError(
5562 "RollbackBlock(): DisconnectBlock failed at %d, hash=%s\n",
5563 pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
5564 return false;
5565 }
5566
5567 // If DisconnectResult::UNCLEAN is returned, it means a non-existing
5568 // UTXO was deleted, or an existing UTXO was overwritten. It
5569 // corresponds to cases where the block-to-be-disconnect never had
5570 // all its operations applied to the UTXO set. However, as both
5571 // writing a UTXO and deleting a UTXO are idempotent operations, the
5572 // result is still a version of the UTXO set with the effects of
5573 // that block undone.
5574 }
5575 pindexOld = pindexOld->pprev;
5576 }
5577
5578 // Roll forward from the forking point to the new tip.
5579 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
5580 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight;
5581 ++nHeight) {
5582 const CBlockIndex &pindex{*Assert(pindexNew->GetAncestor(nHeight))};
5583 LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(),
5584 nHeight);
5586 _("Replaying blocks…"),
5587 (int)((nHeight - nForkHeight) * 100.0 /
5588 (pindexNew->nHeight - nForkHeight)),
5589 false);
5590 if (!RollforwardBlock(&pindex, cache)) {
5591 return false;
5592 }
5593 }
5594
5595 cache.SetBestBlock(pindexNew->GetBlockHash());
5596 cache.Flush();
5598 return true;
5599}
5600
5601// May NOT be used after any connections are up as much of the peer-processing
5602// logic assumes a consistent block index state
5603void Chainstate::ClearBlockIndexCandidates() {
5605 m_best_fork_tip = nullptr;
5606 m_best_fork_base = nullptr;
5608}
5609
5610bool ChainstateManager::DumpRecentHeadersTime(const fs::path &filePath) const {
5612
5614 return false;
5615 }
5616
5617 // Dump enough headers for RTT computation, with a few extras in case a
5618 // reorg occurs.
5619 const uint64_t numHeaders{20};
5620
5621 try {
5622 const fs::path filePathTmp = filePath + ".new";
5623 FILE *filestr = fsbridge::fopen(filePathTmp, "wb");
5624 if (!filestr) {
5625 return false;
5626 }
5627
5628 AutoFile file{filestr};
5629 file << HEADERS_TIME_VERSION;
5630 file << numHeaders;
5631
5632 const CBlockIndex *index = ActiveTip();
5633 bool missingIndex{false};
5634 for (uint64_t i = 0; i < numHeaders; i++) {
5635 if (!index) {
5636 LogPrintf("Missing block index, stopping the headers time "
5637 "dumping after %d blocks.\n",
5638 i);
5639 missingIndex = true;
5640 break;
5641 }
5642
5643 file << index->GetBlockHash();
5644 file << index->GetHeaderReceivedTime();
5645
5646 index = index->pprev;
5647 }
5648
5649 if (!FileCommit(file.Get())) {
5650 throw std::runtime_error(strprintf("Failed to commit to file %s",
5651 PathToString(filePathTmp)));
5652 }
5653 file.fclose();
5654
5655 if (missingIndex) {
5656 fs::remove(filePathTmp);
5657 return false;
5658 }
5659
5660 if (!RenameOver(filePathTmp, filePath)) {
5661 throw std::runtime_error(strprintf("Rename failed from %s to %s",
5662 PathToString(filePathTmp),
5663 PathToString(filePath)));
5664 }
5665 } catch (const std::exception &e) {
5666 LogPrintf("Failed to dump the headers time: %s.\n", e.what());
5667 return false;
5668 }
5669
5670 LogPrintf("Successfully dumped the last %d headers time to %s.\n",
5671 numHeaders, PathToString(filePath));
5672
5673 return true;
5674}
5675
5678
5680 return false;
5681 }
5682
5683 FILE *filestr = fsbridge::fopen(filePath, "rb");
5684 AutoFile file{filestr};
5685 if (file.IsNull()) {
5686 LogPrintf("Failed to open header times from disk, skipping.\n");
5687 return false;
5688 }
5689
5690 try {
5691 uint64_t version;
5692 file >> version;
5693
5694 if (version != HEADERS_TIME_VERSION) {
5695 LogPrintf("Unsupported header times file version, skipping.\n");
5696 return false;
5697 }
5698
5699 uint64_t numBlocks;
5700 file >> numBlocks;
5701
5702 for (uint64_t i = 0; i < numBlocks; i++) {
5703 BlockHash blockHash;
5704 int64_t receiveTime;
5705
5706 file >> blockHash;
5707 file >> receiveTime;
5708
5709 CBlockIndex *index = m_blockman.LookupBlockIndex(blockHash);
5710 if (!index) {
5711 LogPrintf("Missing index for block %s, stopping the headers "
5712 "time loading after %d blocks.\n",
5713 blockHash.ToString(), i);
5714 return false;
5715 }
5716
5717 index->nTimeReceived = receiveTime;
5718 }
5719 } catch (const std::exception &e) {
5720 LogPrintf("Failed to read the headers time file data on disk: %s.\n",
5721 e.what());
5722 return false;
5723 }
5724
5725 return true;
5726}
5727
5730 // Load block index from databases
5731 bool needs_init = fReindex;
5732 if (!fReindex) {
5733 bool ret{m_blockman.LoadBlockIndexDB(SnapshotBlockhash())};
5734 if (!ret) {
5735 return false;
5736 }
5737
5738 m_blockman.ScanAndUnlinkAlreadyPrunedFiles();
5739
5740 std::vector<CBlockIndex *> vSortedByHeight{
5741 m_blockman.GetAllBlockIndices()};
5742 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
5744
5745 for (CBlockIndex *pindex : vSortedByHeight) {
5746 if (m_interrupt) {
5747 return false;
5748 }
5749 // If we have an assumeutxo-based chainstate, then the snapshot
5750 // block will be a candidate for the tip, but it may not be
5751 // VALID_TRANSACTIONS (eg if we haven't yet downloaded the block),
5752 // so we special-case the snapshot block as a potential candidate
5753 // here.
5754 if (pindex == GetSnapshotBaseBlock() ||
5756 (pindex->HaveNumChainTxs() || pindex->pprev == nullptr))) {
5757 for (Chainstate *chainstate : GetAll()) {
5758 chainstate->TryAddBlockIndexCandidate(pindex);
5759 }
5760 }
5761
5762 if (pindex->nStatus.isInvalid() &&
5763 (!m_best_invalid ||
5764 pindex->nChainWork > m_best_invalid->nChainWork)) {
5765 m_best_invalid = pindex;
5766 }
5767
5768 if (pindex->nStatus.isOnParkedChain() &&
5769 (!m_best_parked ||
5770 pindex->nChainWork > m_best_parked->nChainWork)) {
5771 m_best_parked = pindex;
5772 }
5773
5774 if (pindex->IsValid(BlockValidity::TREE) &&
5775 (m_best_header == nullptr ||
5776 CBlockIndexWorkComparator()(m_best_header, pindex))) {
5777 m_best_header = pindex;
5778 }
5779 }
5780
5781 needs_init = m_blockman.m_block_index.empty();
5782 }
5783
5784 if (needs_init) {
5785 // Everything here is for *new* reindex/DBs. Thus, though
5786 // LoadBlockIndexDB may have set fReindex if we shut down
5787 // mid-reindex previously, we don't check fReindex and
5788 // instead only check it prior to LoadBlockIndexDB to set
5789 // needs_init.
5790
5791 LogPrintf("Initializing databases...\n");
5792 }
5793 return true;
5794}
5795
5797 LOCK(cs_main);
5798
5799 const CChainParams &params{m_chainman.GetParams()};
5800
5801 // Check whether we're already initialized by checking for genesis in
5802 // m_blockman.m_block_index. Note that we can't use m_chain here, since it
5803 // is set based on the coins db, not the block index db, which is the only
5804 // thing loaded at this point.
5805 if (m_blockman.m_block_index.count(params.GenesisBlock().GetHash())) {
5806 return true;
5807 }
5808
5809 try {
5810 const CBlock &block = params.GenesisBlock();
5811 FlatFilePos blockPos{m_blockman.WriteBlock(block, 0)};
5812 if (blockPos.IsNull()) {
5813 LogError("%s: writing genesis block to disk failed\n", __func__);
5814 return false;
5815 }
5816 CBlockIndex *pindex =
5817 m_blockman.AddToBlockIndex(block, m_chainman.m_best_header);
5818 m_chainman.ReceivedBlockTransactions(block, pindex, blockPos);
5819 } catch (const std::runtime_error &e) {
5820 LogError("%s: failed to write genesis block: %s\n", __func__, e.what());
5821 return false;
5822 }
5823
5824 return true;
5825}
5826
5828 AutoFile &file_in, FlatFilePos *dbp,
5829 std::multimap<BlockHash, FlatFilePos> *blocks_with_unknown_parent,
5831 // Either both should be specified (-reindex), or neither (-loadblock).
5832 assert(!dbp == !blocks_with_unknown_parent);
5833
5834 int64_t nStart = GetTimeMillis();
5835 const CChainParams &params{GetParams()};
5836
5837 int nLoaded = 0;
5838 try {
5839 // Make sure we have at least 2*MAX_TX_SIZE space in the buffer
5840 // so any transaction can fit in there.
5841 BufferedFile blkdat{file_in, 2 * MAX_TX_SIZE, MAX_TX_SIZE + 8};
5842 // nRewind indicates where to resume scanning in case something goes
5843 // wrong, such as a block fails to deserialize.
5844 uint64_t nRewind = blkdat.GetPos();
5845 while (!blkdat.eof()) {
5846 if (m_interrupt) {
5847 return;
5848 }
5849
5850 blkdat.SetPos(nRewind);
5851 // Start one byte further next time, in case of failure.
5852 nRewind++;
5853 // Remove former limit.
5854 blkdat.SetLimit();
5855 unsigned int nSize = 0;
5856 try {
5857 // Locate a header.
5859 blkdat.FindByte(std::byte(params.DiskMagic()[0]));
5860 nRewind = blkdat.GetPos() + 1;
5861 blkdat >> buf;
5862 if (memcmp(buf, params.DiskMagic().data(),
5864 continue;
5865 }
5866
5867 // Read size.
5868 blkdat >> nSize;
5869 if (nSize < 80) {
5870 continue;
5871 }
5872 } catch (const std::exception &) {
5873 // No valid block header found; don't complain.
5874 // (this happens at the end of every blk.dat file)
5875 break;
5876 }
5877
5878 try {
5879 // read block header
5880 const uint64_t nBlockPos{blkdat.GetPos()};
5881 if (dbp) {
5882 dbp->nPos = nBlockPos;
5883 }
5884 blkdat.SetLimit(nBlockPos + nSize);
5885 CBlockHeader header;
5886 blkdat >> header;
5887 const BlockHash hash{header.GetHash()};
5888 // Skip the rest of this block (this may read from disk
5889 // into memory); position to the marker before the next block,
5890 // but it's still possible to rewind to the start of the
5891 // current block (without a disk read).
5892 nRewind = nBlockPos + nSize;
5893 blkdat.SkipTo(nRewind);
5894
5895 // needs to remain available after the cs_main lock is released
5896 // to avoid duplicate reads from disk
5897 std::shared_ptr<CBlock> pblock{};
5898
5899 {
5900 LOCK(cs_main);
5901 // detect out of order blocks, and store them for later
5902 if (hash != params.GetConsensus().hashGenesisBlock &&
5904 LogPrint(
5906 "%s: Out of order block %s, parent %s not known\n",
5907 __func__, hash.ToString(),
5908 header.hashPrevBlock.ToString());
5909 if (dbp && blocks_with_unknown_parent) {
5910 blocks_with_unknown_parent->emplace(
5911 header.hashPrevBlock, *dbp);
5912 }
5913 continue;
5914 }
5915
5916 // process in case the block isn't known yet
5917 const CBlockIndex *pindex =
5919 if (!pindex || !pindex->nStatus.hasData()) {
5920 // This block can be processed immediately; rewind to
5921 // its start, read and deserialize it.
5922 blkdat.SetPos(nBlockPos);
5923 pblock = std::make_shared<CBlock>();
5924 blkdat >> *pblock;
5925 nRewind = blkdat.GetPos();
5926
5928 if (AcceptBlock(pblock, state, true, dbp, nullptr,
5929 true)) {
5930 nLoaded++;
5931 }
5932 if (state.IsError()) {
5933 break;
5934 }
5935 } else if (hash != params.GetConsensus().hashGenesisBlock &&
5936 pindex->nHeight % 1000 == 0) {
5937 LogPrint(
5939 "Block Import: already had block %s at height %d\n",
5940 hash.ToString(), pindex->nHeight);
5941 }
5942 }
5943
5944 // Activate the genesis block so normal node progress can
5945 // continue
5946 if (hash == params.GetConsensus().hashGenesisBlock) {
5947 bool genesis_activation_failure = false;
5948 for (auto c : GetAll()) {
5950 if (!c->ActivateBestChain(state, nullptr, avalanche)) {
5951 genesis_activation_failure = true;
5952 break;
5953 }
5954 }
5955 if (genesis_activation_failure) {
5956 break;
5957 }
5958 }
5959
5960 if (m_blockman.IsPruneMode() && !fReindex && pblock) {
5961 // Must update the tip for pruning to work while importing
5962 // with -loadblock. This is a tradeoff to conserve disk
5963 // space at the expense of time spent updating the tip to be
5964 // able to prune. Otherwise, ActivateBestChain won't be
5965 // called by the import process until after all of the block
5966 // files are loaded. ActivateBestChain can be called by
5967 // concurrent network message processing, but that is not
5968 // reliable for the purpose of pruning while importing.
5969 bool activation_failure = false;
5970 for (auto c : GetAll()) {
5972 if (!c->ActivateBestChain(state, pblock, avalanche)) {
5974 "failed to activate chain (%s)\n",
5975 state.ToString());
5976 activation_failure = true;
5977 break;
5978 }
5979 }
5980 if (activation_failure) {
5981 break;
5982 }
5983 }
5984
5985 NotifyHeaderTip(*this);
5986
5987 if (!blocks_with_unknown_parent) {
5988 continue;
5989 }
5990
5991 // Recursively process earlier encountered successors of this
5992 // block
5993 std::deque<BlockHash> queue;
5994 queue.push_back(hash);
5995 while (!queue.empty()) {
5996 BlockHash head = queue.front();
5997 queue.pop_front();
5998 auto range = blocks_with_unknown_parent->equal_range(head);
5999 while (range.first != range.second) {
6000 std::multimap<BlockHash, FlatFilePos>::iterator it =
6001 range.first;
6002 std::shared_ptr<CBlock> pblockrecursive =
6003 std::make_shared<CBlock>();
6004 if (m_blockman.ReadBlock(*pblockrecursive,
6005 it->second)) {
6006 LogPrint(
6008 "%s: Processing out of order child %s of %s\n",
6009 __func__, pblockrecursive->GetHash().ToString(),
6010 head.ToString());
6011 LOCK(cs_main);
6013 if (AcceptBlock(pblockrecursive, dummy, true,
6014 &it->second, nullptr, true)) {
6015 nLoaded++;
6016 queue.push_back(pblockrecursive->GetHash());
6017 }
6018 }
6019 range.first++;
6020 blocks_with_unknown_parent->erase(it);
6021 NotifyHeaderTip(*this);
6022 }
6023 }
6024 } catch (const std::exception &e) {
6025 // Historical bugs added extra data to the block files that does
6026 // not deserialize cleanly. Commonly this data is between
6027 // readable blocks, but it does not really matter. Such data is
6028 // not fatal to the import process. The code that reads the
6029 // block files deals with invalid data by simply ignoring it. It
6030 // continues to search for the next {4 byte magic message start
6031 // bytes + 4 byte length + block} that does deserialize cleanly
6032 // and passes all of the other block validation checks dealing
6033 // with POW and the merkle root, etc... We merely note with this
6034 // informational log message when unexpected data is
6035 // encountered. We could also be experiencing a storage system
6036 // read error, or a read of a previous bad write. These are
6037 // possible, but less likely scenarios. We don't have enough
6038 // information to tell a difference here. The reindex process is
6039 // not the place to attempt to clean and/or compact the block
6040 // files. If so desired, a studious node operator may use
6041 // knowledge of the fact that the block files are not entirely
6042 // pristine in order to prepare a set of pristine, and perhaps
6043 // ordered, block files for later reindexing.
6045 "%s: unexpected data at file offset 0x%x - %s. "
6046 "continuing\n",
6047 __func__, (nRewind - 1), e.what());
6048 }
6049 }
6050 } catch (const std::runtime_error &e) {
6051 GetNotifications().fatalError(std::string("System error: ") + e.what());
6052 }
6053
6054 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded,
6055 GetTimeMillis() - nStart);
6056}
6057
6059 if (!ShouldCheckBlockIndex()) {
6060 return;
6061 }
6062
6063 LOCK(cs_main);
6064
6065 // During a reindex, we read the genesis block and call CheckBlockIndex
6066 // before ActivateBestChain, so we have the genesis block in
6067 // m_blockman.m_block_index but no active chain. (A few of the tests when
6068 // iterating the block tree require that m_chain has been initialized.)
6069 if (ActiveChain().Height() < 0) {
6070 assert(m_blockman.m_block_index.size() <= 1);
6071 return;
6072 }
6073
6074 // Build forward-pointing map of the entire block tree.
6075 std::multimap<CBlockIndex *, CBlockIndex *> forward;
6076 for (auto &[_, block_index] : m_blockman.m_block_index) {
6077 forward.emplace(block_index.pprev, &block_index);
6078 }
6079
6080 assert(forward.size() == m_blockman.m_block_index.size());
6081
6082 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6083 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6084 rangeGenesis = forward.equal_range(nullptr);
6085 CBlockIndex *pindex = rangeGenesis.first->second;
6086 rangeGenesis.first++;
6087 // There is only one index entry with parent nullptr.
6088 assert(rangeGenesis.first == rangeGenesis.second);
6089
6090 // Iterate over the entire block tree, using depth-first search.
6091 // Along the way, remember whether there are blocks on the path from genesis
6092 // block being explored which are the first to have certain properties.
6093 size_t nNodes = 0;
6094 int nHeight = 0;
6095 // Oldest ancestor of pindex which is invalid.
6096 CBlockIndex *pindexFirstInvalid = nullptr;
6097 // Oldest ancestor of pindex which is parked.
6098 CBlockIndex *pindexFirstParked = nullptr;
6099 // Oldest ancestor of pindex which does not have data available, since
6100 // assumeutxo snapshot if used.
6101 CBlockIndex *pindexFirstMissing = nullptr;
6102 // Oldest ancestor of pindex for which nTx == 0, since assumeutxo snapshot
6103 // if used..
6104 CBlockIndex *pindexFirstNeverProcessed = nullptr;
6105 // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE
6106 // (regardless of being valid or not).
6107 CBlockIndex *pindexFirstNotTreeValid = nullptr;
6108 // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS
6109 // (regardless of being valid or not), since assumeutxo snapshot if used.
6110 CBlockIndex *pindexFirstNotTransactionsValid = nullptr;
6111 // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN
6112 // (regardless of being valid or not), since assumeutxo snapshot if used.
6113 CBlockIndex *pindexFirstNotChainValid = nullptr;
6114 // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS
6115 // (regardless of being valid or not), since assumeutxo snapshot if used.
6116 CBlockIndex *pindexFirstNotScriptsValid = nullptr;
6117
6118 // After checking an assumeutxo snapshot block, reset pindexFirst pointers
6119 // to earlier blocks that have not been downloaded or validated yet, so
6120 // checks for later blocks can assume the earlier blocks were validated and
6121 // be stricter, testing for more requirements.
6122 const CBlockIndex *snap_base{GetSnapshotBaseBlock()};
6123 CBlockIndex *snap_first_missing{}, *snap_first_notx{}, *snap_first_notv{},
6124 *snap_first_nocv{}, *snap_first_nosv{};
6125 auto snap_update_firsts = [&] {
6126 if (pindex == snap_base) {
6127 std::swap(snap_first_missing, pindexFirstMissing);
6128 std::swap(snap_first_notx, pindexFirstNeverProcessed);
6129 std::swap(snap_first_notv, pindexFirstNotTransactionsValid);
6130 std::swap(snap_first_nocv, pindexFirstNotChainValid);
6131 std::swap(snap_first_nosv, pindexFirstNotScriptsValid);
6132 }
6133 };
6134
6135 while (pindex != nullptr) {
6136 nNodes++;
6137 if (pindexFirstInvalid == nullptr && pindex->nStatus.hasFailed()) {
6138 pindexFirstInvalid = pindex;
6139 }
6140 if (pindexFirstParked == nullptr && pindex->nStatus.isParked()) {
6141 pindexFirstParked = pindex;
6142 }
6143 if (pindexFirstMissing == nullptr && !pindex->nStatus.hasData()) {
6144 pindexFirstMissing = pindex;
6145 }
6146 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) {
6147 pindexFirstNeverProcessed = pindex;
6148 }
6149 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr &&
6150 pindex->nStatus.getValidity() < BlockValidity::TREE) {
6151 pindexFirstNotTreeValid = pindex;
6152 }
6153 if (pindex->pprev != nullptr) {
6154 if (pindexFirstNotTransactionsValid == nullptr &&
6155 pindex->nStatus.getValidity() < BlockValidity::TRANSACTIONS) {
6156 pindexFirstNotTransactionsValid = pindex;
6157 }
6158 if (pindexFirstNotChainValid == nullptr &&
6159 pindex->nStatus.getValidity() < BlockValidity::CHAIN) {
6160 pindexFirstNotChainValid = pindex;
6161 }
6162 if (pindexFirstNotScriptsValid == nullptr &&
6163 pindex->nStatus.getValidity() < BlockValidity::SCRIPTS) {
6164 pindexFirstNotScriptsValid = pindex;
6165 }
6166 }
6167
6168 // Begin: actual consistency checks.
6169 if (pindex->pprev == nullptr) {
6170 // Genesis block checks.
6171 // Genesis block's hash must match.
6172 assert(pindex->GetBlockHash() == GetConsensus().hashGenesisBlock);
6173 for (auto c : GetAll()) {
6174 if (c->m_chain.Genesis() != nullptr) {
6175 // The chain's genesis block must be this block.
6176 assert(pindex == c->m_chain.Genesis());
6177 }
6178 }
6179 }
6180 if (!pindex->HaveNumChainTxs()) {
6181 // nSequenceId can't be set positive for blocks that aren't linked
6182 // (negative is used for preciousblock)
6183 assert(pindex->nSequenceId <= 0);
6184 }
6185 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or
6186 // not pruning has occurred). HAVE_DATA is only equivalent to nTx > 0
6187 // (or VALID_TRANSACTIONS) if no pruning has occurred.
6189 // If we've never pruned, then HAVE_DATA should be equivalent to nTx
6190 // > 0
6191 assert(pindex->nStatus.hasData() == (pindex->nTx > 0));
6192 assert(pindexFirstMissing == pindexFirstNeverProcessed);
6193 } else if (pindex->nStatus.hasData()) {
6194 // If we have pruned, then we can only say that HAVE_DATA implies
6195 // nTx > 0
6196 assert(pindex->nTx > 0);
6197 }
6198 if (pindex->nStatus.hasUndo()) {
6199 assert(pindex->nStatus.hasData());
6200 }
6201 if (snap_base && snap_base->GetAncestor(pindex->nHeight) == pindex) {
6202 // Assumed-valid blocks should connect to the main chain.
6203 assert(pindex->nStatus.getValidity() >= BlockValidity::TREE);
6204 }
6205 // There should only be an nTx value if we have
6206 // actually seen a block's transactions.
6207 // This is pruning-independent.
6208 assert((pindex->nStatus.getValidity() >= BlockValidity::TRANSACTIONS) ==
6209 (pindex->nTx > 0));
6210 // All parents having had data (at some point) is equivalent to all
6211 // parents being VALID_TRANSACTIONS, which is equivalent to
6212 // HaveNumChainTxs().
6213 assert((pindexFirstNeverProcessed == nullptr || pindex == snap_base) ==
6214 (pindex->HaveNumChainTxs()));
6215 assert((pindexFirstNotTransactionsValid == nullptr ||
6216 pindex == snap_base) == (pindex->HaveNumChainTxs()));
6217 // nHeight must be consistent.
6218 assert(pindex->nHeight == nHeight);
6219 // For every block except the genesis block, the chainwork must be
6220 // larger than the parent's.
6221 assert(pindex->pprev == nullptr ||
6222 pindex->nChainWork >= pindex->pprev->nChainWork);
6223 // The pskip pointer must point back for all but the first 2 blocks.
6224 assert(nHeight < 2 ||
6225 (pindex->pskip && (pindex->pskip->nHeight < nHeight)));
6226 // All m_blockman.m_block_index entries must at least be TREE valid
6227 assert(pindexFirstNotTreeValid == nullptr);
6228 if (pindex->nStatus.getValidity() >= BlockValidity::TREE) {
6229 // TREE valid implies all parents are TREE valid
6230 assert(pindexFirstNotTreeValid == nullptr);
6231 }
6232 if (pindex->nStatus.getValidity() >= BlockValidity::CHAIN) {
6233 // CHAIN valid implies all parents are CHAIN valid
6234 assert(pindexFirstNotChainValid == nullptr);
6235 }
6236 if (pindex->nStatus.getValidity() >= BlockValidity::SCRIPTS) {
6237 // SCRIPTS valid implies all parents are SCRIPTS valid
6238 assert(pindexFirstNotScriptsValid == nullptr);
6239 }
6240 if (pindexFirstInvalid == nullptr) {
6241 // Checks for not-invalid blocks.
6242 // The failed mask cannot be set for blocks without invalid parents.
6243 assert(!pindex->nStatus.isInvalid());
6244 }
6245 if (pindexFirstParked == nullptr) {
6246 // Checks for not-parked blocks.
6247 // The parked mask cannot be set for blocks without parked parents.
6248 // (i.e., hasParkedParent only if an ancestor is properly parked).
6249 assert(!pindex->nStatus.isOnParkedChain());
6250 }
6251 // Make sure nChainTx sum is correctly computed.
6252 if (!pindex->pprev) {
6253 // If no previous block, nTx and nChainTx must be the same.
6254 assert(pindex->nChainTx == pindex->nTx);
6255 } else if (pindex->pprev->nChainTx > 0 && pindex->nTx > 0) {
6256 // If previous nChainTx is set and number of transactions in block
6257 // is known, sum must be set.
6258 assert(pindex->nChainTx == pindex->nTx + pindex->pprev->nChainTx);
6259 } else {
6260 // Otherwise nChainTx should only be set if this is a snapshot
6261 // block, and must be set if it is.
6262 assert((pindex->nChainTx != 0) == (pindex == snap_base));
6263 }
6264
6265 // Chainstate-specific checks on setBlockIndexCandidates
6266 for (auto c : GetAll()) {
6267 if (c->m_chain.Tip() == nullptr) {
6268 continue;
6269 }
6270 // Two main factors determine whether pindex is a candidate in
6271 // setBlockIndexCandidates:
6272 //
6273 // - If pindex has less work than the chain tip, it should not be a
6274 // candidate, and this will be asserted below. Otherwise it is a
6275 // potential candidate.
6276 //
6277 // - If pindex or one of its parent blocks back to the genesis block
6278 // or an assumeutxo snapshot never downloaded transactions
6279 // (pindexFirstNeverProcessed is non-null), it should not be a
6280 // candidate, and this will be asserted below. The only exception
6281 // is if pindex itself is an assumeutxo snapshot block. Then it is
6282 // also a potential candidate.
6283 if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) &&
6284 (pindexFirstNeverProcessed == nullptr || pindex == snap_base)) {
6285 // If pindex was detected as invalid (pindexFirstInvalid is
6286 // non-null), it is not required to be in
6287 // setBlockIndexCandidates.
6288 if (pindexFirstInvalid == nullptr) {
6289 // If this chainstate is the active chainstate, pindex
6290 // must be in setBlockIndexCandidates. Otherwise, this
6291 // chainstate is a background validation chainstate, and
6292 // pindex only needs to be added if it is an ancestor of
6293 // the snapshot that is being validated.
6294 if (c == &ActiveChainstate() ||
6295 GetSnapshotBaseBlock()->GetAncestor(pindex->nHeight) ==
6296 pindex) {
6297 // If pindex and all its parents back to the genesis
6298 // block or an assumeutxo snapshot block downloaded
6299 // transactions, transactions, and the transactions were
6300 // not pruned (pindexFirstMissing is null), it is a
6301 // potential candidate or was parked. The check excludes
6302 // pruned blocks, because if any blocks were pruned
6303 // between pindex the current chain tip, pindex will
6304 // only temporarily be added to setBlockIndexCandidates,
6305 // before being moved to m_blocks_unlinked. This check
6306 // could be improved to verify that if all blocks
6307 // between the chain tip and pindex have data, pindex
6308 // must be a candidate.
6309 if (pindexFirstMissing == nullptr) {
6310 assert(pindex->nStatus.isOnParkedChain() ||
6311 c->setBlockIndexCandidates.count(pindex));
6312 }
6313 // If pindex is the chain tip, it also is a potential
6314 // candidate.
6315 //
6316 // If the chainstate was loaded from a snapshot and
6317 // pindex is the base of the snapshot, pindex is also a
6318 // potential candidate.
6319 if (pindex == c->m_chain.Tip() ||
6320 pindex == c->SnapshotBase()) {
6321 assert(c->setBlockIndexCandidates.count(pindex));
6322 }
6323 }
6324 // If some parent is missing, then it could be that this
6325 // block was in setBlockIndexCandidates but had to be
6326 // removed because of the missing data. In this case it must
6327 // be in m_blocks_unlinked -- see test below.
6328 }
6329 } else {
6330 // If this block sorts worse than the current tip or some
6331 // ancestor's block has never been seen, it cannot be in
6332 // setBlockIndexCandidates.
6333 assert(c->setBlockIndexCandidates.count(pindex) == 0);
6334 }
6335 }
6336 // Check whether this block is in m_blocks_unlinked.
6337 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6338 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6339 rangeUnlinked =
6340 m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
6341 bool foundInUnlinked = false;
6342 while (rangeUnlinked.first != rangeUnlinked.second) {
6343 assert(rangeUnlinked.first->first == pindex->pprev);
6344 if (rangeUnlinked.first->second == pindex) {
6345 foundInUnlinked = true;
6346 break;
6347 }
6348 rangeUnlinked.first++;
6349 }
6350 if (pindex->pprev && pindex->nStatus.hasData() &&
6351 pindexFirstNeverProcessed != nullptr &&
6352 pindexFirstInvalid == nullptr) {
6353 // If this block has block data available, some parent was never
6354 // received, and has no invalid parents, it must be in
6355 // m_blocks_unlinked.
6356 assert(foundInUnlinked);
6357 }
6358 if (!pindex->nStatus.hasData()) {
6359 // Can't be in m_blocks_unlinked if we don't HAVE_DATA
6360 assert(!foundInUnlinked);
6361 }
6362 if (pindexFirstMissing == nullptr) {
6363 // We aren't missing data for any parent -- cannot be in
6364 // m_blocks_unlinked.
6365 assert(!foundInUnlinked);
6366 }
6367 if (pindex->pprev && pindex->nStatus.hasData() &&
6368 pindexFirstNeverProcessed == nullptr &&
6369 pindexFirstMissing != nullptr) {
6370 // We HAVE_DATA for this block, have received data for all parents
6371 // at some point, but we're currently missing data for some parent.
6373 // This block may have entered m_blocks_unlinked if:
6374 // - it has a descendant that at some point had more work than the
6375 // tip, and
6376 // - we tried switching to that descendant but were missing
6377 // data for some intermediate block between m_chain and the
6378 // tip.
6379 // So if this block is itself better than any m_chain.Tip() and it
6380 // wasn't in setBlockIndexCandidates, then it must be in
6381 // m_blocks_unlinked.
6382 for (auto c : GetAll()) {
6383 const bool is_active = c == &ActiveChainstate();
6384 if (!CBlockIndexWorkComparator()(pindex, c->m_chain.Tip()) &&
6385 c->setBlockIndexCandidates.count(pindex) == 0) {
6386 if (pindexFirstInvalid == nullptr) {
6387 if (is_active ||
6388 snap_base->GetAncestor(pindex->nHeight) == pindex) {
6389 assert(foundInUnlinked);
6390 }
6391 }
6392 }
6393 }
6394 }
6395 // Perhaps too slow
6396 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash());
6397 // End: actual consistency checks.
6398
6399 // Try descending into the first subnode.
6400 snap_update_firsts();
6401 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6402 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6403 range = forward.equal_range(pindex);
6404 if (range.first != range.second) {
6405 // A subnode was found.
6406 pindex = range.first->second;
6407 nHeight++;
6408 continue;
6409 }
6410 // This is a leaf node. Move upwards until we reach a node of which we
6411 // have not yet visited the last child.
6412 while (pindex) {
6413 // We are going to either move to a parent or a sibling of pindex.
6414 snap_update_firsts();
6415 // If pindex was the first with a certain property, unset the
6416 // corresponding variable.
6417 if (pindex == pindexFirstInvalid) {
6418 pindexFirstInvalid = nullptr;
6419 }
6420 if (pindex == pindexFirstParked) {
6421 pindexFirstParked = nullptr;
6422 }
6423 if (pindex == pindexFirstMissing) {
6424 pindexFirstMissing = nullptr;
6425 }
6426 if (pindex == pindexFirstNeverProcessed) {
6427 pindexFirstNeverProcessed = nullptr;
6428 }
6429 if (pindex == pindexFirstNotTreeValid) {
6430 pindexFirstNotTreeValid = nullptr;
6431 }
6432 if (pindex == pindexFirstNotTransactionsValid) {
6433 pindexFirstNotTransactionsValid = nullptr;
6434 }
6435 if (pindex == pindexFirstNotChainValid) {
6436 pindexFirstNotChainValid = nullptr;
6437 }
6438 if (pindex == pindexFirstNotScriptsValid) {
6439 pindexFirstNotScriptsValid = nullptr;
6440 }
6441 // Find our parent.
6442 CBlockIndex *pindexPar = pindex->pprev;
6443 // Find which child we just visited.
6444 std::pair<std::multimap<CBlockIndex *, CBlockIndex *>::iterator,
6445 std::multimap<CBlockIndex *, CBlockIndex *>::iterator>
6446 rangePar = forward.equal_range(pindexPar);
6447 while (rangePar.first->second != pindex) {
6448 // Our parent must have at least the node we're coming from as
6449 // child.
6450 assert(rangePar.first != rangePar.second);
6451 rangePar.first++;
6452 }
6453 // Proceed to the next one.
6454 rangePar.first++;
6455 if (rangePar.first != rangePar.second) {
6456 // Move to the sibling.
6457 pindex = rangePar.first->second;
6458 break;
6459 } else {
6460 // Move up further.
6461 pindex = pindexPar;
6462 nHeight--;
6463 continue;
6464 }
6465 }
6466 }
6467
6468 // Check that we actually traversed the entire map.
6469 assert(nNodes == forward.size());
6470}
6471
6472std::string Chainstate::ToString() {
6474 CBlockIndex *tip = m_chain.Tip();
6475 return strprintf("Chainstate [%s] @ height %d (%s)",
6476 m_from_snapshot_blockhash ? "snapshot" : "ibd",
6477 tip ? tip->nHeight : -1,
6478 tip ? tip->GetBlockHash().ToString() : "null");
6479}
6480
6481bool Chainstate::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) {
6483 if (coinstip_size == m_coinstip_cache_size_bytes &&
6484 coinsdb_size == m_coinsdb_cache_size_bytes) {
6485 // Cache sizes are unchanged, no need to continue.
6486 return true;
6487 }
6488 size_t old_coinstip_size = m_coinstip_cache_size_bytes;
6489 m_coinstip_cache_size_bytes = coinstip_size;
6490 m_coinsdb_cache_size_bytes = coinsdb_size;
6491 CoinsDB().ResizeCache(coinsdb_size);
6492
6493 LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n", this->ToString(),
6494 coinsdb_size * (1.0 / 1024 / 1024));
6495 LogPrintf("[%s] resized coinstip cache to %.1f MiB\n", this->ToString(),
6496 coinstip_size * (1.0 / 1024 / 1024));
6497
6499 bool ret;
6500
6501 if (coinstip_size > old_coinstip_size) {
6502 // Likely no need to flush if cache sizes have grown.
6504 } else {
6505 // Otherwise, flush state to disk and deallocate the in-memory coins
6506 // map.
6508 }
6509 return ret;
6510}
6511
6517 const CBlockIndex *pindex) {
6518 if (pindex == nullptr) {
6519 return 0.0;
6520 }
6521 if (pindex->nChainTx == 0) {
6523 "Block %d has unset m_chain_tx_count. Unable to "
6524 "estimate verification progress.\n",
6525 pindex->nHeight);
6526 return 0.0;
6527 }
6528
6529 int64_t nNow = time(nullptr);
6530
6531 double fTxTotal;
6532 if (pindex->GetChainTxCount() <= data.nTxCount) {
6533 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
6534 } else {
6535 fTxTotal = pindex->GetChainTxCount() +
6536 (nNow - pindex->GetBlockTime()) * data.dTxRate;
6537 }
6538
6539 return std::min<double>(pindex->GetChainTxCount() / fTxTotal, 1.0);
6540}
6541
6542std::optional<BlockHash> ChainstateManager::SnapshotBlockhash() const {
6543 LOCK(::cs_main);
6544 if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
6545 // If a snapshot chainstate exists, it will always be our active.
6546 return m_active_chainstate->m_from_snapshot_blockhash;
6547 }
6548 return std::nullopt;
6549}
6550
6551std::vector<Chainstate *> ChainstateManager::GetAll() {
6552 LOCK(::cs_main);
6553 std::vector<Chainstate *> out;
6554
6555 for (Chainstate *pchainstate :
6556 {m_ibd_chainstate.get(), m_snapshot_chainstate.get()}) {
6557 if (this->IsUsable(pchainstate)) {
6558 out.push_back(pchainstate);
6559 }
6560 }
6561
6562 return out;
6563}
6564
6565Chainstate &ChainstateManager::InitializeChainstate(CTxMemPool *mempool) {
6567 assert(!m_ibd_chainstate);
6568 assert(!m_active_chainstate);
6569
6570 m_ibd_chainstate = std::make_unique<Chainstate>(mempool, m_blockman, *this);
6571 m_active_chainstate = m_ibd_chainstate.get();
6572 return *m_active_chainstate;
6573}
6574
6575[[nodiscard]] static bool DeleteCoinsDBFromDisk(const fs::path &db_path,
6576 bool is_snapshot)
6579
6580 if (is_snapshot) {
6581 fs::path base_blockhash_path =
6583
6584 try {
6585 const bool existed{fs::remove(base_blockhash_path)};
6586 if (!existed) {
6587 LogPrintf("[snapshot] snapshot chainstate dir being removed "
6588 "lacks %s file\n",
6590 }
6591 } catch (const fs::filesystem_error &e) {
6592 LogPrintf("[snapshot] failed to remove file %s: %s\n",
6593 fs::PathToString(base_blockhash_path),
6595 }
6596 }
6597
6598 std::string path_str = fs::PathToString(db_path);
6599 LogPrintf("Removing leveldb dir at %s\n", path_str);
6600
6601 // We have to destruct before this call leveldb::DB in order to release the
6602 // db lock, otherwise `DestroyDB` will fail. See `leveldb::~DBImpl()`.
6603 const bool destroyed = dbwrapper::DestroyDB(path_str, {}).ok();
6604
6605 if (!destroyed) {
6606 LogPrintf("error: leveldb DestroyDB call failed on %s\n", path_str);
6607 }
6608
6609 // Datadir should be removed from filesystem; otherwise initialization may
6610 // detect it on subsequent statups and get confused.
6611 //
6612 // If the base_blockhash_path removal above fails in the case of snapshot
6613 // chainstates, this will return false since leveldb won't remove a
6614 // non-empty directory.
6615 return destroyed && !fs::exists(db_path);
6616}
6617
6619 AutoFile &coins_file, const SnapshotMetadata &metadata, bool in_memory) {
6620 BlockHash base_blockhash = metadata.m_base_blockhash;
6621
6622 if (this->SnapshotBlockhash()) {
6624 "Can't activate a snapshot-based chainstate more than once")};
6625 }
6626
6627 CBlockIndex *snapshot_start_block{};
6628
6629 {
6630 LOCK(::cs_main);
6631
6632 if (!GetParams().AssumeutxoForBlockhash(base_blockhash).has_value()) {
6633 auto available_heights = GetParams().GetAvailableSnapshotHeights();
6634 std::string heights_formatted =
6635 Join(available_heights, ", ",
6636 [&](const auto &i) { return ToString(i); });
6637 return util::Error{strprintf(
6638 Untranslated("assumeutxo block hash in snapshot metadata not "
6639 "recognized (hash: %s). The following "
6640 "snapshot heights are available: %s."),
6641 base_blockhash.ToString(), heights_formatted)};
6642 }
6643
6644 snapshot_start_block = m_blockman.LookupBlockIndex(base_blockhash);
6645 if (!snapshot_start_block) {
6646 return util::Error{strprintf(
6647 Untranslated("The base block header (%s) must appear in the "
6648 "headers chain. Make sure all headers are "
6649 "syncing, and call loadtxoutset again."),
6650 base_blockhash.ToString())};
6651 }
6652
6653 if (snapshot_start_block->nStatus.isInvalid()) {
6654 return util::Error{strprintf(
6656 "The base block header (%s) is part of an invalid chain"),
6657 base_blockhash.ToString())};
6658 }
6659
6660 if (!m_best_header ||
6661 m_best_header->GetAncestor(snapshot_start_block->nHeight) !=
6662 snapshot_start_block) {
6664 "A forked headers-chain with more work than the chain with the "
6665 "snapshot base block header exists. Please proceed to sync "
6666 "without AssumeUtxo.")};
6667 }
6668
6669 if (Assert(m_active_chainstate->GetMempool())->size() > 0) {
6671 "Can't activate a snapshot when mempool not empty.")};
6672 }
6673 }
6674
6675 int64_t current_coinsdb_cache_size{0};
6676 int64_t current_coinstip_cache_size{0};
6677
6678 // Cache percentages to allocate to each chainstate.
6679 //
6680 // These particular percentages don't matter so much since they will only be
6681 // relevant during snapshot activation; caches are rebalanced at the
6682 // conclusion of this function. We want to give (essentially) all available
6683 // cache capacity to the snapshot to aid the bulk load later in this
6684 // function.
6685 static constexpr double IBD_CACHE_PERC = 0.01;
6686 static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
6687
6688 {
6689 LOCK(::cs_main);
6690 // Resize the coins caches to ensure we're not exceeding memory limits.
6691 //
6692 // Allocate the majority of the cache to the incoming snapshot
6693 // chainstate, since (optimistically) getting to its tip will be the top
6694 // priority. We'll need to call `MaybeRebalanceCaches()` once we're done
6695 // with this function to ensure the right allocation (including the
6696 // possibility that no snapshot was activated and that we should restore
6697 // the active chainstate caches to their original size).
6698 //
6699 current_coinsdb_cache_size =
6700 this->ActiveChainstate().m_coinsdb_cache_size_bytes;
6701 current_coinstip_cache_size =
6702 this->ActiveChainstate().m_coinstip_cache_size_bytes;
6703
6704 // Temporarily resize the active coins cache to make room for the
6705 // newly-created snapshot chain.
6706 this->ActiveChainstate().ResizeCoinsCaches(
6707 static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
6708 static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
6709 }
6710
6711 auto snapshot_chainstate =
6712 WITH_LOCK(::cs_main, return std::make_unique<Chainstate>(
6713 /* mempool */ nullptr, m_blockman, *this,
6714 base_blockhash));
6715
6716 {
6717 LOCK(::cs_main);
6718 snapshot_chainstate->InitCoinsDB(
6719 static_cast<size_t>(current_coinsdb_cache_size *
6720 SNAPSHOT_CACHE_PERC),
6721 in_memory, false, "chainstate");
6722 snapshot_chainstate->InitCoinsCache(static_cast<size_t>(
6723 current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
6724 }
6725
6726 auto cleanup_bad_snapshot =
6728 this->MaybeRebalanceCaches();
6729
6730 // PopulateAndValidateSnapshot can return (in error) before the
6731 // leveldb datadir has been created, so only attempt removal if we
6732 // got that far.
6733 if (auto snapshot_datadir =
6735 // We have to destruct leveldb::DB in order to release the db
6736 // lock, otherwise DestroyDB() (in DeleteCoinsDBFromDisk()) will
6737 // fail. See `leveldb::~DBImpl()`. Destructing the chainstate
6738 // (and so resetting the coinsviews object) does this.
6739 snapshot_chainstate.reset();
6740 bool removed = DeleteCoinsDBFromDisk(*snapshot_datadir,
6741 /*is_snapshot=*/true);
6742 if (!removed) {
6744 "Failed to remove snapshot chainstate dir (%s). "
6745 "Manually remove it before restarting.\n",
6746 fs::PathToString(*snapshot_datadir)));
6747 }
6748 }
6749 return util::Error{std::move(reason)};
6750 };
6751
6752 if (!this->PopulateAndValidateSnapshot(*snapshot_chainstate, coins_file,
6753 metadata)) {
6754 LOCK(::cs_main);
6755 return cleanup_bad_snapshot(Untranslated("population failed"));
6756 }
6757
6758 // cs_main required for rest of snapshot activation.
6759 LOCK(::cs_main);
6760
6761 // Do a final check to ensure that the snapshot chainstate is actually a
6762 // more work chain than the active chainstate; a user could have loaded a
6763 // snapshot very late in the IBD process, and we wouldn't want to load a
6764 // useless chainstate.
6766 snapshot_chainstate->m_chain.Tip())) {
6767 return cleanup_bad_snapshot(
6768 Untranslated("work does not exceed active chainstate"));
6769 }
6770 // If not in-memory, persist the base blockhash for use during subsequent
6771 // initialization.
6772 if (!in_memory) {
6773 if (!node::WriteSnapshotBaseBlockhash(*snapshot_chainstate)) {
6774 return cleanup_bad_snapshot(
6775 Untranslated("could not write base blockhash"));
6776 }
6777 }
6778
6779 assert(!m_snapshot_chainstate);
6780 m_snapshot_chainstate.swap(snapshot_chainstate);
6781 const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
6782 assert(chaintip_loaded);
6783
6784 // Transfer possession of the mempool to the snapshot chainstate.
6785 // Mempool is empty at this point because we're still in IBD.
6786 Assert(m_active_chainstate->m_mempool->size() == 0);
6787 Assert(!m_snapshot_chainstate->m_mempool);
6788 m_snapshot_chainstate->m_mempool = m_active_chainstate->m_mempool;
6789 m_active_chainstate->m_mempool = nullptr;
6790 m_active_chainstate = m_snapshot_chainstate.get();
6791 m_blockman.m_snapshot_height = this->GetSnapshotBaseHeight();
6792
6793 LogPrintf("[snapshot] successfully activated snapshot %s\n",
6794 base_blockhash.ToString());
6795 LogPrintf("[snapshot] (%.2f MB)\n",
6796 m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() /
6797 (1000 * 1000));
6798
6799 this->MaybeRebalanceCaches();
6800 return snapshot_start_block;
6801}
6802
6803static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache,
6804 bool snapshot_loaded) {
6806 strprintf("%s (%.2f MB)",
6807 snapshot_loaded ? "saving snapshot chainstate"
6808 : "flushing coins cache",
6809 coins_cache.DynamicMemoryUsage() / (1000 * 1000)),
6810 BCLog::LogFlags::ALL);
6811
6812 coins_cache.Flush();
6813}
6814
6815struct StopHashingException : public std::exception {
6816 const char *what() const throw() override {
6817 return "ComputeUTXOStats interrupted by shutdown.";
6818 }
6819};
6820
6822 if (interrupt) {
6823 throw StopHashingException();
6824 }
6825}
6826
6828 Chainstate &snapshot_chainstate, AutoFile &coins_file,
6829 const SnapshotMetadata &metadata) {
6830 // It's okay to release cs_main before we're done using `coins_cache`
6831 // because we know that nothing else will be referencing the newly created
6832 // snapshot_chainstate yet.
6833 CCoinsViewCache &coins_cache =
6834 *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
6835
6836 BlockHash base_blockhash = metadata.m_base_blockhash;
6837
6838 CBlockIndex *snapshot_start_block = WITH_LOCK(
6839 ::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
6840
6841 if (!snapshot_start_block) {
6842 // Needed for ComputeUTXOStats to determine the
6843 // height and to avoid a crash when base_blockhash.IsNull()
6844 LogPrintf("[snapshot] Did not find snapshot start blockheader %s\n",
6845 base_blockhash.ToString());
6846 return false;
6847 }
6848
6849 int base_height = snapshot_start_block->nHeight;
6850 const auto &maybe_au_data = GetParams().AssumeutxoForHeight(base_height);
6851
6852 if (!maybe_au_data) {
6853 LogPrintf("[snapshot] assumeutxo height in snapshot metadata not "
6854 "recognized (%d) - refusing to load snapshot\n",
6855 base_height);
6856 return false;
6857 }
6858
6859 const AssumeutxoData &au_data = *maybe_au_data;
6860
6861 // This work comparison is a duplicate check with the one performed later in
6862 // ActivateSnapshot(), but is done so that we avoid doing the long work of
6863 // staging a snapshot that isn't actually usable.
6865 ActiveTip(), snapshot_start_block))) {
6866 LogPrintf("[snapshot] activation failed - work does not exceed active "
6867 "chainstate\n");
6868 return false;
6869 }
6870
6871 const uint64_t coins_count = metadata.m_coins_count;
6872 uint64_t coins_left = metadata.m_coins_count;
6873
6874 LogPrintf("[snapshot] loading %d coins from snapshot %s\n", coins_left,
6875 base_blockhash.ToString());
6876 int64_t coins_processed{0};
6877
6878 while (coins_left > 0) {
6879 try {
6880 TxId txid;
6881 coins_file >> txid;
6882 size_t coins_per_txid{0};
6883 coins_per_txid = ReadCompactSize(coins_file);
6884
6885 if (coins_per_txid > coins_left) {
6886 LogPrintf("[snapshot] mismatch in coins count in snapshot "
6887 "metadata and actual snapshot data\n");
6888 return false;
6889 }
6890
6891 for (size_t i = 0; i < coins_per_txid; i++) {
6892 Coin coin;
6893 COutPoint outpoint{
6894 txid, static_cast<uint32_t>(ReadCompactSize(coins_file))};
6895 coins_file >> coin;
6896 // Avoid integer wrap-around in coinstats.cpp:ApplyHash
6897 if (coin.GetHeight() > uint32_t(base_height) ||
6898 outpoint.GetN() >=
6899 std::numeric_limits<decltype(outpoint.GetN())>::max()) {
6900 LogPrintf("[snapshot] bad snapshot data after "
6901 "deserializing %d coins\n",
6902 coins_count - coins_left);
6903 return false;
6904 }
6905 if (!MoneyRange(coin.GetTxOut().nValue)) {
6906 LogPrintf("[snapshot] bad snapshot data after "
6907 "deserializing %d coins - bad tx out value\n",
6908 coins_count - coins_left);
6909 return false;
6910 }
6911 coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint),
6912 std::move(coin));
6913
6914 --coins_left;
6915 ++coins_processed;
6916
6917 if (coins_processed % 1000000 == 0) {
6918 LogPrintf("[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
6919 coins_processed,
6920 static_cast<float>(coins_processed) * 100 /
6921 static_cast<float>(coins_count),
6922 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
6923 }
6924
6925 // Batch write and flush (if we need to) every so often.
6926 //
6927 // If our average Coin size is roughly 41 bytes, checking every
6928 // 120,000 coins means <5MB of memory imprecision.
6929 if (coins_processed % 120000 == 0) {
6930 if (m_interrupt) {
6931 return false;
6932 }
6933
6934 const auto snapshot_cache_state = WITH_LOCK(
6935 ::cs_main,
6936 return snapshot_chainstate.GetCoinsCacheSizeState());
6937
6938 if (snapshot_cache_state >= CoinsCacheSizeState::CRITICAL) {
6939 // This is a hack - we don't know what the actual best
6940 // block is, but that doesn't matter for the purposes of
6941 // flushing the cache here. We'll set this to its
6942 // correct value (`base_blockhash`) below after the
6943 // coins are loaded.
6944 coins_cache.SetBestBlock(BlockHash{GetRandHash()});
6945
6946 // No need to acquire cs_main since this chainstate
6947 // isn't being used yet.
6948 FlushSnapshotToDisk(coins_cache,
6949 /*snapshot_loaded=*/false);
6950 }
6951 }
6952 }
6953 } catch (const std::ios_base::failure &) {
6954 LogPrintf("[snapshot] bad snapshot format or truncated snapshot "
6955 "after deserializing %d coins\n",
6956 coins_processed);
6957 return false;
6958 }
6959 }
6960
6961 // Important that we set this. This and the coins_cache accesses above are
6962 // sort of a layer violation, but either we reach into the innards of
6963 // CCoinsViewCache here or we have to invert some of the Chainstate to
6964 // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
6965 // method.
6966 coins_cache.SetBestBlock(base_blockhash);
6967
6968 bool out_of_coins{false};
6969 try {
6970 TxId txid;
6971 coins_file >> txid;
6972 } catch (const std::ios_base::failure &) {
6973 // We expect an exception since we should be out of coins.
6974 out_of_coins = true;
6975 }
6976 if (!out_of_coins) {
6977 LogPrintf("[snapshot] bad snapshot - coins left over after "
6978 "deserializing %d coins\n",
6979 coins_count);
6980 return false;
6981 }
6982
6983 LogPrintf("[snapshot] loaded %d (%.2f MB) coins from snapshot %s\n",
6984 coins_count, coins_cache.DynamicMemoryUsage() / (1000 * 1000),
6985 base_blockhash.ToString());
6986
6987 // No need to acquire cs_main since this chainstate isn't being used yet.
6988 FlushSnapshotToDisk(coins_cache, /*snapshot_loaded=*/true);
6989
6990 assert(coins_cache.GetBestBlock() == base_blockhash);
6991
6992 // As above, okay to immediately release cs_main here since no other context
6993 // knows about the snapshot_chainstate.
6994 CCoinsViewDB *snapshot_coinsdb =
6995 WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsDB());
6996
6997 std::optional<CCoinsStats> maybe_stats;
6998
6999 try {
7000 maybe_stats = ComputeUTXOStats(
7001 CoinStatsHashType::HASH_SERIALIZED, snapshot_coinsdb, m_blockman,
7002 [&interrupt = m_interrupt] {
7003 SnapshotUTXOHashBreakpoint(interrupt);
7004 });
7005 } catch (StopHashingException const &) {
7006 return false;
7007 }
7008 if (!maybe_stats.has_value()) {
7009 LogPrintf("[snapshot] failed to generate coins stats\n");
7010 return false;
7011 }
7012
7013 // Assert that the deserialized chainstate contents match the expected
7014 // assumeutxo value.
7015 if (AssumeutxoHash{maybe_stats->hashSerialized} !=
7016 au_data.hash_serialized) {
7017 LogPrintf("[snapshot] bad snapshot content hash: expected %s, got %s\n",
7018 au_data.hash_serialized.ToString(),
7019 maybe_stats->hashSerialized.ToString());
7020 return false;
7021 }
7022
7023 snapshot_chainstate.m_chain.SetTip(*snapshot_start_block);
7024
7025 // The remainder of this function requires modifying data protected by
7026 // cs_main.
7027 LOCK(::cs_main);
7028
7029 // Fake various pieces of CBlockIndex state:
7030 CBlockIndex *index = nullptr;
7031
7032 // Don't make any modifications to the genesis block since it shouldn't be
7033 // necessary, and since the genesis block doesn't have normal flags like
7034 // BLOCK_VALID_SCRIPTS set.
7035 constexpr int AFTER_GENESIS_START{1};
7036
7037 for (int i = AFTER_GENESIS_START; i <= snapshot_chainstate.m_chain.Height();
7038 ++i) {
7039 index = snapshot_chainstate.m_chain[i];
7040
7041 m_blockman.m_dirty_blockindex.insert(index);
7042 // Changes to the block index will be flushed to disk after this call
7043 // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
7044 // called, since we've added a snapshot chainstate and therefore will
7045 // have to downsize the IBD chainstate, which will result in a call to
7046 // `FlushStateToDisk(ALWAYS)`.
7047 }
7048
7049 assert(index);
7050 assert(index == snapshot_start_block);
7051 index->nChainTx = au_data.nChainTx;
7052 snapshot_chainstate.setBlockIndexCandidates.insert(snapshot_start_block);
7053
7054 LogPrintf("[snapshot] validated snapshot (%.2f MB)\n",
7055 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
7056 return true;
7057}
7058
7059// Currently, this function holds cs_main for its duration, which could be for
7060// multiple minutes due to the ComputeUTXOStats call. This hold is necessary
7061// because we need to avoid advancing the background validation chainstate
7062// farther than the snapshot base block - and this function is also invoked
7063// from within ConnectTip, i.e. from within ActivateBestChain, so cs_main is
7064// held anyway.
7065//
7066// Eventually (TODO), we could somehow separate this function's runtime from
7067// maintenance of the active chain, but that will either require
7068//
7069// (i) setting `m_disabled` immediately and ensuring all chainstate accesses go
7070// through IsUsable() checks, or
7071//
7072// (ii) giving each chainstate its own lock instead of using cs_main for
7073// everything.
7074SnapshotCompletionResult ChainstateManager::MaybeCompleteSnapshotValidation() {
7076 if (m_ibd_chainstate.get() == &this->ActiveChainstate() ||
7077 !this->IsUsable(m_snapshot_chainstate.get()) ||
7078 !this->IsUsable(m_ibd_chainstate.get()) ||
7079 !m_ibd_chainstate->m_chain.Tip()) {
7080 // Nothing to do - this function only applies to the background
7081 // validation chainstate.
7083 }
7084 const int snapshot_tip_height = this->ActiveHeight();
7085 const int snapshot_base_height = *Assert(this->GetSnapshotBaseHeight());
7086 const CBlockIndex &index_new = *Assert(m_ibd_chainstate->m_chain.Tip());
7087
7088 if (index_new.nHeight < snapshot_base_height) {
7089 // Background IBD not complete yet.
7091 }
7092
7094 BlockHash snapshot_blockhash = *Assert(SnapshotBlockhash());
7095
7096 auto handle_invalid_snapshot = [&]() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
7097 bilingual_str user_error = strprintf(
7098 _("%s failed to validate the -assumeutxo snapshot state. "
7099 "This indicates a hardware problem, or a bug in the software, or "
7100 "a bad software modification that allowed an invalid snapshot to "
7101 "be loaded. As a result of this, the node will shut down and "
7102 "stop using any state that was built on the snapshot, resetting "
7103 "the chain height from %d to %d. On the next restart, the node "
7104 "will resume syncing from %d without using any snapshot data. "
7105 "Please report this incident to %s, including how you obtained "
7106 "the snapshot. The invalid snapshot chainstate will be left on "
7107 "disk in case it is helpful in diagnosing the issue that caused "
7108 "this error."),
7109 PACKAGE_NAME, snapshot_tip_height, snapshot_base_height,
7110 snapshot_base_height, PACKAGE_BUGREPORT);
7111
7112 LogPrintf("[snapshot] !!! %s\n", user_error.original);
7113 LogPrintf("[snapshot] deleting snapshot, reverting to validated chain, "
7114 "and stopping node\n");
7115
7116 m_active_chainstate = m_ibd_chainstate.get();
7117 m_snapshot_chainstate->m_disabled = true;
7118 assert(!this->IsUsable(m_snapshot_chainstate.get()));
7119 assert(this->IsUsable(m_ibd_chainstate.get()));
7120
7121 auto rename_result = m_snapshot_chainstate->InvalidateCoinsDBOnDisk();
7122 if (!rename_result) {
7123 user_error = strprintf(Untranslated("%s\n%s"), user_error,
7124 util::ErrorString(rename_result));
7125 }
7126
7127 GetNotifications().fatalError(user_error.original, user_error);
7128 };
7129
7130 if (index_new.GetBlockHash() != snapshot_blockhash) {
7131 LogPrintf(
7132 "[snapshot] supposed base block %s does not match the "
7133 "snapshot base block %s (height %d). Snapshot is not valid.\n",
7134 index_new.ToString(), snapshot_blockhash.ToString(),
7135 snapshot_base_height);
7136 handle_invalid_snapshot();
7138 }
7139
7140 assert(index_new.nHeight == snapshot_base_height);
7141
7142 int curr_height = m_ibd_chainstate->m_chain.Height();
7143
7144 assert(snapshot_base_height == curr_height);
7145 assert(snapshot_base_height == index_new.nHeight);
7146 assert(this->IsUsable(m_snapshot_chainstate.get()));
7147 assert(this->GetAll().size() == 2);
7148
7149 CCoinsViewDB &ibd_coins_db = m_ibd_chainstate->CoinsDB();
7150 m_ibd_chainstate->ForceFlushStateToDisk();
7151
7152 const auto &maybe_au_data =
7153 this->GetParams().AssumeutxoForHeight(curr_height);
7154 if (!maybe_au_data) {
7155 LogPrintf("[snapshot] assumeutxo data not found for height "
7156 "(%d) - refusing to validate snapshot\n",
7157 curr_height);
7158 handle_invalid_snapshot();
7160 }
7161
7162 const AssumeutxoData &au_data = *maybe_au_data;
7163 std::optional<CCoinsStats> maybe_ibd_stats;
7164 LogPrintf(
7165 "[snapshot] computing UTXO stats for background chainstate to validate "
7166 "snapshot - this could take a few minutes\n");
7167 try {
7168 maybe_ibd_stats =
7169 ComputeUTXOStats(CoinStatsHashType::HASH_SERIALIZED, &ibd_coins_db,
7170 m_blockman, [&interrupt = m_interrupt] {
7171 SnapshotUTXOHashBreakpoint(interrupt);
7172 });
7173 } catch (StopHashingException const &) {
7175 }
7176
7177 if (!maybe_ibd_stats) {
7178 LogPrintf(
7179 "[snapshot] failed to generate stats for validation coins db\n");
7180 // While this isn't a problem with the snapshot per se, this condition
7181 // prevents us from validating the snapshot, so we should shut down and
7182 // let the user handle the issue manually.
7183 handle_invalid_snapshot();
7185 }
7186 const auto &ibd_stats = *maybe_ibd_stats;
7187
7188 // Compare the background validation chainstate's UTXO set hash against the
7189 // hard-coded assumeutxo hash we expect.
7190 //
7191 // TODO: For belt-and-suspenders, we could cache the UTXO set
7192 // hash for the snapshot when it's loaded in its chainstate's leveldb. We
7193 // could then reference that here for an additional check.
7194 if (AssumeutxoHash{ibd_stats.hashSerialized} != au_data.hash_serialized) {
7195 LogPrintf("[snapshot] hash mismatch: actual=%s, expected=%s\n",
7196 ibd_stats.hashSerialized.ToString(),
7197 au_data.hash_serialized.ToString());
7198 handle_invalid_snapshot();
7200 }
7201
7202 LogPrintf("[snapshot] snapshot beginning at %s has been fully validated\n",
7203 snapshot_blockhash.ToString());
7204
7205 m_ibd_chainstate->m_disabled = true;
7206 this->MaybeRebalanceCaches();
7207
7209}
7210
7212 LOCK(::cs_main);
7213 assert(m_active_chainstate);
7214 return *m_active_chainstate;
7215}
7216
7218 auto &active_chainstate = ActiveChainstate();
7219 LOCK(active_chainstate.cs_avalancheFinalizedBlockIndex);
7220 return active_chainstate.m_avalancheFinalizedBlockIndex;
7221}
7222
7224 LOCK(::cs_main);
7225 return m_snapshot_chainstate &&
7226 m_active_chainstate == m_snapshot_chainstate.get();
7227}
7228void ChainstateManager::MaybeRebalanceCaches() {
7230 bool ibd_usable = this->IsUsable(m_ibd_chainstate.get());
7231 bool snapshot_usable = this->IsUsable(m_snapshot_chainstate.get());
7232 assert(ibd_usable || snapshot_usable);
7233
7234 if (ibd_usable && !snapshot_usable) {
7235 LogPrintf("[snapshot] allocating all cache to the IBD chainstate\n");
7236 // Allocate everything to the IBD chainstate.
7237 m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache,
7239 } else if (snapshot_usable && !ibd_usable) {
7240 // If background validation has completed and snapshot is our active
7241 // chain...
7242 LogPrintf(
7243 "[snapshot] allocating all cache to the snapshot chainstate\n");
7244 // Allocate everything to the snapshot chainstate.
7245 m_snapshot_chainstate->ResizeCoinsCaches(m_total_coinstip_cache,
7247 } else if (ibd_usable && snapshot_usable) {
7248 // If both chainstates exist, determine who needs more cache based on
7249 // IBD status.
7250 //
7251 // Note: shrink caches first so that we don't inadvertently overwhelm
7252 // available memory.
7253 if (IsInitialBlockDownload()) {
7254 m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache * 0.05,
7255 m_total_coinsdb_cache * 0.05);
7256 m_snapshot_chainstate->ResizeCoinsCaches(
7258 } else {
7259 m_snapshot_chainstate->ResizeCoinsCaches(
7261 m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache * 0.95,
7262 m_total_coinsdb_cache * 0.95);
7263 }
7264 }
7265}
7266
7267void ChainstateManager::ResetChainstates() {
7268 m_ibd_chainstate.reset();
7269 m_snapshot_chainstate.reset();
7270 m_active_chainstate = nullptr;
7271}
7272
7279 if (!opts.check_block_index.has_value()) {
7280 opts.check_block_index =
7281 opts.config.GetChainParams().DefaultConsistencyChecks();
7282 }
7283
7284 if (!opts.minimum_chain_work.has_value()) {
7285 opts.minimum_chain_work = UintToArith256(
7286 opts.config.GetChainParams().GetConsensus().nMinimumChainWork);
7287 }
7288 if (!opts.assumed_valid_block.has_value()) {
7289 opts.assumed_valid_block =
7290 opts.config.GetChainParams().GetConsensus().defaultAssumeValid;
7291 }
7292 Assert(opts.adjusted_time_callback);
7293 return std::move(opts);
7294}
7295
7297 const util::SignalInterrupt &interrupt, Options options,
7298 node::BlockManager::Options blockman_options)
7299 : m_interrupt{interrupt}, m_options{Flatten(std::move(options))},
7300 m_blockman{interrupt, std::move(blockman_options)},
7301 m_validation_cache{m_options.script_execution_cache_bytes,
7302 m_options.signature_cache_bytes} {}
7303
7304bool ChainstateManager::DetectSnapshotChainstate(CTxMemPool *mempool) {
7305 assert(!m_snapshot_chainstate);
7306 std::optional<fs::path> path =
7308 if (!path) {
7309 return false;
7310 }
7311 std::optional<BlockHash> base_blockhash =
7313 if (!base_blockhash) {
7314 return false;
7315 }
7316 LogPrintf("[snapshot] detected active snapshot chainstate (%s) - loading\n",
7317 fs::PathToString(*path));
7318
7319 this->ActivateExistingSnapshot(*base_blockhash);
7320 return true;
7321}
7322
7323Chainstate &
7324ChainstateManager::ActivateExistingSnapshot(BlockHash base_blockhash) {
7325 assert(!m_snapshot_chainstate);
7326 m_snapshot_chainstate = std::make_unique<Chainstate>(nullptr, m_blockman,
7327 *this, base_blockhash);
7328 LogPrintf("[snapshot] switching active chainstate to %s\n",
7329 m_snapshot_chainstate->ToString());
7330
7331 // Mempool is empty at this point because we're still in IBD.
7332 Assert(m_active_chainstate->m_mempool->size() == 0);
7333 Assert(!m_snapshot_chainstate->m_mempool);
7334 m_snapshot_chainstate->m_mempool = m_active_chainstate->m_mempool;
7335 m_active_chainstate->m_mempool = nullptr;
7336 m_active_chainstate = m_snapshot_chainstate.get();
7337 return *m_snapshot_chainstate;
7338}
7339
7343 // Should never be called on a non-snapshot chainstate.
7344 assert(cs.m_from_snapshot_blockhash);
7345 auto storage_path_maybe = cs.CoinsDB().StoragePath();
7346 // Should never be called with a non-existent storage path.
7347 assert(storage_path_maybe);
7348 return *storage_path_maybe;
7349}
7350
7351util::Result<void> Chainstate::InvalidateCoinsDBOnDisk() {
7352 fs::path snapshot_datadir = GetSnapshotCoinsDBPath(*this);
7353
7354 // Coins views no longer usable.
7355 m_coins_views.reset();
7356
7357 auto invalid_path = snapshot_datadir + "_INVALID";
7358 std::string dbpath = fs::PathToString(snapshot_datadir);
7359 std::string target = fs::PathToString(invalid_path);
7360 LogPrintf("[snapshot] renaming snapshot datadir %s to %s\n", dbpath,
7361 target);
7362
7363 // The invalid snapshot datadir is simply moved and not deleted because we
7364 // may want to do forensics later during issue investigation. The user is
7365 // instructed accordingly in MaybeCompleteSnapshotValidation().
7366 try {
7367 fs::rename(snapshot_datadir, invalid_path);
7368 } catch (const fs::filesystem_error &e) {
7369 auto src_str = fs::PathToString(snapshot_datadir);
7370 auto dest_str = fs::PathToString(invalid_path);
7371
7372 LogPrintf("%s: error renaming file '%s' -> '%s': %s\n", __func__,
7373 src_str, dest_str, e.what());
7374 return util::Error{strprintf(_("Rename of '%s' -> '%s' failed. "
7375 "You should resolve this by manually "
7376 "moving or deleting the invalid "
7377 "snapshot directory %s, otherwise you "
7378 "will encounter the same error again "
7379 "on the next startup."),
7380 src_str, dest_str, src_str)};
7381 }
7382 return {};
7383}
7384
7385bool ChainstateManager::DeleteSnapshotChainstate() {
7387 Assert(m_snapshot_chainstate);
7388 Assert(m_ibd_chainstate);
7389
7390 fs::path snapshot_datadir =
7392 if (!DeleteCoinsDBFromDisk(snapshot_datadir, /*is_snapshot=*/true)) {
7393 LogPrintf("Deletion of %s failed. Please remove it manually to "
7394 "continue reindexing.\n",
7395 fs::PathToString(snapshot_datadir));
7396 return false;
7397 }
7398 m_active_chainstate = m_ibd_chainstate.get();
7399 m_active_chainstate->m_mempool = m_snapshot_chainstate->m_mempool;
7400 m_snapshot_chainstate.reset();
7401 return true;
7402}
7403
7404ChainstateRole Chainstate::GetRole() const {
7405 if (m_chainman.GetAll().size() <= 1) {
7407 }
7408 return (this != &m_chainman.ActiveChainstate())
7411}
7412const CBlockIndex *ChainstateManager::GetSnapshotBaseBlock() const {
7413 return m_active_chainstate ? m_active_chainstate->SnapshotBase() : nullptr;
7414}
7415
7416std::optional<int> ChainstateManager::GetSnapshotBaseHeight() const {
7417 const CBlockIndex *base = this->GetSnapshotBaseBlock();
7418 return base ? std::make_optional(base->nHeight) : std::nullopt;
7419}
7420
7421void ChainstateManager::RecalculateBestHeader() {
7423 m_best_header = ActiveChain().Tip();
7424 for (auto &entry : m_blockman.m_block_index) {
7425 if (!(entry.second.nStatus.isInvalid()) &&
7426 m_best_header->nChainWork < entry.second.nChainWork) {
7427 m_best_header = &entry.second;
7428 }
7429 }
7430}
7431
7432bool ChainstateManager::ValidatedSnapshotCleanup() {
7434 auto get_storage_path = [](auto &chainstate) EXCLUSIVE_LOCKS_REQUIRED(
7435 ::cs_main) -> std::optional<fs::path> {
7436 if (!(chainstate && chainstate->HasCoinsViews())) {
7437 return {};
7438 }
7439 return chainstate->CoinsDB().StoragePath();
7440 };
7441 std::optional<fs::path> ibd_chainstate_path_maybe =
7442 get_storage_path(m_ibd_chainstate);
7443 std::optional<fs::path> snapshot_chainstate_path_maybe =
7444 get_storage_path(m_snapshot_chainstate);
7445
7446 if (!this->IsSnapshotValidated()) {
7447 // No need to clean up.
7448 return false;
7449 }
7450 // If either path doesn't exist, that means at least one of the chainstates
7451 // is in-memory, in which case we can't do on-disk cleanup. You'd better be
7452 // in a unittest!
7453 if (!ibd_chainstate_path_maybe || !snapshot_chainstate_path_maybe) {
7454 LogPrintf("[snapshot] snapshot chainstate cleanup cannot happen with "
7455 "in-memory chainstates. You are testing, right?\n");
7456 return false;
7457 }
7458
7459 const auto &snapshot_chainstate_path = *snapshot_chainstate_path_maybe;
7460 const auto &ibd_chainstate_path = *ibd_chainstate_path_maybe;
7461
7462 // Since we're going to be moving around the underlying leveldb filesystem
7463 // content for each chainstate, make sure that the chainstates (and their
7464 // constituent CoinsViews members) have been destructed first.
7465 //
7466 // The caller of this method will be responsible for reinitializing
7467 // chainstates if they want to continue operation.
7468 this->ResetChainstates();
7469
7470 // No chainstates should be considered usable.
7471 assert(this->GetAll().size() == 0);
7472
7473 LogPrintf("[snapshot] deleting background chainstate directory (now "
7474 "unnecessary) (%s)\n",
7475 fs::PathToString(ibd_chainstate_path));
7476
7477 fs::path tmp_old{ibd_chainstate_path + "_todelete"};
7478
7479 auto rename_failed_abort = [this](fs::path p_old, fs::path p_new,
7480 const fs::filesystem_error &err) {
7481 LogPrintf("Error renaming file (%s): %s\n", fs::PathToString(p_old),
7482 err.what());
7484 "Rename of '%s' -> '%s' failed. "
7485 "Cannot clean up the background chainstate leveldb directory.",
7486 fs::PathToString(p_old), fs::PathToString(p_new)));
7487 };
7488
7489 try {
7490 fs::rename(ibd_chainstate_path, tmp_old);
7491 } catch (const fs::filesystem_error &e) {
7492 rename_failed_abort(ibd_chainstate_path, tmp_old, e);
7493 throw;
7494 }
7495
7496 LogPrintf("[snapshot] moving snapshot chainstate (%s) to "
7497 "default chainstate directory (%s)\n",
7498 fs::PathToString(snapshot_chainstate_path),
7499 fs::PathToString(ibd_chainstate_path));
7500
7501 try {
7502 fs::rename(snapshot_chainstate_path, ibd_chainstate_path);
7503 } catch (const fs::filesystem_error &e) {
7504 rename_failed_abort(snapshot_chainstate_path, ibd_chainstate_path, e);
7505 throw;
7506 }
7507
7508 if (!DeleteCoinsDBFromDisk(tmp_old, /*is_snapshot=*/false)) {
7509 // No need to FatalError because once the unneeded bg chainstate data is
7510 // moved, it will not interfere with subsequent initialization.
7511 LogPrintf("Deletion of %s failed. Please remove it manually, as the "
7512 "directory is now unnecessary.\n",
7513 fs::PathToString(tmp_old));
7514 } else {
7515 LogPrintf("[snapshot] deleted background chainstate directory (%s)\n",
7516 fs::PathToString(ibd_chainstate_path));
7517 }
7518 return true;
7519}
7520
7521Chainstate &ChainstateManager::GetChainstateForIndexing() {
7522 // We can't always return `m_ibd_chainstate` because after background
7523 // validation has completed,
7524 // `m_snapshot_chainstate == m_active_chainstate`, but it can be indexed.
7525 return (this->GetAll().size() > 1) ? *m_ibd_chainstate
7526 : *m_active_chainstate;
7527}
7528
7529std::pair<int, int>
7530ChainstateManager::GetPruneRange(const Chainstate &chainstate,
7531 int last_height_can_prune) {
7532 if (chainstate.m_chain.Height() <= 0) {
7533 return {0, 0};
7534 }
7535 int prune_start{0};
7536
7537 if (this->GetAll().size() > 1 &&
7538 m_snapshot_chainstate.get() == &chainstate) {
7539 // Leave the blocks in the background IBD chain alone if we're pruning
7540 // the snapshot chain.
7541 prune_start = *Assert(GetSnapshotBaseHeight()) + 1;
7542 }
7543
7544 int max_prune = std::max<int>(0, chainstate.m_chain.Height() -
7545 static_cast<int>(MIN_BLOCKS_TO_KEEP));
7546
7547 // last block to prune is the lesser of (caller-specified height,
7548 // MIN_BLOCKS_TO_KEEP from the tip)
7549 //
7550 // While you might be tempted to prune the background chainstate more
7551 // aggressively (i.e. fewer MIN_BLOCKS_TO_KEEP), this won't work with index
7552 // building - specifically blockfilterindex requires undo data, and if
7553 // we don't maintain this trailing window, we hit indexing failures.
7554 int prune_end = std::min(last_height_can_prune, max_prune);
7555
7556 return {prune_start, prune_end};
7557}
bool IsDAAEnabled(const Consensus::Params &params, int nHeight)
Definition: activation.cpp:24
bool IsUAHFenabled(const Consensus::Params &params, int nHeight)
Definition: activation.cpp:11
static bool IsPhononEnabled(const Consensus::Params &params, int32_t nHeight)
Definition: activation.cpp:65
static bool IsGravitonEnabled(const Consensus::Params &params, int32_t nHeight)
Definition: activation.cpp:51
bool IsMagneticAnomalyEnabled(const Consensus::Params &params, int32_t nHeight)
Check if Nov 15, 2018 HF has activated using block height.
Definition: activation.cpp:37
bool MoneyRange(const Amount nValue)
Definition: amount.h:171
static constexpr Amount SATOSHI
Definition: amount.h:148
static constexpr Amount COIN
Definition: amount.h:149
arith_uint256 UintToArith256(const uint256 &a)
int flags
Definition: bitcoin-tx.cpp:542
@ CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
@ TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
@ SCRIPTS
Scripts & signatures ok.
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:89
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:112
bool AreOnTheSameFork(const CBlockIndex *pa, const CBlockIndex *pb)
Check if two block index are on the same fork.
Definition: chain.cpp:136
#define Assert(val)
Identity function.
Definition: check.h:84
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:430
std::string ToString() const
Definition: hash_type.h:28
uint64_t getExcessiveBlockSize() const
Definition: validation.h:158
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:143
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:150
BlockValidationOptions(const Config &config)
Definition: validation.cpp:123
bool shouldValidatePoW() const
Definition: validation.h:156
bool shouldValidateMerkleRoot() const
Definition: validation.h:157
Wrapper around an AutoFile& that implements a ring buffer to deserialize from.
Definition: streams.h:502
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
NodeSeconds Time() const
Definition: block.h:53
uint32_t nBits
Definition: block.h:30
BlockHash hashPrevBlock
Definition: block.h:27
int64_t GetBlockTime() const
Definition: block.h:57
int32_t nVersion
Definition: block.h:26
uint256 hashMerkleRoot
Definition: block.h:28
Definition: block.h:60
bool m_checked_merkle_root
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:63
bool fChecked
Definition: block.h:67
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
bool IsValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const EXCLUSIVE_LOCKS_REQUIRED(
Check whether this block index entry is valid up to the passed validity level.
Definition: blockindex.h:191
std::string ToString() const
Definition: blockindex.cpp:30
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
int64_t GetHeaderReceivedTime() const
Definition: blockindex.h:164
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:29
int64_t GetChainTxCount() const
Get the number of transaction in the chain so far.
Definition: blockindex.h:138
bool HaveNumChainTxs() const
Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot ...
Definition: blockindex.h:154
uint32_t nTime
Definition: blockindex.h:76
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: blockindex.h:82
int64_t GetReceivedTimeDiff() const
Definition: blockindex.h:166
int64_t GetBlockTime() const
Definition: blockindex.h:160
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:107
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: blockindex.h:35
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:55
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: blockindex.h:199
int32_t nVersion
block header
Definition: blockindex.h:74
int64_t nTimeReceived
(memory only) block header metadata
Definition: blockindex.h:85
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
BlockHash GetBlockHash() const
Definition: blockindex.h:130
unsigned int nSize
Size of this block.
Definition: blockindex.h:60
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: blockindex.h:68
Undo information for a CBlock.
Definition: undo.h:72
std::vector< CTxUndo > vtxundo
Definition: undo.h:75
An in-memory indexed chain of blocks.
Definition: chain.h:138
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:154
void SetTip(CBlockIndex &block)
Set/initialize a chain with a given tip.
Definition: chain.cpp:8
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:147
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:178
int Height() const
Return the maximal height in the chain.
Definition: chain.h:190
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:49
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:170
CBlockLocator GetLocator() const
Return a CBlockLocator that refers to the tip of this chain.
Definition: chain.cpp:45
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
const CBlock & GenesisBlock() const
Definition: chainparams.h:112
std::vector< int > GetAvailableSnapshotHeights() const
const CMessageHeader::MessageMagic & DiskMagic() const
Definition: chainparams.h:99
const ChainTxData & TxData() const
Definition: chainparams.h:158
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:98
std::optional< AssumeutxoData > AssumeutxoForHeight(int height) const
Definition: chainparams.h:147
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:145
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:216
std::optional< R > Complete()
Definition: checkqueue.h:233
void Add(std::vector< T > &&vChecks)
Definition: checkqueue.h:242
The verifications are represented by a type T, which must provide an operator(), returning an std::op...
Definition: checkqueue.h:32
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:46
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:363
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:99
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:213
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:171
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:323
void SetBestBlock(const BlockHash &hashBlock)
Definition: coins.cpp:220
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:336
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:90
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:208
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:297
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:68
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:309
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:145
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:203
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:195
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:49
std::optional< fs::path > StoragePath()
Definition: txdb.h:75
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Dynamically alter the underlying leveldb cache size.
Definition: txdb.cpp:88
Abstract view on the open txout dataset.
Definition: coins.h:305
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:12
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:647
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
void TransactionAddedToMempool(const CTransactionRef &, std::shared_ptr< const std::vector< Coin > >, uint64_t mempool_sequence)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void BlockConnected(ChainstateRole, const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void BlockChecked(const CBlock &, const BlockValidationState &)
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void ChainStateFlushed(ChainstateRole, const CBlockLocator &)
void BlockFinalized(const CBlockIndex *pindex)
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:36
void insert(Span< const uint8_t > vKey)
Definition: bloom.cpp:215
bool contains(Span< const uint8_t > vKey) const
Definition: bloom.cpp:249
CSHA256 & Write(const uint8_t *data, size_t len)
Definition: sha256.cpp:819
Closure representing one script verification.
Definition: validation.h:565
SignatureCache * m_signature_cache
Definition: validation.h:574
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:598
uint32_t nFlags
Definition: validation.h:570
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:575
ScriptExecutionMetrics metrics
Definition: validation.h:572
CTxOut m_tx_out
Definition: validation.h:567
bool cacheStore
Definition: validation.h:571
std::optional< std::pair< ScriptError, std::string > > operator()()
PrecomputedTransactionData txdata
Definition: validation.h:573
const CTransaction * ptxTo
Definition: validation.h:568
unsigned int nIn
Definition: validation.h:569
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:576
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: mempool_entry.h:65
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:317
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:145
const int64_t m_max_size_bytes
Definition: txmempool.h:354
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:814
CTransactionRef get(const TxId &txid) const
Definition: txmempool.cpp:676
void clear(bool include_finalized_txs=false)
Definition: txmempool.cpp:379
void SetLoadTried(bool load_tried)
Set whether or not we've made an attempt to load the mempool (regardless of whether the attempt was s...
Definition: txmempool.cpp:1026
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:61
std::vector< Coin > vprevout
Definition: undo.h:64
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:656
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:733
bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Checks if a block is finalized by avalanche voting.
const std::optional< BlockHash > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition: validation.h:840
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
Definition: validation.h:825
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Find the best known block, and make it the tip of the block chain.
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:739
bool ConnectTip(BlockValidationState &state, BlockPolicyValidationState &blockPolicyState, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, DisconnectedBlockTransactions &disconnectpool, const avalanche::Processor *const avalanche=nullptr, ChainstateRole chainstate_role=ChainstateRole::NORMAL) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f, C fChild, AC fAncestorWasChanged) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:832
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:886
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(NodeClock::time_poin m_next_write)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:1125
CTxMemPool * GetMempool()
Definition: validation.h:872
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:892
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:859
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:889
void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Set invalidity status to all descendants of a block.
Definition: validation.h:1009
void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< BlockHash > from_snapshot_blockhash=std::nullopt)
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, const avalanche::Processor *const avalanche=nullptr, ChainstateRole=ChainstateRole::NORMAL) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Try to make some progress towards making pindexMostWork the active block.
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:763
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:743
void LoadMempool(const fs::path &load_path, fsbridge::FopenFn mockable_fopen_function=fsbridge::fopen)
Load the persisted mempool from disk.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:866
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex, bool invalidate) EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Mark a block as invalid.
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:795
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:747
const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The base of the snapshot this chainstate was created from.
Definition: validation.h:847
CRollingBloomFilter m_filterParkingPoliciesApplied
Filter to prevent parking a block due to block policies more than once.
Definition: validation.h:778
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, BlockValidationOptions options, Amount *blockFees=nullptr, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
Definition: validation.h:952
CBlockIndex const * m_best_fork_tip
Definition: validation.h:781
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool AvalancheFinalizeBlock(CBlockIndex *pindex, avalanche::Processor &avalanche) EXCLUSIVE_LOCKS_REQUIRED(voi ClearAvalancheFinalizedBlock)() EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
Mark a block as finalized by avalanche.
Definition: validation.h:995
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Resize the CoinsViews caches dynamically and flush state to disk.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:790
ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Return the current role of the chainstate.
CBlockIndex const * m_best_fork_base
Definition: validation.h:782
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main
void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block.
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Mark a block as precious and reorganize.
void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
Definition: validation.cpp:128
CBlockIndex * FindMostWorkChain(std::vector< const CBlockIndex * > &blocksToReconcile, bool fAutoUnpark) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
Park a block.
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Dictates whether we need to flush the cache to disk or not.
Definition: validation.h:1070
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1436
ValidationCache m_validation_cache
Definition: validation.h:1328
std::atomic< int32_t > nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Definition: validation.h:1344
bool DetectSnapshotChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &ActivateExistingSnapshot(BlockHash base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(std::pair< int, int > GetPruneRange(const Chainstate &chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(std::optional< int > GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(boo DumpRecentHeadersTime)(const fs::path &filePath) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process...
Definition: validation.h:1687
const Config & GetConfig() const
Definition: validation.h:1276
size_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:1388
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
kernel::Notifications & GetNotifications() const
Definition: validation.h:1293
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
bool ShouldCheckBlockIndex() const
Definition: validation.h:1284
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
bool LoadRecentHeadersTime(const fs::path &filePath) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Load the recent block headers reception time from a file.
std::optional< BlockHash > SnapshotBlockhash() const
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1474
bool IsUsable(const Chainstate *const pchainstate) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
Definition: validation.h:1257
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1443
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1450
size_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:1392
std::atomic< bool > m_cached_finished_ibd
Whether initial block download has ended and IsInitialBlockDownload should return false from now on.
Definition: validation.h:1337
bool PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1321
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1440
bool IsSnapshotActive() const
int StopAtHeight() const
Definition: validation.h:1296
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Sufficiently validate a block for disk storage (and store on disk).
std::function< void()> snapshot_download_completed
Function to restart active indexes; set dynamically to avoid a circular dependency on base/index....
Definition: validation.h:1274
const CChainParams & GetParams() const
Definition: validation.h:1278
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
const Consensus::Params & GetConsensus() const
Definition: validation.h:1281
ChainstateManager(const util::SignalInterrupt &interrupt, Options options, node::BlockManager::Options blockman_options)
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1287
void CheckBlockIndex()
Make various assertions about the state of the block index.
const CBlockIndex * GetAvalancheFinalizedTip() const
util::Result< CBlockIndex * > ActivateSnapshot(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
const Options m_options
Definition: validation.h:1322
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1437
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void ReportHeadersPresync(const arith_uint256 &work, int64_t height, int64_t timestamp)
Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:1349
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1290
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1402
std::set< CBlockIndex * > m_failed_blocks
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to conn...
Definition: validation.h:1378
void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< BlockHash, FlatFilePos > *blocks_with_unknown_parent=nullptr, avalanche::Processor *const avalanche=nullptr)
Import blocks from an external file.
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:1347
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1326
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:388
bool consume_and_check(int consumed)
Definition: validation.h:395
A UTXO entry.
Definition: coins.h:29
uint32_t GetHeight() const
Definition: coins.h:46
bool IsCoinBase() const
Definition: coins.h:47
CTxOut & GetTxOut()
Definition: coins.h:50
bool IsSpent() const
Definition: coins.h:48
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Definition: config.h:19
virtual const CChainParams & GetChainParams() const =0
std::pair< uint32_t, size_t > setup_bytes(size_t bytes)
setup_bytes is a convenience function which accounts for internal memory usage when deciding how many...
Definition: cuckoocache.h:386
bool get(Element &e, const bool erase) const
get is almost identical to contains(), with the difference that it obtains the found element (for Ele...
Definition: cuckoocache.h:523
void insert(Element e, bool replace=false)
insert loops at most depth_limit times trying to insert a hash at various locations in the table via ...
Definition: cuckoocache.h:421
void updateMempoolForReorg(Chainstate &active_chainstate, bool fAddToMempool, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
void addForBlock(const std::vector< CTransactionRef > &vtx, CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
void importMempool(CTxMemPool &pool) EXCLUSIVE_LOCKS_REQUIRED(pool.cs)
Fast randomness source.
Definition: random.h:411
Different type to mark Mutex at global scope.
Definition: sync.h:144
static RCUPtr acquire(T *&ptrIn)
Acquire ownership of some pointer.
Definition: rcu.h:103
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range) noexcept
Return the time point advanced by a uniform random duration.
Definition: random.h:339
The script cache is a map using a key/value element, that caches the success of executing a specific ...
Definition: scriptcache.h:26
static TxSigCheckLimiter getDisabled()
Definition: validation.h:416
Convenience class for initializing and passing the script execution cache and signature cache.
Definition: validation.h:429
CuckooCache::cache< ScriptCacheElement, ScriptCacheHasher > m_script_execution_cache
Definition: validation.h:437
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
Definition: validation.h:447
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
Definition: validation.h:433
SignatureCache m_signature_cache
Definition: validation.h:438
bool IsValid() const
Definition: validation.h:119
std::string GetRejectReason() const
Definition: validation.h:123
std::string GetDebugMessage() const
Definition: validation.h:124
bool Error(const std::string &reject_reason)
Definition: validation.h:112
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:101
bool IsError() const
Definition: validation.h:121
Result GetResult() const
Definition: validation.h:122
std::string ToString() const
Definition: validation.h:125
bool IsInvalid() const
Definition: validation.h:120
256-bit unsigned big integer.
uint8_t * begin()
Definition: uint256.h:85
std::string ToString() const
Definition: uint256.h:80
bool IsNull() const
Definition: uint256.h:32
double getdouble() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
A base class defining functions for notifying about certain kernel events.
virtual void headerTip(SynchronizationState state, int64_t height, int64_t timestamp, bool presync)
virtual void fatalError(const std::string &debug_message, const bilingual_str &user_message={})
The fatal error notification is sent to notify the user when an error occurs in kernel code that can'...
virtual void warning(const std::string &warning)
virtual void progress(const bilingual_str &title, int progress_percent, bool resume_possible)
virtual void blockTip(SynchronizationState state, CBlockIndex &index)
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:116
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:252
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:197
bool CheckBlockDataAvailability(const CBlockIndex &upper_block LIFETIMEBOUND, const CBlockIndex &lower_block LIFETIMEBOUND) EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetFirstBlock(const CBlockIndex &upper_block LIFETIMEBOUND, std::function< bool(BlockStatus)> status_test, const CBlockIndex *lower_block=nullptr) const EXCLUSIVE_LOCKS_REQUIRED(boo m_have_pruned)
Check if all blocks in the [upper_block, lower_block] range have data available.
Definition: blockstorage.h:412
bool FlushChainstateBlockFile(int tip_height)
void FindFilesToPrune(std::set< int > &setFilesToPrune, int last_prune, const Chainstate &chain, ChainstateManager &chainman)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
void UpdateBlockInfo(const CBlock &block, unsigned int nHeight, const FlatFilePos &pos)
Update blockfile info while processing a block during reindex.
bool ReadBlockUndo(CBlockUndo &blockundo, const CBlockIndex &index) const
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool LoadingBlocks() const
Definition: blockstorage.h:359
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB(const std::optional< BlockHash > &snapshot_blockhash) EXCLUSIVE_LOCKS_REQUIRED(void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(CBlockIndex * AddToBlockIndex(const CBlockHeader &block, CBlockIndex *&best_header) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove any pruned block & undo files that are still on disk.
Definition: blockstorage.h:303
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
Definition: blockstorage.h:235
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
Definition: blockstorage.h:230
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:350
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, const Chainstate &chain, ChainstateManager &chainman)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
bool WriteBlockUndo(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos WriteBlock(const CBlock &block, int nHeight)
Store block on disk and update block file statistics.
Definition: blockstorage.h:336
bool ReadBlock(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
std::optional< int > m_snapshot_height
The height of the base block of an assumeutxo snapshot, if one is in use.
Definition: blockstorage.h:278
std::vector< CBlockIndex * > GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Definition: blockstorage.h:280
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:30
uint64_t m_coins_count
The number of coins in the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:41
BlockHash m_base_blockhash
The hash of the block that reflects the tip of the chain for the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:37
256-bit opaque blob.
Definition: uint256.h:129
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:410
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:155
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ BLOCK_HEADER_LOW_WORK
the block header may be on a too-little-work chain
@ BLOCK_INVALID_HEADER
invalid proof of work or time too old
@ BLOCK_CACHED_INVALID
this block was cached as being invalid and we didn't store the reason why
@ BLOCK_CONSENSUS
invalid by consensus rules (excluding any below reasons)
@ BLOCK_MISSING_PREV
We don't have the previous block the checked one is built on.
@ BLOCK_INVALID_PREV
A block this one builds on is invalid.
@ BLOCK_MUTATED
the block's data didn't match the data committed to by the PoW
@ BLOCK_TIME_FUTURE
block timestamp was > 2 hours in the future (or our clock is bad)
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_CHILD_BEFORE_PARENT
This tx outputs are already spent in the mempool.
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/etc limits
@ TX_PACKAGE_RECONSIDERABLE
fails some policy, but might be acceptable if submitted in a (different) package
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_DUPLICATE
Tx already in mempool or in the chain.
@ TX_INPUTS_NOT_STANDARD
inputs failed policy rules
@ TX_CONFLICT
Tx conflicts with a finalized tx, i.e.
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_AVALANCHE_RECONSIDERABLE
fails some policy, but might be reconsidered by avalanche voting
@ TX_NO_MEMPOOL
this node does not have a mempool so can't validate the transaction
@ TX_CONSENSUS
invalid by consensus rules
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:38
static const uint64_t MAX_TX_SIZE
The maximum allowed size for a transaction, in bytes.
Definition: consensus.h:14
uint64_t GetMaxBlockSigChecksCount(uint64_t maxBlockSize)
Compute the maximum number of sigchecks that can be contained in a block given the MAXIMUM block size...
Definition: consensus.h:47
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
DisconnectResult
volatile double sum
Definition: examples.cpp:10
bool RenameOver(fs::path src, fs::path dest)
Definition: fs_helpers.cpp:273
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:112
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:126
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, uint32_t flags, const BaseSignatureChecker &checker, ScriptExecutionMetrics &metricsOut, ScriptError *serror)
Execute an unlocking and locking script together.
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:14
#define LogPrintLevel(category, level,...)
Definition: logging.h:437
#define LogPrintLevel_(category, level, should_ratelimit,...)
Definition: logging.h:407
#define LogWarning(...)
Definition: logging.h:416
#define LogPrint(category,...)
Definition: logging.h:452
#define LogInfo(...)
Definition: logging.h:413
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
unsigned int nHeight
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Compute the Merkle root of the transactions in a block.
Definition: merkle.cpp:69
@ AVALANCHE
Definition: logging.h:91
@ REINDEX
Definition: logging.h:80
@ VALIDATION
Definition: logging.h:90
@ PRUNE
Definition: logging.h:83
@ MEMPOOL
Definition: logging.h:71
@ BENCH
Definition: logging.h:73
bool CheckBlock(const CCheckpointData &data, int nHeight, const BlockHash &hash)
Returns true if block passes checkpoint checks.
Definition: checkpoints.cpp:11
@ DEPLOYMENT_DERSIG
Definition: params.h:23
@ DEPLOYMENT_P2SH
Definition: params.h:20
@ DEPLOYMENT_CSV
Definition: params.h:24
@ DEPLOYMENT_HEIGHTINCB
Definition: params.h:21
@ DEPLOYMENT_CLTV
Definition: params.h:22
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, Amount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts).
Definition: tx_verify.cpp:194
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:142
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: fs.h:203
Definition: common.cpp:21
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
Definition: coinstats.cpp:95
CoinStatsHashType
Definition: coinstats.h:24
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, FopenFn mockable_fopen_function)
const fs::path SNAPSHOT_BLOCKHASH_FILENAME
The file in the snapshot chainstate dir which stores the base blockhash.
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate)
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:74
std::optional< BlockHash > ReadSnapshotBaseBlockhash(const fs::path &chaindir)
bool WriteSnapshotBaseBlockhash(Chainstate &snapshot_chainstate) EXCLUSIVE_LOCKS_REQUIRED(std::optional< BlockHash > ReadSnapshotBaseBlockhash(const fs::path &chaindir) EXCLUSIVE_LOCKS_REQUIRED(constexpr std::string_view SNAPSHOT_CHAINSTATE_SUFFIX
Write out the blockhash of the snapshot base block that was used to construct this chainstate.
std::optional< fs::path > FindSnapshotChainstateDir(const fs::path &data_dir)
Return a path to the snapshot-based chainstate dir, if one exists.
std::atomic_bool fReindex
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: spanparsing.cpp:23
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:90
std::shared_ptr< Chain::Notifications > m_notifications
Definition: interfaces.cpp:475
bool IsChildWithParents(const Package &package)
Context-free check that a package is exactly one child and its parents; not all parents need to be pr...
Definition: packages.cpp:86
bool CheckPackage(const Package &txns, PackageValidationState &state)
Context-free package policy checks:
Definition: packages.cpp:14
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:40
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
@ PCKG_MEMPOOL_ERROR
Mempool logic error.
@ PCKG_TX
At least one tx is invalid.
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs, uint32_t flags)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:145
bool IsStandardTx(const CTransaction &tx, const std::optional< unsigned > &max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:66
static constexpr uint32_t STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:91
static constexpr uint32_t STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
Definition: policy.h:108
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:87
uint32_t GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const CChainParams &chainParams)
Definition: pow.cpp:21
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
uint256 GetRandHash() noexcept
========== CONVENIENCE FUNCTIONS FOR COMMONLY USED RANDOMNESS ==========
Definition: random.h:494
const char * prefix
Definition: rest.cpp:812
reverse_range< T > reverse_iterate(T &x)
std::string ScriptErrorString(const ScriptError serror)
ScriptError
Definition: script_error.h:11
@ SIGCHECKS_LIMIT_EXCEEDED
@ SCRIPT_VERIFY_P2SH
Definition: script_flags.h:16
@ SCRIPT_VERIFY_SIGPUSHONLY
Definition: script_flags.h:35
@ SCRIPT_VERIFY_LOW_S
Definition: script_flags.h:31
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
Definition: script_flags.h:68
@ SCRIPT_ENABLE_REPLAY_PROTECTION
Definition: script_flags.h:89
@ SCRIPT_ENABLE_SCHNORR_MULTISIG
Definition: script_flags.h:97
@ SCRIPT_VERIFY_STRICTENC
Definition: script_flags.h:22
@ SCRIPT_VERIFY_NULLFAIL
Definition: script_flags.h:81
@ SCRIPT_VERIFY_DERSIG
Definition: script_flags.h:26
@ SCRIPT_ENFORCE_SIGCHECKS
Definition: script_flags.h:106
@ SCRIPT_VERIFY_CLEANSTACK
Definition: script_flags.h:63
@ SCRIPT_VERIFY_NONE
Definition: script_flags.h:12
@ SCRIPT_VERIFY_MINIMALDATA
Definition: script_flags.h:43
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
Definition: script_flags.h:73
@ SCRIPT_ENABLE_SIGHASH_FORKID
Definition: script_flags.h:85
CAddrDb db
Definition: main.cpp:35
size_t GetSerializeSize(const T &t)
Definition: serialize.h:1262
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:469
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:16
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:63
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:108
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:48
AssumeutxoHash hash_serialized
The expected hash of the deserialized UTXO set.
Definition: chainparams.h:52
unsigned int nChainTx
Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex().
Definition: chainparams.h:60
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
bool isValid(enum BlockValidity nUpTo=BlockValidity::TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: blockstatus.h:99
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:108
std::vector< BlockHash > vHave
Definition: block.h:120
Holds various statistics on transactions within a chain.
Definition: chainparams.h:73
double dTxRate
Definition: chainparams.h:76
int64_t nTime
Definition: chainparams.h:74
int64_t nTxCount
Definition: chainparams.h:75
User-controlled performance and debug options.
Definition: txdb.h:40
Parameters that influence chain consensus.
Definition: params.h:34
BlockHash BIP34Hash
Definition: params.h:41
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:40
int nSubsidyHalvingInterval
Definition: params.h:36
int obolenskyActivationTime
Unix time used for MTP activation of 15 May 2026 12:00:00 UTC upgrade.
Definition: params.h:67
BlockHash hashGenesisBlock
Definition: params.h:35
int64_t nPowTargetSpacing
Definition: params.h:80
bool fPowAllowMinDifficultyBlocks
Definition: params.h:77
Application-specific storage settings.
Definition: dbwrapper.h:31
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:33
int nFile
Definition: flatfile.h:15
unsigned int nPos
Definition: flatfile.h:16
bool IsNull() const
Definition: flatfile.h:40
int64_t time
Definition: mempool_entry.h:27
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:212
const ResultType m_result_type
Result type.
Definition: validation.h:223
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:251
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition: validation.h:256
static MempoolAcceptResult Success(int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for success case.
Definition: validation.h:264
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:274
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:71
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:315
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:325
In future if many more values are added, it should be considered to expand the element size to 64 byt...
Definition: scriptcache.h:52
const char * what() const override
A TxId is the identifier of a transaction.
Definition: txid.h:14
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
const std::function< NodeClock::time_point()> adjusted_time_callback
std::optional< bool > check_block_index
std::chrono::seconds max_tip_age
If the tip is older than this, the node is considered to be in initial block download.
bool store_recent_headers_time
If set, store and load the last few block headers reception time to speed up RTT bootstraping.
std::optional< int64_t > replay_protection_activation_time
If set, this overwrites the timestamp at which replay protection activates.
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
#define NO_THREAD_SAFETY_ANALYSIS
Definition: threadsafety.h:58
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:105
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:109
#define LOG_TIME_MILLIS_WITH_CATEGORY(end_msg, log_category)
Definition: timer.h:97
#define LOG_TIME_MILLIS_WITH_CATEGORY_MSG_ONCE(end_msg, log_category)
Definition: timer.h:100
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
#define TRACE6(context, event, a, b, c, d, e, f)
Definition: trace.h:45
#define TRACE5(context, event, a, b, c, d, e)
Definition: trace.h:44
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
bool CheckRegularTransaction(const CTransaction &tx, TxValidationState &state)
Context-independent validity checks for coinbase and non-coinbase transactions.
Definition: tx_check.cpp:74
bool CheckCoinbase(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:55
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
Definition: tx_verify.cpp:72
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:176
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
Definition: tx_verify.cpp:187
bool ContextualCheckTransaction(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int nHeight, int64_t nMedianTimePast)
Context dependent validity checks for non coinbase transactions.
Definition: tx_verify.cpp:41
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > &prevHeights, const CBlockIndex &block)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: tx_verify.h:62
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coins to signify they are only in the memory pool(since 0....
Definition: txmempool.h:55
uint256 uint256S(const char *str)
uint256 from const char *.
Definition: uint256.h:143
#define expect(bit)
static bool DeleteCoinsDBFromDisk(const fs::path &db_path, bool is_snapshot) EXCLUSIVE_LOCKS_REQUIRED(
static bool NotifyHeaderTip(ChainstateManager &chainman) LOCKS_EXCLUDED(cs_main)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
static int64_t num_blocks_total
bool FatalError(Notifications &notifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage)
GlobalMutex g_best_block_mutex
Definition: validation.cpp:119
static SteadyClock::duration time_connect_total
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:120
std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Calculate LockPoints required to check if transaction will be BIP68 final in the next block to be cre...
Definition: validation.cpp:186
static bool pool cs
Definition: validation.cpp:251
return CheckInputScripts(tx, state, view, flags, true, true, txdata, validation_cache, nSigChecksOut)
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
DisconnectResult ApplyBlockUndo(CBlockUndo &&blockUndo, const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo a block from the block and the undoblock data.
static constexpr size_t WARN_FLUSH_COINS_SIZE
Size threshold for warning about slow UTXO set flush to disk.
Definition: validation.cpp:92
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept, unsigned int heightOverride)
Try to add a transaction to the mempool.
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Return true if the provided block header is valid.
static SynchronizationState GetSynchronizationState(bool init)
static bool ContextualCheckBlock(const CBlock &block, BlockValidationState &state, const ChainstateManager &chainman, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:210
static SteadyClock::duration time_post_connect
static SteadyClock::duration time_chainstate
static uint32_t GetNextBlockScriptFlags(const CBlockIndex *pindex, const ChainstateManager &chainman)
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:121
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
static SteadyClock::duration time_forks
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
static ChainstateManager::Options && Flatten(ChainstateManager::Options &&opts)
Apply default chain params to nullopt members.
static constexpr auto DATABASE_WRITE_INTERVAL_MAX
Definition: validation.cpp:100
static SteadyClock::duration time_verify
static bool CheckMerkleRoot(const CBlock &block, BlockValidationState &state)
static SteadyClock::duration time_check
static constexpr int PRUNE_LOCK_BUFFER
The number of blocks to keep below the deepest prune lock.
Definition: validation.cpp:115
static SteadyClock::duration time_index
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main)
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
static SteadyClock::duration time_connect
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:101
DisconnectResult UndoCoinSpend(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions)
Check a block is completely valid from start to finish (only works on top of our current best block)
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static void FlushSnapshotToDisk(CCoinsViewCache &coins_cache, bool snapshot_loaded)
bool IsBlockMutated(const CBlock &block)
Check if a block has been mutated (with respect to its merkle root).
std::vector< Coin > GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view)
Get the coins spent by ptx from the coins_view.
static constexpr auto DATABASE_WRITE_INTERVAL_MIN
Time window to wait between writing blocks/block index and chainstate to disk.
Definition: validation.cpp:99
AssertLockHeld(pool.cs)
static SteadyClock::duration time_total
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, const uint32_t flags, PrecomputedTransactionData &txdata, ValidationCache &validation_cache, int &nSigChecksOut, CCoinsViewCache &coins_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Checks to avoid mempool polluting consensus critical paths since cached signature and script validity...
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, ChainstateManager &chainman, const CBlockIndex *pindexPrev, NodeClock::time_point now, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) EXCLUSIVE_LOCKS_REQUIRED(
Context-dependent validity checks.
static SteadyClock::duration time_flush
static SteadyClock::duration time_read_from_disk_total
static void SnapshotUTXOHashBreakpoint(const util::SignalInterrupt &interrupt)
static constexpr uint64_t HEADERS_TIME_VERSION
Definition: validation.cpp:117
static fs::path GetSnapshotCoinsDBPath(Chainstate &cs) EXCLUSIVE_LOCKS_REQUIRED(
static bool IsReplayProtectionEnabled(const Consensus::Params &params, const CBlockIndex *pindexPrev, const std::optional< int64_t > activation_time)
Definition: validation.cpp:230
static void UpdateTipLog(const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const CChainParams &params, const std::string &func_name, const std::string &prefix) EXCLUSIVE_LOCKS_REQUIRED(
assert(!tx.IsCoinBase())
#define MIN_TRANSACTION_SIZE
Definition: validation.h:86
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:99
SnapshotCompletionResult
Definition: validation.h:1137
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:118
VerifyDBResult
Definition: validation.h:642
CoinsCacheSizeState
Definition: validation.h:711
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
FlushStateMode
Definition: validation.h:672
CMainSignals & GetMainSignals()
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:36
void SetfLargeWorkForkFound(bool flag)
Definition: warnings.cpp:26
bool GetfLargeWorkForkFound()
Definition: warnings.cpp:31