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