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