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