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