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