Bitcoin Core 22.99.0
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2020 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <validation.h>
7
8#include <arith_uint256.h>
9#include <chain.h>
10#include <chainparams.h>
11#include <checkqueue.h>
12#include <consensus/amount.h>
13#include <consensus/consensus.h>
14#include <consensus/merkle.h>
15#include <consensus/tx_check.h>
16#include <consensus/tx_verify.h>
18#include <cuckoocache.h>
19#include <deploymentstatus.h>
20#include <flatfile.h>
21#include <hash.h>
23#include <logging.h>
24#include <logging/timer.h>
25#include <node/blockstorage.h>
26#include <node/coinstats.h>
27#include <node/ui_interface.h>
28#include <node/utxo_snapshot.h>
29#include <policy/policy.h>
30#include <policy/rbf.h>
31#include <policy/settings.h>
32#include <pow.h>
33#include <primitives/block.h>
35#include <random.h>
36#include <reverse_iterator.h>
37#include <script/script.h>
38#include <script/sigcache.h>
39#include <shutdown.h>
40#include <signet.h>
41#include <timedata.h>
42#include <tinyformat.h>
43#include <txdb.h>
44#include <txmempool.h>
45#include <uint256.h>
46#include <undo.h>
47#include <util/check.h> // For NDEBUG compile time check
48#include <util/hasher.h>
49#include <util/moneystr.h>
50#include <util/rbf.h>
51#include <util/strencodings.h>
52#include <util/system.h>
53#include <util/trace.h>
54#include <util/translation.h>
55#include <validationinterface.h>
56#include <warnings.h>
57
58#include <numeric>
59#include <optional>
60#include <string>
61
62#include <boost/algorithm/string/replace.hpp>
63
64#define MICRO 0.000001
65#define MILLI 0.001
66
72static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
74static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
76static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1};
78static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24};
80static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3};
81const std::vector<std::string> CHECKLEVEL_DOC {
82 "level 0 reads the blocks from disk",
83 "level 1 verifies block validity",
84 "level 2 verifies undo data",
85 "level 3 checks disconnection of tip blocks",
86 "level 4 tries to reconnect the blocks",
87 "each level includes the checks of the previous levels",
88};
89
91 // First sort by most total work, ...
92 if (pa->nChainWork > pb->nChainWork) return false;
93 if (pa->nChainWork < pb->nChainWork) return true;
94
95 // ... then by earliest time received, ...
96 if (pa->nSequenceId < pb->nSequenceId) return false;
97 if (pa->nSequenceId > pb->nSequenceId) return true;
98
99 // Use pointer address as tie breaker (should only happen with blocks
100 // loaded from disk, as those all have id 0).
101 if (pa < pb) return false;
102 if (pa > pb) return true;
103
104 // Identical blocks.
105 return false;
106}
107
119
122std::condition_variable g_best_block_cv;
126bool fCheckBlockIndex = false;
129
132
134
135// Internal stuff
136namespace {
137 CBlockIndex* pindexBestInvalid = nullptr;
138} // namespace
139
140// Internal stuff from blockstorage ...
142extern std::vector<CBlockFileInfo> vinfoBlockFile;
143extern int nLastBlockFile;
144extern bool fCheckForPruning;
145extern std::set<CBlockIndex*> setDirtyBlockIndex;
146extern std::set<int> setDirtyFileInfo;
147void FlushBlockFile(bool fFinalize = false, bool finalize_undo = false);
148// ... TODO move fully to blockstorage
149
151{
153 BlockMap::const_iterator it = m_block_index.find(hash);
154 return it == m_block_index.end() ? nullptr : it->second;
155}
156
158{
160
161 // Find the latest block common to locator and chain - we expect that
162 // locator.vHave is sorted descending by height.
163 for (const uint256& hash : locator.vHave) {
164 CBlockIndex* pindex = LookupBlockIndex(hash);
165 if (pindex) {
166 if (chain.Contains(pindex))
167 return pindex;
168 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
169 return chain.Tip();
170 }
171 }
172 }
173 return chain.Genesis();
174}
175
177 const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
178 bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
179 std::vector<CScriptCheck>* pvChecks = nullptr)
181
182bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, int flags)
183{
185 assert(active_chain_tip); // TODO: Make active_chain_tip a reference
186
187 // By convention a negative value for flags indicates that the
188 // current network-enforced consensus rules should be used. In
189 // a future soft-fork scenario that would mean checking which
190 // rules would be enforced for the next block and setting the
191 // appropriate flags. At the present time no soft-forks are
192 // scheduled, so no flags are set.
193 flags = std::max(flags, 0);
194
195 // CheckFinalTx() uses active_chain_tip.Height()+1 to evaluate
196 // nLockTime because when IsFinalTx() is called within
197 // AcceptBlock(), the height of the block *being*
198 // evaluated is what is used. Thus if we want to know if a
199 // transaction can be part of the *next* block, we need to call
200 // IsFinalTx() with one more than active_chain_tip.Height().
201 const int nBlockHeight = active_chain_tip->nHeight + 1;
202
203 // BIP113 requires that time-locked transactions have nLockTime set to
204 // less than the median time of the previous block they're contained in.
205 // When the next block is created its previous block will be the current
206 // chain tip, so we use that to calculate the median time passed to
207 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
208 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
209 ? active_chain_tip->GetMedianTimePast()
210 : GetAdjustedTime();
211
212 return IsFinalTx(tx, nBlockHeight, nBlockTime);
213}
214
215bool TestLockPointValidity(CChain& active_chain, const LockPoints* lp)
216{
218 assert(lp);
219 // If there are relative lock times then the maxInputBlock will be set
220 // If there are no relative lock times, the LockPoints don't depend on the chain
221 if (lp->maxInputBlock) {
222 // Check whether active_chain is an extension of the block at which the LockPoints
223 // calculation was valid. If not LockPoints are no longer valid
224 if (!active_chain.Contains(lp->maxInputBlock)) {
225 return false;
226 }
227 }
228
229 // LockPoints still valid
230 return true;
231}
232
234 const CCoinsView& coins_view,
235 const CTransaction& tx,
236 int flags,
237 LockPoints* lp,
238 bool useExistingLockPoints)
239{
240 assert(tip != nullptr);
241
242 CBlockIndex index;
243 index.pprev = tip;
244 // CheckSequenceLocks() uses active_chainstate.m_chain.Height()+1 to evaluate
245 // height based locks because when SequenceLocks() is called within
246 // ConnectBlock(), the height of the block *being*
247 // evaluated is what is used.
248 // Thus if we want to know if a transaction can be part of the
249 // *next* block, we need to use one more than active_chainstate.m_chain.Height()
250 index.nHeight = tip->nHeight + 1;
251
252 std::pair<int, int64_t> lockPair;
253 if (useExistingLockPoints) {
254 assert(lp);
255 lockPair.first = lp->height;
256 lockPair.second = lp->time;
257 }
258 else {
259 std::vector<int> prevheights;
260 prevheights.resize(tx.vin.size());
261 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
262 const CTxIn& txin = tx.vin[txinIndex];
263 Coin coin;
264 if (!coins_view.GetCoin(txin.prevout, coin)) {
265 return error("%s: Missing input", __func__);
266 }
267 if (coin.nHeight == MEMPOOL_HEIGHT) {
268 // Assume all mempool transaction confirm in the next block
269 prevheights[txinIndex] = tip->nHeight + 1;
270 } else {
271 prevheights[txinIndex] = coin.nHeight;
272 }
273 }
274 lockPair = CalculateSequenceLocks(tx, flags, prevheights, index);
275 if (lp) {
276 lp->height = lockPair.first;
277 lp->time = lockPair.second;
278 // Also store the hash of the block with the highest height of
279 // all the blocks which have sequence locked prevouts.
280 // This hash needs to still be on the chain
281 // for these LockPoint calculations to be valid
282 // Note: It is impossible to correctly calculate a maxInputBlock
283 // if any of the sequence locked inputs depend on unconfirmed txs,
284 // except in the special case where the relative lock time/height
285 // is 0, which is equivalent to no sequence lock. Since we assume
286 // input height of tip+1 for mempool txs and test the resulting
287 // lockPair from CalculateSequenceLocks against tip+1. We know
288 // EvaluateSequenceLocks will fail if there was a non-zero sequence
289 // lock on a mempool input, so we can use the return value of
290 // CheckSequenceLocks to indicate the LockPoints validity
291 int maxInputHeight = 0;
292 for (const int height : prevheights) {
293 // Can ignore mempool inputs since we'll fail if they had non-zero locks
294 if (height != tip->nHeight+1) {
295 maxInputHeight = std::max(maxInputHeight, height);
296 }
297 }
298 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
299 }
300 }
301 return EvaluateSequenceLocks(index, lockPair);
302}
303
304// Returns the script flags which should be checked for a given block
305static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
306
307static void LimitMempoolSize(CTxMemPool& pool, CCoinsViewCache& coins_cache, size_t limit, std::chrono::seconds age)
309{
310 int expired = pool.Expire(GetTime<std::chrono::seconds>() - age);
311 if (expired != 0) {
312 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
313 }
314
315 std::vector<COutPoint> vNoSpendsRemaining;
316 pool.TrimToSize(limit, &vNoSpendsRemaining);
317 for (const COutPoint& removed : vNoSpendsRemaining)
318 coins_cache.Uncache(removed);
319}
320
322{
324 if (active_chainstate.IsInitialBlockDownload())
325 return false;
326 if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
327 return false;
328 if (active_chainstate.m_chain.Height() < pindexBestHeader->nHeight - 1)
329 return false;
330 return true;
331}
332
334 DisconnectedBlockTransactions& disconnectpool,
335 bool fAddToMempool)
336{
337 if (!m_mempool) return;
338
341 std::vector<uint256> vHashUpdate;
342 // disconnectpool's insertion_order index sorts the entries from
343 // oldest to newest, but the oldest entry will be the last tx from the
344 // latest mined block that was disconnected.
345 // Iterate disconnectpool in reverse, so that we add transactions
346 // back to the mempool starting with the earliest transaction that had
347 // been previously seen in a block.
348 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
349 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
350 // ignore validation errors in resurrected transactions
351 if (!fAddToMempool || (*it)->IsCoinBase() ||
353 *this, *m_mempool, *it, true /* bypass_limits */).m_result_type !=
355 // If the transaction doesn't make it in to the mempool, remove any
356 // transactions that depend on it (which would now be orphans).
358 } else if (m_mempool->exists(GenTxid::Txid((*it)->GetHash()))) {
359 vHashUpdate.push_back((*it)->GetHash());
360 }
361 ++it;
362 }
363 disconnectpool.queuedTx.clear();
364 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
365 // no in-mempool children, which is generally not true when adding
366 // previously-confirmed transactions back to the mempool.
367 // UpdateTransactionsFromBlock finds descendants of any transactions in
368 // the disconnectpool that were added back and cleans up the mempool state.
370
371 // We also need to remove any now-immature transactions
373 // Re-limit mempool size, in case we added any transactions
375 *m_mempool,
376 this->CoinsTip(),
377 gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000,
378 std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
379}
380
387 const CCoinsViewCache& view, const CTxMemPool& pool,
388 unsigned int flags, PrecomputedTransactionData& txdata, CCoinsViewCache& coins_tip)
390{
393
395 for (const CTxIn& txin : tx.vin) {
396 const Coin& coin = view.AccessCoin(txin.prevout);
397
398 // This coin was checked in PreChecks and MemPoolAccept
399 // has been holding cs_main since then.
400 Assume(!coin.IsSpent());
401 if (coin.IsSpent()) return false;
402
403 // If the Coin is available, there are 2 possibilities:
404 // it is available in our current ChainstateActive UTXO set,
405 // or it's a UTXO provided by a transaction in our mempool.
406 // Ensure the scriptPubKeys in Coins from CoinsView are correct.
407 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
408 if (txFrom) {
409 assert(txFrom->GetHash() == txin.prevout.hash);
410 assert(txFrom->vout.size() > txin.prevout.n);
411 assert(txFrom->vout[txin.prevout.n] == coin.out);
412 } else {
413 const Coin& coinFromUTXOSet = coins_tip.AccessCoin(txin.prevout);
414 assert(!coinFromUTXOSet.IsSpent());
415 assert(coinFromUTXOSet.out == coin.out);
416 }
417 }
418
419 // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
420 return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata);
421}
422
423namespace {
424
425class MemPoolAccept
426{
427public:
428 explicit MemPoolAccept(CTxMemPool& mempool, CChainState& active_chainstate) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&active_chainstate.CoinsTip(), m_pool), m_active_chainstate(active_chainstate),
429 m_limit_ancestors(gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)),
430 m_limit_ancestor_size(gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000),
431 m_limit_descendants(gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)),
432 m_limit_descendant_size(gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {
433 }
434
435 // We put the arguments we're handed into a struct, so we can pass them
436 // around easier.
437 struct ATMPArgs {
438 const CChainParams& m_chainparams;
439 const int64_t m_accept_time;
440 const bool m_bypass_limits;
441 /*
442 * Return any outpoints which were not previously present in the coins
443 * cache, but were added as a result of validating the tx for mempool
444 * acceptance. This allows the caller to optionally remove the cache
445 * additions if the associated transaction ends up being rejected by
446 * the mempool.
447 */
448 std::vector<COutPoint>& m_coins_to_uncache;
449 const bool m_test_accept;
453 const bool m_allow_bip125_replacement{true};
454 };
455
456 // Single transaction acceptance
457 MempoolAcceptResult AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
458
464 PackageMempoolAcceptResult AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
465
466private:
467 // All the intermediate state that gets passed between the various levels
468 // of checking a given transaction.
469 struct Workspace {
470 explicit Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(ptx->GetHash()) {}
471 std::set<uint256> m_conflicts;
472 CTxMemPool::setEntries m_all_conflicting;
473 CTxMemPool::setEntries m_ancestors;
474 std::unique_ptr<CTxMemPoolEntry> m_entry;
475 std::list<CTransactionRef> m_replaced_transactions;
476
477 CAmount m_base_fees;
478 CAmount m_modified_fees;
480 CAmount m_conflicting_fees{0};
482 size_t m_conflicting_size{0};
483
484 const CTransactionRef& m_ptx;
485 const uint256& m_hash;
486 TxValidationState m_state;
487 };
488
489 // Run the policy checks on a given transaction, excluding any script checks.
490 // Looks up inputs, calculates feerate, considers replacement, evaluates
491 // package limits, etc. As this function can be invoked for "free" by a peer,
492 // only tests that are fast should be done here (to avoid CPU DoS).
493 bool PreChecks(ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
494
495 // Run the script checks using our policy flags. As this can be slow, we should
496 // only invoke this on transactions that have otherwise passed policy checks.
497 bool PolicyScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
498
499 // Re-run the script checks, using consensus flags, and try to cache the
500 // result in the scriptcache. This should be done after
501 // PolicyScriptChecks(). This requires that all inputs either be in our
502 // utxo set or in the mempool.
503 bool ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData &txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
504
505 // Try to add the transaction to the mempool, removing any conflicts first.
506 // Returns true if the transaction is in the mempool after any size
507 // limiting is performed, false otherwise.
508 bool Finalize(const ATMPArgs& args, Workspace& ws) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs);
509
510 // Compare a package's feerate against minimum allowed.
511 bool CheckFeeRate(size_t package_size, CAmount package_fee, TxValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_pool.cs)
512 {
513 CAmount mempoolRejectFee = m_pool.GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(package_size);
514 if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
515 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
516 }
517
518 if (package_fee < ::minRelayTxFee.GetFee(package_size)) {
519 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met", strprintf("%d < %d", package_fee, ::minRelayTxFee.GetFee(package_size)));
520 }
521 return true;
522 }
523
524private:
525 CTxMemPool& m_pool;
526 CCoinsViewCache m_view;
527 CCoinsViewMemPool m_viewmempool;
528 CCoinsView m_dummy;
529
530 CChainState& m_active_chainstate;
531
532 // The package limits in effect at the time of invocation.
533 const size_t m_limit_ancestors;
534 const size_t m_limit_ancestor_size;
535 // These may be modified while evaluating a transaction (eg to account for
536 // in-mempool conflicts; see below).
537 size_t m_limit_descendants;
538 size_t m_limit_descendant_size;
539};
540
541bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
542{
543 const CTransactionRef& ptx = ws.m_ptx;
544 const CTransaction& tx = *ws.m_ptx;
545 const uint256& hash = ws.m_hash;
546
547 // Copy/alias what we need out of args
548 const int64_t nAcceptTime = args.m_accept_time;
549 const bool bypass_limits = args.m_bypass_limits;
550 std::vector<COutPoint>& coins_to_uncache = args.m_coins_to_uncache;
551
552 // Alias what we need out of ws
553 TxValidationState& state = ws.m_state;
554 std::set<uint256>& setConflicts = ws.m_conflicts;
555 CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
556 CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
557 std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
558 CAmount& nModifiedFees = ws.m_modified_fees;
559 CAmount& nConflictingFees = ws.m_conflicting_fees;
560 size_t& nConflictingSize = ws.m_conflicting_size;
561
562 if (!CheckTransaction(tx, state)) {
563 return false; // state filled in by CheckTransaction
564 }
565
566 // Coinbase is only valid in a block, not as a loose transaction
567 if (tx.IsCoinBase())
568 return state.Invalid(TxValidationResult::TX_CONSENSUS, "coinbase");
569
570 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
571 std::string reason;
572 if (fRequireStandard && !IsStandardTx(tx, reason))
573 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, reason);
574
575 // Do not work on transactions that are too small.
576 // A transaction with 1 segwit input and 1 P2WPHK output has non-witness size of 82 bytes.
577 // Transactions smaller than this are not relayed to mitigate CVE-2017-12842 by not relaying
578 // 64-byte transactions.
580 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "tx-size-small");
581
582 // Only accept nLockTime-using transactions that can be mined in the next
583 // block; we don't want our mempool filled up with transactions that can't
584 // be mined yet.
585 if (!CheckFinalTx(m_active_chainstate.m_chain.Tip(), tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
586 return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-final");
587
588 if (m_pool.exists(GenTxid::Wtxid(tx.GetWitnessHash()))) {
589 // Exact transaction already exists in the mempool.
590 return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-in-mempool");
591 } else if (m_pool.exists(GenTxid::Txid(tx.GetHash()))) {
592 // Transaction with the same non-witness data but different witness (same txid, different
593 // wtxid) already exists in the mempool.
594 return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-same-nonwitness-data-in-mempool");
595 }
596
597 // Check for conflicts with in-memory transactions
598 for (const CTxIn &txin : tx.vin)
599 {
600 const CTransaction* ptxConflicting = m_pool.GetConflictTx(txin.prevout);
601 if (ptxConflicting) {
602 if (!args.m_allow_bip125_replacement) {
603 // Transaction conflicts with a mempool tx, but we're not allowing replacements.
604 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "bip125-replacement-disallowed");
605 }
606 if (!setConflicts.count(ptxConflicting->GetHash()))
607 {
608 // Transactions that don't explicitly signal replaceability are
609 // *not* replaceable with the current logic, even if one of their
610 // unconfirmed ancestors signals replaceability. This diverges
611 // from BIP125's inherited signaling description (see CVE-2021-31876).
612 // Applications relying on first-seen mempool behavior should
613 // check all unconfirmed ancestors; otherwise an opt-in ancestor
614 // might be replaced, causing removal of this descendant.
615 if (!SignalsOptInRBF(*ptxConflicting)) {
616 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "txn-mempool-conflict");
617 }
618
619 setConflicts.insert(ptxConflicting->GetHash());
620 }
621 }
622 }
623
625 m_view.SetBackend(m_viewmempool);
626
627 const CCoinsViewCache& coins_cache = m_active_chainstate.CoinsTip();
628 // do all inputs exist?
629 for (const CTxIn& txin : tx.vin) {
630 if (!coins_cache.HaveCoinInCache(txin.prevout)) {
631 coins_to_uncache.push_back(txin.prevout);
632 }
633
634 // Note: this call may add txin.prevout to the coins cache
635 // (coins_cache.cacheCoins) by way of FetchCoin(). It should be removed
636 // later (via coins_to_uncache) if this tx turns out to be invalid.
637 if (!m_view.HaveCoin(txin.prevout)) {
638 // Are inputs missing because we already have the tx?
639 for (size_t out = 0; out < tx.vout.size(); out++) {
640 // Optimistically just do efficient check of cache for outputs
641 if (coins_cache.HaveCoinInCache(COutPoint(hash, out))) {
642 return state.Invalid(TxValidationResult::TX_CONFLICT, "txn-already-known");
643 }
644 }
645 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
646 return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent");
647 }
648 }
649
650 // This is const, but calls into the back end CoinsViews. The CCoinsViewDB at the bottom of the
651 // hierarchy brings the best block into scope. See CCoinsViewDB::GetBestBlock().
652 m_view.GetBestBlock();
653
654 // we have all inputs cached now, so switch back to dummy (to protect
655 // against bugs where we pull more inputs from disk that miss being added
656 // to coins_to_uncache)
657 m_view.SetBackend(m_dummy);
658
659 // Only accept BIP68 sequence locked transactions that can be mined in the next
660 // block; we don't want our mempool filled up with transactions that can't
661 // be mined yet.
662 // Pass in m_view which has all of the relevant inputs cached. Note that, since m_view's
663 // backend was removed, it no longer pulls coins from the mempool.
664 if (!CheckSequenceLocks(m_active_chainstate.m_chain.Tip(), m_view, tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
665 return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "non-BIP68-final");
666
667 if (!Consensus::CheckTxInputs(tx, state, m_view, m_active_chainstate.m_blockman.GetSpendHeight(m_view), ws.m_base_fees)) {
668 return false; // state filled in by CheckTxInputs
669 }
670
671 // Check for non-standard pay-to-script-hash in inputs
672 const bool taproot_active = DeploymentActiveAfter(m_active_chainstate.m_chain.Tip(), args.m_chainparams.GetConsensus(), Consensus::DEPLOYMENT_TAPROOT);
673 if (fRequireStandard && !AreInputsStandard(tx, m_view, taproot_active)) {
674 return state.Invalid(TxValidationResult::TX_INPUTS_NOT_STANDARD, "bad-txns-nonstandard-inputs");
675 }
676
677 // Check for non-standard witnesses.
678 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, m_view))
679 return state.Invalid(TxValidationResult::TX_WITNESS_MUTATED, "bad-witness-nonstandard");
680
681 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, m_view, STANDARD_SCRIPT_VERIFY_FLAGS);
682
683 // nModifiedFees includes any fee deltas from PrioritiseTransaction
684 nModifiedFees = ws.m_base_fees;
685 m_pool.ApplyDelta(hash, nModifiedFees);
686
687 // Keep track of transactions that spend a coinbase, which we re-scan
688 // during reorgs to ensure COINBASE_MATURITY is still met.
689 bool fSpendsCoinbase = false;
690 for (const CTxIn &txin : tx.vin) {
691 const Coin &coin = m_view.AccessCoin(txin.prevout);
692 if (coin.IsCoinBase()) {
693 fSpendsCoinbase = true;
694 break;
695 }
696 }
697
698 entry.reset(new CTxMemPoolEntry(ptx, ws.m_base_fees, nAcceptTime, m_active_chainstate.m_chain.Height(),
699 fSpendsCoinbase, nSigOpsCost, lp));
700 unsigned int nSize = entry->GetTxSize();
701
702 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
703 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, "bad-txns-too-many-sigops",
704 strprintf("%d", nSigOpsCost));
705
706 // No transactions are allowed below minRelayTxFee except from disconnected
707 // blocks
708 if (!bypass_limits && !CheckFeeRate(nSize, nModifiedFees, state)) return false;
709
710 const CTxMemPool::setEntries setIterConflicting = m_pool.GetIterSet(setConflicts);
711 // Calculate in-mempool ancestors, up to a limit.
712 if (setConflicts.size() == 1) {
713 // In general, when we receive an RBF transaction with mempool conflicts, we want to know whether we
714 // would meet the chain limits after the conflicts have been removed. However, there isn't a practical
715 // way to do this short of calculating the ancestor and descendant sets with an overlay cache of
716 // changed mempool entries. Due to both implementation and runtime complexity concerns, this isn't
717 // very realistic, thus we only ensure a limited set of transactions are RBF'able despite mempool
718 // conflicts here. Importantly, we need to ensure that some transactions which were accepted using
719 // the below carve-out are able to be RBF'ed, without impacting the security the carve-out provides
720 // for off-chain contract systems (see link in the comment below).
721 //
722 // Specifically, the subset of RBF transactions which we allow despite chain limits are those which
723 // conflict directly with exactly one other transaction (but may evict children of said transaction),
724 // and which are not adding any new mempool dependencies. Note that the "no new mempool dependencies"
725 // check is accomplished later, so we don't bother doing anything about it here, but if BIP 125 is
726 // amended, we may need to move that check to here instead of removing it wholesale.
727 //
728 // Such transactions are clearly not merging any existing packages, so we are only concerned with
729 // ensuring that (a) no package is growing past the package size (not count) limits and (b) we are
730 // not allowing something to effectively use the (below) carve-out spot when it shouldn't be allowed
731 // to.
732 //
733 // To check these we first check if we meet the RBF criteria, above, and increment the descendant
734 // limits by the direct conflict and its descendants (as these are recalculated in
735 // CalculateMempoolAncestors by assuming the new transaction being added is a new descendant, with no
736 // removals, of each parent's existing dependent set). The ancestor count limits are unmodified (as
737 // the ancestor limits should be the same for both our new transaction and any conflicts).
738 // We don't bother incrementing m_limit_descendants by the full removal count as that limit never comes
739 // into force here (as we're only adding a single transaction).
740 assert(setIterConflicting.size() == 1);
741 CTxMemPool::txiter conflict = *setIterConflicting.begin();
742
743 m_limit_descendants += 1;
744 m_limit_descendant_size += conflict->GetSizeWithDescendants();
745 }
746
747 std::string errString;
748 if (!m_pool.CalculateMemPoolAncestors(*entry, setAncestors, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants, m_limit_descendant_size, errString)) {
749 setAncestors.clear();
750 // If CalculateMemPoolAncestors fails second time, we want the original error string.
751 std::string dummy_err_string;
752 // Contracting/payment channels CPFP carve-out:
753 // If the new transaction is relatively small (up to 40k weight)
754 // and has at most one ancestor (ie ancestor limit of 2, including
755 // the new transaction), allow it if its parent has exactly the
756 // descendant limit descendants.
757 //
758 // This allows protocols which rely on distrusting counterparties
759 // being able to broadcast descendants of an unconfirmed transaction
760 // to be secure by simply only having two immediately-spendable
761 // outputs - one for each counterparty. For more info on the uses for
762 // this, see https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2018-November/016518.html
763 if (nSize > EXTRA_DESCENDANT_TX_SIZE_LIMIT ||
764 !m_pool.CalculateMemPoolAncestors(*entry, setAncestors, 2, m_limit_ancestor_size, m_limit_descendants + 1, m_limit_descendant_size + EXTRA_DESCENDANT_TX_SIZE_LIMIT, dummy_err_string)) {
765 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "too-long-mempool-chain", errString);
766 }
767 }
768
769 // A transaction that spends outputs that would be replaced by it is invalid. Now
770 // that we have the set of all ancestors we can detect this
771 // pathological case by making sure setConflicts and setAncestors don't
772 // intersect.
773 if (const auto err_string{EntriesAndTxidsDisjoint(setAncestors, setConflicts, hash)}) {
774 // We classify this as a consensus error because a transaction depending on something it
775 // conflicts with would be inconsistent.
776 return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spends-conflicting-tx", *err_string);
777 }
778
779
780 if (!setConflicts.empty()) {
781 CFeeRate newFeeRate(nModifiedFees, nSize);
782 // It's possible that the replacement pays more fees than its direct conflicts but not more
783 // than all conflicts (i.e. the direct conflicts have high-fee descendants). However, if the
784 // replacement doesn't pay more fees than its direct conflicts, then we can be sure it's not
785 // more economically rational to mine. Before we go digging through the mempool for all
786 // transactions that would need to be removed (direct conflicts and all descendants), check
787 // that the replacement transaction pays more than its direct conflicts.
788 if (const auto err_string{PaysMoreThanConflicts(setIterConflicting, newFeeRate, hash)}) {
789 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
790 }
791
792 // Calculate all conflicting entries and enforce BIP125 Rule #5.
793 if (const auto err_string{GetEntriesForConflicts(tx, m_pool, setIterConflicting, allConflicting)}) {
795 "too many potential replacements", *err_string);
796 }
797 // Enforce BIP125 Rule #2.
798 if (const auto err_string{HasNoNewUnconfirmed(tx, m_pool, setIterConflicting)}) {
800 "replacement-adds-unconfirmed", *err_string);
801 }
802
803 // Check if it's economically rational to mine this transaction rather than the ones it
804 // replaces and pays for its own relay fees. Enforce BIP125 Rules #3 and #4.
805 for (CTxMemPool::txiter it : allConflicting) {
806 nConflictingFees += it->GetModifiedFee();
807 nConflictingSize += it->GetTxSize();
808 }
809 if (const auto err_string{PaysForRBF(nConflictingFees, nModifiedFees, nSize, ::incrementalRelayFee, hash)}) {
810 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "insufficient fee", *err_string);
811 }
812 }
813 return true;
814}
815
816bool MemPoolAccept::PolicyScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
817{
818 const CTransaction& tx = *ws.m_ptx;
819 TxValidationState& state = ws.m_state;
820
821 constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
822
823 // Check input scripts and signatures.
824 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
825 if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, txdata)) {
826 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
827 // need to turn both off, and compare against just turning off CLEANSTACK
828 // to see if the failure is specifically due to witness validation.
829 TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
830 if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
831 !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
832 // Only the witness is missing, so the transaction itself may be fine.
834 state.GetRejectReason(), state.GetDebugMessage());
835 }
836 return false; // state filled in by CheckInputScripts
837 }
838
839 return true;
840}
841
842bool MemPoolAccept::ConsensusScriptChecks(const ATMPArgs& args, Workspace& ws, PrecomputedTransactionData& txdata)
843{
844 const CTransaction& tx = *ws.m_ptx;
845 const uint256& hash = ws.m_hash;
846 TxValidationState& state = ws.m_state;
847 const CChainParams& chainparams = args.m_chainparams;
848
849 // Check again against the current block tip's script verification
850 // flags to cache our script execution flags. This is, of course,
851 // useless if the next block has different script flags from the
852 // previous one, but because the cache tracks script flags for us it
853 // will auto-invalidate and we'll just have a few blocks of extra
854 // misses on soft-fork activation.
855 //
856 // This is also useful in case of bugs in the standard flags that cause
857 // transactions to pass as valid when they're actually invalid. For
858 // instance the STRICTENC flag was incorrectly allowing certain
859 // CHECKSIG NOT scripts to pass, even though they were invalid.
860 //
861 // There is a similar check in CreateNewBlock() to prevent creating
862 // invalid blocks (using TestBlockValidity), however allowing such
863 // transactions into the mempool can be exploited as a DoS attack.
864 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(m_active_chainstate.m_chain.Tip(), chainparams.GetConsensus());
865 if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags, txdata, m_active_chainstate.CoinsTip())) {
866 return error("%s: BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s",
867 __func__, hash.ToString(), state.ToString());
868 }
869
870 return true;
871}
872
873bool MemPoolAccept::Finalize(const ATMPArgs& args, Workspace& ws)
874{
875 const CTransaction& tx = *ws.m_ptx;
876 const uint256& hash = ws.m_hash;
877 TxValidationState& state = ws.m_state;
878 const bool bypass_limits = args.m_bypass_limits;
879
880 CTxMemPool::setEntries& allConflicting = ws.m_all_conflicting;
881 CTxMemPool::setEntries& setAncestors = ws.m_ancestors;
882 const CAmount& nModifiedFees = ws.m_modified_fees;
883 const CAmount& nConflictingFees = ws.m_conflicting_fees;
884 const size_t& nConflictingSize = ws.m_conflicting_size;
885 std::unique_ptr<CTxMemPoolEntry>& entry = ws.m_entry;
886
887 // Remove conflicting transactions from the mempool
888 for (CTxMemPool::txiter it : allConflicting)
889 {
890 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s additional fees, %d delta bytes\n",
891 it->GetTx().GetHash().ToString(),
892 hash.ToString(),
893 FormatMoney(nModifiedFees - nConflictingFees),
894 (int)entry->GetTxSize() - (int)nConflictingSize);
895 ws.m_replaced_transactions.push_back(it->GetSharedTx());
896 }
897 m_pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
898
899 // This transaction should only count for fee estimation if:
900 // - it's not being re-added during a reorg which bypasses typical mempool fee limits
901 // - the node is not behind
902 // - the transaction is not dependent on any other transactions in the mempool
903 bool validForFeeEstimation = !bypass_limits && IsCurrentForFeeEstimation(m_active_chainstate) && m_pool.HasNoInputsOf(tx);
904
905 // Store transaction in memory
906 m_pool.addUnchecked(*entry, setAncestors, validForFeeEstimation);
907
908 // trim mempool and check if tx was trimmed
909 if (!bypass_limits) {
910 LimitMempoolSize(m_pool, m_active_chainstate.CoinsTip(), gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)});
911 if (!m_pool.exists(GenTxid::Txid(hash)))
912 return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
913 }
914 return true;
915}
916
917MempoolAcceptResult MemPoolAccept::AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args)
918{
920 LOCK(m_pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
921
922 Workspace ws(ptx);
923
924 if (!PreChecks(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
925
926 // Only compute the precomputed transaction data if we need to verify
927 // scripts (ie, other policy checks pass). We perform the inexpensive
928 // checks first and avoid hashing and signature verification unless those
929 // checks pass, to mitigate CPU exhaustion denial-of-service attacks.
931
932 if (!PolicyScriptChecks(args, ws, txdata)) return MempoolAcceptResult::Failure(ws.m_state);
933
934 if (!ConsensusScriptChecks(args, ws, txdata)) return MempoolAcceptResult::Failure(ws.m_state);
935
936 // Tx was accepted, but not added
937 if (args.m_test_accept) {
938 return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees);
939 }
940
941 if (!Finalize(args, ws)) return MempoolAcceptResult::Failure(ws.m_state);
942
943 GetMainSignals().TransactionAddedToMempool(ptx, m_pool.GetAndIncrementSequence());
944
945 return MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees);
946}
947
948PackageMempoolAcceptResult MemPoolAccept::AcceptMultipleTransactions(const std::vector<CTransactionRef>& txns, ATMPArgs& args)
949{
951
952 // These context-free package limits can be done before taking the mempool lock.
953 PackageValidationState package_state;
954 if (!CheckPackage(txns, package_state)) return PackageMempoolAcceptResult(package_state, {});
955
956 std::vector<Workspace> workspaces{};
957 workspaces.reserve(txns.size());
958 std::transform(txns.cbegin(), txns.cend(), std::back_inserter(workspaces),
959 [](const auto& tx) { return Workspace(tx); });
960 std::map<const uint256, const MempoolAcceptResult> results;
961
962 LOCK(m_pool.cs);
963
964 // Do all PreChecks first and fail fast to avoid running expensive script checks when unnecessary.
965 for (Workspace& ws : workspaces) {
966 if (!PreChecks(args, ws)) {
967 package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
968 // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
969 results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
970 return PackageMempoolAcceptResult(package_state, std::move(results));
971 }
972 // Make the coins created by this transaction available for subsequent transactions in the
973 // package to spend. Since we already checked conflicts in the package and we don't allow
974 // replacements, we don't need to track the coins spent. Note that this logic will need to be
975 // updated if package replace-by-fee is allowed in the future.
976 assert(!args.m_allow_bip125_replacement);
977 m_viewmempool.PackageAddTransaction(ws.m_ptx);
978 }
979
980 // Apply package mempool ancestor/descendant limits. Skip if there is only one transaction,
981 // because it's unnecessary. Also, CPFP carve out can increase the limit for individual
982 // transactions, but this exemption is not extended to packages in CheckPackageLimits().
983 std::string err_string;
984 if (txns.size() > 1 &&
985 !m_pool.CheckPackageLimits(txns, m_limit_ancestors, m_limit_ancestor_size, m_limit_descendants,
986 m_limit_descendant_size, err_string)) {
987 // All transactions must have individually passed mempool ancestor and descendant limits
988 // inside of PreChecks(), so this is separate from an individual transaction error.
989 package_state.Invalid(PackageValidationResult::PCKG_POLICY, "package-mempool-limits", err_string);
990 return PackageMempoolAcceptResult(package_state, std::move(results));
991 }
992
993 for (Workspace& ws : workspaces) {
995 if (!PolicyScriptChecks(args, ws, txdata)) {
996 // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
997 package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
998 results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
999 return PackageMempoolAcceptResult(package_state, std::move(results));
1000 }
1001 if (args.m_test_accept) {
1002 // When test_accept=true, transactions that pass PolicyScriptChecks are valid because there are
1003 // no further mempool checks (passing PolicyScriptChecks implies passing ConsensusScriptChecks).
1004 results.emplace(ws.m_ptx->GetWitnessHash(),
1005 MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_base_fees));
1006 }
1007 }
1008
1009 return PackageMempoolAcceptResult(package_state, std::move(results));
1010}
1011
1012} // anon namespace
1013
1016 CChainState& active_chainstate,
1017 const CTransactionRef &tx, int64_t nAcceptTime,
1018 bool bypass_limits, bool test_accept)
1020{
1021 std::vector<COutPoint> coins_to_uncache;
1022 MemPoolAccept::ATMPArgs args { chainparams, nAcceptTime, bypass_limits, coins_to_uncache,
1023 test_accept, /* m_allow_bip125_replacement */ true };
1024
1025 const MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransaction(tx, args);
1027 // Remove coins that were not present in the coins cache before calling
1028 // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
1029 // number of invalid transactions that attempt to overrun the in-memory coins cache
1030 // (`CCoinsViewCache::cacheCoins`).
1031
1032 for (const COutPoint& hashTx : coins_to_uncache)
1033 active_chainstate.CoinsTip().Uncache(hashTx);
1034 }
1035 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1036 BlockValidationState state_dummy;
1037 active_chainstate.FlushStateToDisk(state_dummy, FlushStateMode::PERIODIC);
1038 return result;
1039}
1040
1042 bool bypass_limits, bool test_accept)
1043{
1044 return AcceptToMemoryPoolWithTime(Params(), pool, active_chainstate, tx, GetTime(), bypass_limits, test_accept);
1045}
1046
1048 const Package& package, bool test_accept)
1049{
1051 assert(test_accept); // Only allow package accept dry-runs (testmempoolaccept RPC).
1052 assert(!package.empty());
1053 assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
1054
1055 std::vector<COutPoint> coins_to_uncache;
1056 const CChainParams& chainparams = Params();
1057 MemPoolAccept::ATMPArgs args { chainparams, GetTime(), /* bypass_limits */ false, coins_to_uncache,
1058 test_accept, /* m_allow_bip125_replacement */ false };
1059 const PackageMempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptMultipleTransactions(package, args);
1060
1061 // Uncache coins pertaining to transactions that were not submitted to the mempool.
1062 for (const COutPoint& hashTx : coins_to_uncache) {
1063 active_chainstate.CoinsTip().Uncache(hashTx);
1064 }
1065 return result;
1066}
1067
1069{
1070 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1071 // Force block reward to zero when right shift is undefined.
1072 if (halvings >= 64)
1073 return 0;
1074
1075 CAmount nSubsidy = 50 * COIN;
1076 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1077 nSubsidy >>= halvings;
1078 return nSubsidy;
1079}
1080
1082 std::string ldb_name,
1083 size_t cache_size_bytes,
1084 bool in_memory,
1085 bool should_wipe) : m_dbview(
1086 gArgs.GetDataDirNet() / ldb_name, cache_size_bytes, in_memory, should_wipe),
1087 m_catcherview(&m_dbview) {}
1088
1089void CoinsViews::InitCache()
1090{
1091 m_cacheview = std::make_unique<CCoinsViewCache>(&m_catcherview);
1092}
1093
1095 CTxMemPool* mempool,
1096 BlockManager& blockman,
1097 ChainstateManager& chainman,
1098 std::optional<uint256> from_snapshot_blockhash)
1099 : m_mempool(mempool),
1100 m_params(::Params()),
1101 m_blockman(blockman),
1102 m_chainman(chainman),
1103 m_from_snapshot_blockhash(from_snapshot_blockhash) {}
1104
1106 size_t cache_size_bytes,
1107 bool in_memory,
1108 bool should_wipe,
1109 std::string leveldb_name)
1110{
1112 leveldb_name += "_" + m_from_snapshot_blockhash->ToString();
1113 }
1114
1115 m_coins_views = std::make_unique<CoinsViews>(
1116 leveldb_name, cache_size_bytes, in_memory, should_wipe);
1117}
1118
1119void CChainState::InitCoinsCache(size_t cache_size_bytes)
1120{
1121 assert(m_coins_views != nullptr);
1122 m_coinstip_cache_size_bytes = cache_size_bytes;
1123 m_coins_views->InitCache();
1124}
1125
1126// Note that though this is marked const, we may end up modifying `m_cached_finished_ibd`, which
1127// is a performance-related implementation detail. This function must be marked
1128// `const` so that `CValidationInterface` clients (which are given a `const CChainState*`)
1129// can call it.
1130//
1132{
1133 // Optimization: pre-test latch before taking the lock.
1134 if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1135 return false;
1136
1137 LOCK(cs_main);
1138 if (m_cached_finished_ibd.load(std::memory_order_relaxed))
1139 return false;
1140 if (fImporting || fReindex)
1141 return true;
1142 if (m_chain.Tip() == nullptr)
1143 return true;
1145 return true;
1146 if (m_chain.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1147 return true;
1148 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1149 m_cached_finished_ibd.store(true, std::memory_order_relaxed);
1150 return false;
1151}
1152
1153static void AlertNotify(const std::string& strMessage)
1154{
1155 uiInterface.NotifyAlertChanged();
1156#if HAVE_SYSTEM
1157 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1158 if (strCmd.empty()) return;
1159
1160 // Alert text should be plain ascii coming from a trusted source, but to
1161 // be safe we first strip anything not in safeChars, then add single quotes around
1162 // the whole string before passing it to the shell:
1163 std::string singleQuote("'");
1164 std::string safeStatus = SanitizeString(strMessage);
1165 safeStatus = singleQuote+safeStatus+singleQuote;
1166 boost::replace_all(strCmd, "%s", safeStatus);
1167
1168 std::thread t(runCommand, strCmd);
1169 t.detach(); // thread runs free
1170#endif
1171}
1172
1174{
1176
1177 // Before we get past initial download, we cannot reliably alert about forks
1178 // (we assume we don't get stuck on a fork before finishing our initial sync)
1179 if (IsInitialBlockDownload()) {
1180 return;
1181 }
1182
1183 if (pindexBestInvalid && pindexBestInvalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
1184 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1186 } else {
1188 }
1189}
1190
1191// Called both upon regular invalid block discovery *and* InvalidateBlock
1193{
1194 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1195 pindexBestInvalid = pindexNew;
1196 if (pindexBestHeader != nullptr && pindexBestHeader->GetAncestor(pindexNew->nHeight) == pindexNew) {
1198 }
1199
1200 LogPrintf("%s: invalid block=%s height=%d log2_work=%f date=%s\n", __func__,
1201 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1202 log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime()));
1203 CBlockIndex *tip = m_chain.Tip();
1204 assert (tip);
1205 LogPrintf("%s: current best=%s height=%d log2_work=%f date=%s\n", __func__,
1206 tip->GetBlockHash().ToString(), m_chain.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1209}
1210
1211// Same as InvalidChainFound, above, except not called directly from InvalidateBlock,
1212// which does its own setBlockIndexCandidates management.
1214{
1216 pindex->nStatus |= BLOCK_FAILED_VALID;
1217 m_blockman.m_failed_blocks.insert(pindex);
1218 setDirtyBlockIndex.insert(pindex);
1219 setBlockIndexCandidates.erase(pindex);
1220 InvalidChainFound(pindex);
1221 }
1222}
1223
1224void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1225{
1226 // mark inputs spent
1227 if (!tx.IsCoinBase()) {
1228 txundo.vprevout.reserve(tx.vin.size());
1229 for (const CTxIn &txin : tx.vin) {
1230 txundo.vprevout.emplace_back();
1231 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1232 assert(is_spent);
1233 }
1234 }
1235 // add outputs
1236 AddCoins(inputs, tx, nHeight);
1237}
1238
1240 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1241 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1243}
1244
1246{
1248 CBlockIndex* pindexPrev = LookupBlockIndex(inputs.GetBestBlock());
1249 return pindexPrev->nHeight + 1;
1250}
1251
1252
1255
1257 // Setup the salted hasher
1259 // We want the nonce to be 64 bytes long to force the hasher to process
1260 // this chunk, which makes later hash computations more efficient. We
1261 // just write our 32-byte entropy twice to fill the 64 bytes.
1264 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1265 // setup_bytes creates the minimum possible cache (2 elements).
1266 size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetIntArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1267 size_t nElems = g_scriptExecutionCache.setup_bytes(nMaxCacheSize);
1268 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1269 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1270}
1271
1292 const CCoinsViewCache& inputs, unsigned int flags, bool cacheSigStore,
1293 bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
1294 std::vector<CScriptCheck>* pvChecks)
1295{
1296 if (tx.IsCoinBase()) return true;
1297
1298 if (pvChecks) {
1299 pvChecks->reserve(tx.vin.size());
1300 }
1301
1302 // First check if script executions have been cached with the same
1303 // flags. Note that this assumes that the inputs provided are
1304 // correct (ie that the transaction hash which is in tx's prevouts
1305 // properly commits to the scriptPubKey in the inputs view of that
1306 // transaction).
1307 uint256 hashCacheEntry;
1309 hasher.Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1310 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1311 if (g_scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1312 return true;
1313 }
1314
1315 if (!txdata.m_spent_outputs_ready) {
1316 std::vector<CTxOut> spent_outputs;
1317 spent_outputs.reserve(tx.vin.size());
1318
1319 for (const auto& txin : tx.vin) {
1320 const COutPoint& prevout = txin.prevout;
1321 const Coin& coin = inputs.AccessCoin(prevout);
1322 assert(!coin.IsSpent());
1323 spent_outputs.emplace_back(coin.out);
1324 }
1325 txdata.Init(tx, std::move(spent_outputs));
1326 }
1327 assert(txdata.m_spent_outputs.size() == tx.vin.size());
1328
1329 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1330
1331 // We very carefully only pass in things to CScriptCheck which
1332 // are clearly committed to by tx' witness hash. This provides
1333 // a sanity check that our caching is not introducing consensus
1334 // failures through additional data in, eg, the coins being
1335 // spent being checked as a part of CScriptCheck.
1336
1337 // Verify signature
1338 CScriptCheck check(txdata.m_spent_outputs[i], tx, i, flags, cacheSigStore, &txdata);
1339 if (pvChecks) {
1340 pvChecks->push_back(CScriptCheck());
1341 check.swap(pvChecks->back());
1342 } else if (!check()) {
1344 // Check whether the failure was caused by a
1345 // non-mandatory script verification check, such as
1346 // non-standard DER encodings or non-null dummy
1347 // arguments; if so, ensure we return NOT_STANDARD
1348 // instead of CONSENSUS to avoid downstream users
1349 // splitting the network between upgraded and
1350 // non-upgraded nodes by banning CONSENSUS-failing
1351 // data providers.
1352 CScriptCheck check2(txdata.m_spent_outputs[i], tx, i,
1353 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1354 if (check2())
1355 return state.Invalid(TxValidationResult::TX_NOT_STANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1356 }
1357 // MANDATORY flag failures correspond to
1358 // TxValidationResult::TX_CONSENSUS. Because CONSENSUS
1359 // failures are the most serious case of validation
1360 // failures, we may need to consider using
1361 // RECENT_CONSENSUS_CHANGE for any script failure that
1362 // could be due to non-upgraded nodes which we may want to
1363 // support, to avoid splitting the network (but this
1364 // depends on the details of how net_processing handles
1365 // such errors).
1366 return state.Invalid(TxValidationResult::TX_CONSENSUS, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1367 }
1368 }
1369
1370 if (cacheFullScriptStore && !pvChecks) {
1371 // We executed all of the provided scripts, and were told to
1372 // cache the result. Do so now.
1373 g_scriptExecutionCache.insert(hashCacheEntry);
1374 }
1375
1376 return true;
1377}
1378
1379bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage)
1380{
1381 AbortNode(strMessage, userMessage);
1382 return state.Error(strMessage);
1383}
1384
1392int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1393{
1394 bool fClean = true;
1395
1396 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1397
1398 if (undo.nHeight == 0) {
1399 // Missing undo metadata (height and coinbase). Older versions included this
1400 // information only in undo records for the last spend of a transactions'
1401 // outputs. This implies that it must be present for some other output of the same tx.
1402 const Coin& alternate = AccessByTxid(view, out.hash);
1403 if (!alternate.IsSpent()) {
1404 undo.nHeight = alternate.nHeight;
1405 undo.fCoinBase = alternate.fCoinBase;
1406 } else {
1407 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1408 }
1409 }
1410 // If the coin already exists as an unspent coin in the cache, then the
1411 // possible_overwrite parameter to AddCoin must be set to true. We have
1412 // already checked whether an unspent coin exists above using HaveCoin, so
1413 // we don't need to guess. When fClean is false, an unspent coin already
1414 // existed and it is an overwrite.
1415 view.AddCoin(out, std::move(undo), !fClean);
1416
1417 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1418}
1419
1423{
1424 bool fClean = true;
1425
1426 CBlockUndo blockUndo;
1427 if (!UndoReadFromDisk(blockUndo, pindex)) {
1428 error("DisconnectBlock(): failure reading undo data");
1429 return DISCONNECT_FAILED;
1430 }
1431
1432 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1433 error("DisconnectBlock(): block and undo data inconsistent");
1434 return DISCONNECT_FAILED;
1435 }
1436
1437 // undo transactions in reverse order
1438 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1439 const CTransaction &tx = *(block.vtx[i]);
1440 uint256 hash = tx.GetHash();
1441 bool is_coinbase = tx.IsCoinBase();
1442
1443 // Check that all outputs are available and match the outputs in the block itself
1444 // exactly.
1445 for (size_t o = 0; o < tx.vout.size(); o++) {
1446 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1447 COutPoint out(hash, o);
1448 Coin coin;
1449 bool is_spent = view.SpendCoin(out, &coin);
1450 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1451 fClean = false; // transaction output mismatch
1452 }
1453 }
1454 }
1455
1456 // restore inputs
1457 if (i > 0) { // not coinbases
1458 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1459 if (txundo.vprevout.size() != tx.vin.size()) {
1460 error("DisconnectBlock(): transaction and undo data inconsistent");
1461 return DISCONNECT_FAILED;
1462 }
1463 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1464 const COutPoint &out = tx.vin[j].prevout;
1465 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1466 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1467 fClean = fClean && res != DISCONNECT_UNCLEAN;
1468 }
1469 // At this point, all of txundo.vprevout should have been moved out.
1470 }
1471 }
1472
1473 // move best block pointer to prevout block
1474 view.SetBestBlock(pindex->pprev->GetBlockHash());
1475
1476 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1477}
1478
1480
1482{
1483 scriptcheckqueue.StartWorkerThreads(threads_num);
1484}
1485
1487{
1488 scriptcheckqueue.StopWorkerThreads();
1489}
1490
1495{
1496private:
1497 int bit;
1498
1499public:
1500 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1501
1502 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1503 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1504 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1505 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1506
1507 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1508 {
1509 return pindex->nHeight >= params.MinBIP9WarningHeight &&
1511 ((pindex->nVersion >> bit) & 1) != 0 &&
1512 ((g_versionbitscache.ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1513 }
1514};
1515
1517
1518static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams)
1519{
1520 unsigned int flags = SCRIPT_VERIFY_NONE;
1521
1522 // BIP16 didn't become active until Apr 1 2012 (on mainnet, and
1523 // retroactively applied to testnet)
1524 // However, only one historical block violated the P2SH rules (on both
1525 // mainnet and testnet), so for simplicity, always leave P2SH
1526 // on except for the one violating block.
1527 if (consensusparams.BIP16Exception.IsNull() || // no bip16 exception on this chain
1528 pindex->phashBlock == nullptr || // this is a new candidate block, eg from TestBlockValidity()
1529 *pindex->phashBlock != consensusparams.BIP16Exception) // this block isn't the historical exception
1530 {
1531 // Enforce WITNESS rules whenever P2SH is in effect
1533 }
1534
1535 // Enforce the DERSIG (BIP66) rule
1536 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_DERSIG)) {
1538 }
1539
1540 // Enforce CHECKLOCKTIMEVERIFY (BIP65)
1541 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_CLTV)) {
1543 }
1544
1545 // Enforce CHECKSEQUENCEVERIFY (BIP112)
1546 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_CSV)) {
1548 }
1549
1550 // Enforce Taproot (BIP340-BIP342)
1551 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_TAPROOT)) {
1553 }
1554
1555 // Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)
1556 if (DeploymentActiveAt(*pindex, consensusparams, Consensus::DEPLOYMENT_SEGWIT)) {
1558 }
1559
1560 return flags;
1561}
1562
1563
1564
1565static int64_t nTimeCheck = 0;
1566static int64_t nTimeForks = 0;
1567static int64_t nTimeVerify = 0;
1568static int64_t nTimeConnect = 0;
1569static int64_t nTimeIndex = 0;
1570static int64_t nTimeTotal = 0;
1571static int64_t nBlocksTotal = 0;
1572
1577 CCoinsViewCache& view, bool fJustCheck)
1578{
1580 assert(pindex);
1581 assert(*pindex->phashBlock == block.GetHash());
1582 int64_t nTimeStart = GetTimeMicros();
1583
1584 // Check it again in case a previous version let a bad block in
1585 // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1586 // ContextualCheckBlockHeader() here. This means that if we add a new
1587 // consensus rule that is enforced in one of those two functions, then we
1588 // may have let in a block that violates the rule prior to updating the
1589 // software, and we would NOT be enforcing the rule here. Fully solving
1590 // upgrade from one software version to the next after a consensus rule
1591 // change is potentially tricky and issue-specific (see NeedsRedownload()
1592 // for one approach that was used for BIP 141 deployment).
1593 // Also, currently the rule against blocks more than 2 hours in the future
1594 // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1595 // re-enforce that rule here (at least until we make it impossible for
1596 // GetAdjustedTime() to go backward).
1597 if (!CheckBlock(block, state, m_params.GetConsensus(), !fJustCheck, !fJustCheck)) {
1599 // We don't write down blocks to disk if they may have been
1600 // corrupted, so this should be impossible unless we're having hardware
1601 // problems.
1602 return AbortNode(state, "Corrupt block found indicating potential hardware failure; shutting down");
1603 }
1604 return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
1605 }
1606
1607 // verify that the view's current state corresponds to the previous block
1608 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1609 assert(hashPrevBlock == view.GetBestBlock());
1610
1611 nBlocksTotal++;
1612
1613 // Special case for the genesis block, skipping connection of its transactions
1614 // (its coinbase is unspendable)
1615 if (block.GetHash() == m_params.GetConsensus().hashGenesisBlock) {
1616 if (!fJustCheck)
1617 view.SetBestBlock(pindex->GetBlockHash());
1618 return true;
1619 }
1620
1621 bool fScriptChecks = true;
1622 if (!hashAssumeValid.IsNull()) {
1623 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1624 // A suitable default value is included with the software and updated from time to time. Because validity
1625 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1626 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1627 // effectively caching the result of part of the verification.
1628 BlockMap::const_iterator it = m_blockman.m_block_index.find(hashAssumeValid);
1629 if (it != m_blockman.m_block_index.end()) {
1630 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1631 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1633 // This block is a member of the assumed verified chain and an ancestor of the best header.
1634 // Script verification is skipped when connecting blocks under the
1635 // assumevalid block. Assuming the assumevalid block is valid this
1636 // is safe because block merkle hashes are still computed and checked,
1637 // Of course, if an assumed valid block is invalid due to false scriptSigs
1638 // this optimization would allow an invalid chain to be accepted.
1639 // The equivalent time check discourages hash power from extorting the network via DOS attack
1640 // into accepting an invalid block through telling users they must manually set assumevalid.
1641 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1642 // it hard to hide the implication of the demand. This also avoids having release candidates
1643 // that are hardly doing any signature verification at all in testing without having to
1644 // artificially set the default assumed verified block further back.
1645 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1646 // least as good as the expected chain.
1647 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, m_params.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1648 }
1649 }
1650 }
1651
1652 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1653 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1654
1655 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1656 // unless those are already completely spent.
1657 // If such overwrites are allowed, coinbases and transactions depending upon those
1658 // can be duplicated to remove the ability to spend the first instance -- even after
1659 // being sent to another address.
1660 // See BIP30, CVE-2012-1909, and http://r6.ca/blog/20120206T005236Z.html for more information.
1661 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1662 // already refuses previously-known transaction ids entirely.
1663 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1664 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1665 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1666 // initial block download.
1667 bool fEnforceBIP30 = !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1668 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1669
1670 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1671 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1672 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1673 // before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further
1674 // duplicate transactions descending from the known pairs either.
1675 // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
1676
1677 // BIP34 requires that a block at height X (block X) has its coinbase
1678 // scriptSig start with a CScriptNum of X (indicated height X). The above
1679 // logic of no longer requiring BIP30 once BIP34 activates is flawed in the
1680 // case that there is a block X before the BIP34 height of 227,931 which has
1681 // an indicated height Y where Y is greater than X. The coinbase for block
1682 // X would also be a valid coinbase for block Y, which could be a BIP30
1683 // violation. An exhaustive search of all mainnet coinbases before the
1684 // BIP34 height which have an indicated height greater than the block height
1685 // reveals many occurrences. The 3 lowest indicated heights found are
1686 // 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 3
1687 // heights would be the first opportunity for BIP30 to be violated.
1688
1689 // The search reveals a great many blocks which have an indicated height
1690 // greater than 1,983,702, so we simply remove the optimization to skip
1691 // BIP30 checking for blocks at height 1,983,702 or higher. Before we reach
1692 // that block in another 25 years or so, we should take advantage of a
1693 // future consensus change to do a new and improved version of BIP34 that
1694 // will actually prevent ever creating any duplicate coinbases in the
1695 // future.
1696 static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;
1697
1698 // There is no potential to create a duplicate coinbase at block 209,921
1699 // because this is still before the BIP34 height and so explicit BIP30
1700 // checking is still active.
1701
1702 // The final case is block 176,684 which has an indicated height of
1703 // 490,897. Unfortunately, this issue was not discovered until about 2 weeks
1704 // before block 490,897 so there was not much opportunity to address this
1705 // case other than to carefully analyze it and determine it would not be a
1706 // problem. Block 490,897 was, in fact, mined with a different coinbase than
1707 // block 176,684, but it is important to note that even if it hadn't been or
1708 // is remined on an alternate fork with a duplicate coinbase, we would still
1709 // not run into a BIP30 violation. This is because the coinbase for 176,684
1710 // is spent in block 185,956 in transaction
1711 // d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This
1712 // spending transaction can't be duplicated because it also spends coinbase
1713 // 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This
1714 // coinbase has an indicated height of over 4.2 billion, and wouldn't be
1715 // duplicatable until that height, and it's currently impossible to create a
1716 // chain that long. Nevertheless we may wish to consider a future soft fork
1717 // which retroactively prevents block 490,897 from creating a duplicate
1718 // coinbase. The two historical BIP30 violations often provide a confusing
1719 // edge case when manipulating the UTXO and it would be simpler not to have
1720 // another edge case to deal with.
1721
1722 // testnet3 has no blocks before the BIP34 height with indicated heights
1723 // post BIP34 before approximately height 486,000,000 and presumably will
1724 // be reset before it reaches block 1,983,702 and starts doing unnecessary
1725 // BIP30 checking again.
1726 assert(pindex->pprev);
1727 CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(m_params.GetConsensus().BIP34Height);
1728 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1729 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == m_params.GetConsensus().BIP34Hash));
1730
1731 // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
1732 // consensus change that ensures coinbases at those heights can not
1733 // duplicate earlier coinbases.
1734 if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
1735 for (const auto& tx : block.vtx) {
1736 for (size_t o = 0; o < tx->vout.size(); o++) {
1737 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1738 LogPrintf("ERROR: ConnectBlock(): tried to overwrite transaction\n");
1739 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30");
1740 }
1741 }
1742 }
1743 }
1744
1745 // Enforce BIP68 (sequence locks)
1746 int nLockTimeFlags = 0;
1748 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1749 }
1750
1751 // Get the script flags for this block
1752 unsigned int flags = GetBlockScriptFlags(pindex, m_params.GetConsensus());
1753
1754 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1755 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1756
1757 CBlockUndo blockundo;
1758
1759 // Precomputed transaction data pointers must not be invalidated
1760 // until after `control` has run the script checks (potentially
1761 // in multiple threads). Preallocate the vector size so a new allocation
1762 // doesn't invalidate pointers into the vector, and keep txsdata in scope
1763 // for as long as `control`.
1764 CCheckQueueControl<CScriptCheck> control(fScriptChecks && g_parallel_script_checks ? &scriptcheckqueue : nullptr);
1765 std::vector<PrecomputedTransactionData> txsdata(block.vtx.size());
1766
1767 std::vector<int> prevheights;
1768 CAmount nFees = 0;
1769 int nInputs = 0;
1770 int64_t nSigOpsCost = 0;
1771 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1772 for (unsigned int i = 0; i < block.vtx.size(); i++)
1773 {
1774 const CTransaction &tx = *(block.vtx[i]);
1775
1776 nInputs += tx.vin.size();
1777
1778 if (!tx.IsCoinBase())
1779 {
1780 CAmount txfee = 0;
1781 TxValidationState tx_state;
1782 if (!Consensus::CheckTxInputs(tx, tx_state, view, pindex->nHeight, txfee)) {
1783 // Any transaction validation failure in ConnectBlock is a block consensus failure
1785 tx_state.GetRejectReason(), tx_state.GetDebugMessage());
1786 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), state.ToString());
1787 }
1788 nFees += txfee;
1789 if (!MoneyRange(nFees)) {
1790 LogPrintf("ERROR: %s: accumulated fee in the block out of range.\n", __func__);
1791 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-accumulated-fee-outofrange");
1792 }
1793
1794 // Check that transaction is BIP68 final
1795 // BIP68 lock checks (as opposed to nLockTime checks) must
1796 // be in ConnectBlock because they require the UTXO set
1797 prevheights.resize(tx.vin.size());
1798 for (size_t j = 0; j < tx.vin.size(); j++) {
1799 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1800 }
1801
1802 if (!SequenceLocks(tx, nLockTimeFlags, prevheights, *pindex)) {
1803 LogPrintf("ERROR: %s: contains a non-BIP68-final transaction\n", __func__);
1804 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal");
1805 }
1806 }
1807
1808 // GetTransactionSigOpCost counts 3 types of sigops:
1809 // * legacy (always)
1810 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1811 // * witness (when witness enabled in flags and excludes coinbase)
1812 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1813 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST) {
1814 LogPrintf("ERROR: ConnectBlock(): too many sigops\n");
1815 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops");
1816 }
1817
1818 if (!tx.IsCoinBase())
1819 {
1820 std::vector<CScriptCheck> vChecks;
1821 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1822 TxValidationState tx_state;
1823 if (fScriptChecks && !CheckInputScripts(tx, tx_state, view, flags, fCacheResults, fCacheResults, txsdata[i], g_parallel_script_checks ? &vChecks : nullptr)) {
1824 // Any transaction validation failure in ConnectBlock is a block consensus failure
1826 tx_state.GetRejectReason(), tx_state.GetDebugMessage());
1827 return error("ConnectBlock(): CheckInputScripts on %s failed with %s",
1828 tx.GetHash().ToString(), state.ToString());
1829 }
1830 control.Add(vChecks);
1831 }
1832
1833 CTxUndo undoDummy;
1834 if (i > 0) {
1835 blockundo.vtxundo.push_back(CTxUndo());
1836 }
1837 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1838 }
1839 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1840 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
1841
1842 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, m_params.GetConsensus());
1843 if (block.vtx[0]->GetValueOut() > blockReward) {
1844 LogPrintf("ERROR: ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)\n", block.vtx[0]->GetValueOut(), blockReward);
1845 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-amount");
1846 }
1847
1848 if (!control.Wait()) {
1849 LogPrintf("ERROR: %s: CheckQueue failed\n", __func__);
1850 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "block-validation-failed");
1851 }
1852 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1853 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
1854
1855 if (fJustCheck)
1856 return true;
1857
1858 if (!WriteUndoDataForBlock(blockundo, state, pindex, m_params)) {
1859 return false;
1860 }
1861
1862 if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
1864 setDirtyBlockIndex.insert(pindex);
1865 }
1866
1867 assert(pindex->phashBlock);
1868 // add this block to the view's block chain
1869 view.SetBestBlock(pindex->GetBlockHash());
1870
1871 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1872 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1873
1874 TRACE6(validation, block_connected,
1875 block.GetHash().data(),
1876 pindex->nHeight,
1877 block.vtx.size(),
1878 nInputs,
1879 nSigOpsCost,
1880 GetTimeMicros() - nTimeStart // in microseconds (µs)
1881 );
1882
1883 return true;
1884}
1885
1886CoinsCacheSizeState CChainState::GetCoinsCacheSizeState()
1887{
1888 return this->GetCoinsCacheSizeState(
1890 gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
1891}
1892
1893CoinsCacheSizeState CChainState::GetCoinsCacheSizeState(
1894 size_t max_coins_cache_size_bytes,
1895 size_t max_mempool_size_bytes)
1896{
1897 const int64_t nMempoolUsage = m_mempool ? m_mempool->DynamicMemoryUsage() : 0;
1898 int64_t cacheSize = CoinsTip().DynamicMemoryUsage();
1899 int64_t nTotalSpace =
1900 max_coins_cache_size_bytes + std::max<int64_t>(max_mempool_size_bytes - nMempoolUsage, 0);
1901
1903 static constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES = 10 * 1024 * 1024; // 10MB
1904 int64_t large_threshold =
1905 std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE_BYTES);
1906
1907 if (cacheSize > nTotalSpace) {
1908 LogPrintf("Cache size (%s) exceeds total space (%s)\n", cacheSize, nTotalSpace);
1910 } else if (cacheSize > large_threshold) {
1912 }
1914}
1915
1917 BlockValidationState &state,
1918 FlushStateMode mode,
1919 int nManualPruneHeight)
1920{
1921 LOCK(cs_main);
1922 assert(this->CanFlushToDisk());
1923 static std::chrono::microseconds nLastWrite{0};
1924 static std::chrono::microseconds nLastFlush{0};
1925 std::set<int> setFilesToPrune;
1926 bool full_flush_completed = false;
1927
1928 const size_t coins_count = CoinsTip().GetCacheSize();
1929 const size_t coins_mem_usage = CoinsTip().DynamicMemoryUsage();
1930
1931 try {
1932 {
1933 bool fFlushForPrune = false;
1934 bool fDoFullFlush = false;
1935
1936 CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
1938 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1939 // make sure we don't prune above the blockfilterindexes bestblocks
1940 // pruning is height-based
1941 int last_prune = m_chain.Height(); // last height we can prune
1943 last_prune = std::max(1, std::min(last_prune, index.GetSummary().best_block_height));
1944 });
1945
1946 if (nManualPruneHeight > 0) {
1947 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);
1948
1949 m_blockman.FindFilesToPruneManual(setFilesToPrune, std::min(last_prune, nManualPruneHeight), m_chain.Height());
1950 } else {
1951 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);
1952
1954 fCheckForPruning = false;
1955 }
1956 if (!setFilesToPrune.empty()) {
1957 fFlushForPrune = true;
1958 if (!fHavePruned) {
1959 m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
1960 fHavePruned = true;
1961 }
1962 }
1963 }
1964 const auto nNow = GetTime<std::chrono::microseconds>();
1965 // Avoid writing/flushing immediately after startup.
1966 if (nLastWrite.count() == 0) {
1967 nLastWrite = nNow;
1968 }
1969 if (nLastFlush.count() == 0) {
1970 nLastFlush = nNow;
1971 }
1972 // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
1973 bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
1974 // The cache is over the limit, we have to write now.
1975 bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
1976 // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
1977 bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > nLastWrite + DATABASE_WRITE_INTERVAL;
1978 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1979 bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > nLastFlush + DATABASE_FLUSH_INTERVAL;
1980 // Combine all conditions that result in a full cache flush.
1981 fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1982 // Write blocks and block index to disk.
1983 if (fDoFullFlush || fPeriodicWrite) {
1984 // Depend on nMinDiskSpace to ensure we can write block index
1986 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
1987 }
1988 {
1989 LOG_TIME_MILLIS_WITH_CATEGORY("write block and undo data to disk", BCLog::BENCH);
1990
1991 // First make sure all block and undo data is flushed to disk.
1993 }
1994
1995 // Then update all block file information (which may refer to block and undo files).
1996 {
1997 LOG_TIME_MILLIS_WITH_CATEGORY("write block index to disk", BCLog::BENCH);
1998
1999 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2000 vFiles.reserve(setDirtyFileInfo.size());
2001 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2002 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2003 setDirtyFileInfo.erase(it++);
2004 }
2005 std::vector<const CBlockIndex*> vBlocks;
2006 vBlocks.reserve(setDirtyBlockIndex.size());
2007 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2008 vBlocks.push_back(*it);
2009 setDirtyBlockIndex.erase(it++);
2010 }
2011 if (!m_blockman.m_block_tree_db->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2012 return AbortNode(state, "Failed to write to block index database");
2013 }
2014 }
2015 // Finally remove any pruned files
2016 if (fFlushForPrune) {
2017 LOG_TIME_MILLIS_WITH_CATEGORY("unlink pruned files", BCLog::BENCH);
2018
2019 UnlinkPrunedFiles(setFilesToPrune);
2020 }
2021 nLastWrite = nNow;
2022 }
2023 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2024 if (fDoFullFlush && !CoinsTip().GetBestBlock().IsNull()) {
2025 LOG_TIME_MILLIS_WITH_CATEGORY(strprintf("write coins cache to disk (%d coins, %.2fkB)",
2026 coins_count, coins_mem_usage / 1000), BCLog::BENCH);
2027
2028 // Typical Coin structures on disk are around 48 bytes in size.
2029 // Pushing a new one to the database can cause it to be written
2030 // twice (once in the log, and once in the tables). This is already
2031 // an overestimation, as most will delete an existing entry or
2032 // overwrite one. Still, use a conservative safety factor of 2.
2033 if (!CheckDiskSpace(gArgs.GetDataDirNet(), 48 * 2 * 2 * CoinsTip().GetCacheSize())) {
2034 return AbortNode(state, "Disk space is too low!", _("Disk space is too low!"));
2035 }
2036 // Flush the chainstate (which may refer to block index entries).
2037 if (!CoinsTip().Flush())
2038 return AbortNode(state, "Failed to write to coin database");
2039 nLastFlush = nNow;
2040 full_flush_completed = true;
2041 }
2042 }
2043 if (full_flush_completed) {
2044 // Update best block in wallet (so we can detect restored wallets).
2046 }
2047 } catch (const std::runtime_error& e) {
2048 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2049 }
2050 return true;
2051}
2052
2054{
2056 if (!this->FlushStateToDisk(state, FlushStateMode::ALWAYS)) {
2057 LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2058 }
2059}
2060
2062{
2064 fCheckForPruning = true;
2065 if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
2066 LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
2067 }
2068}
2069
2070static void DoWarning(const bilingual_str& warning)
2071{
2072 static bool fWarned = false;
2073 SetMiscWarning(warning);
2074 if (!fWarned) {
2075 AlertNotify(warning.original);
2076 fWarned = true;
2077 }
2078}
2079
2081static void AppendWarning(bilingual_str& res, const bilingual_str& warn)
2082{
2083 if (!res.empty()) res += Untranslated(", ");
2084 res += warn;
2085}
2086
2087static void UpdateTipLog(
2088 const CCoinsViewCache& coins_tip,
2089 const CBlockIndex* tip,
2090 const CChainParams& params,
2091 const std::string& func_name,
2092 const std::string& prefix,
2093 const std::string& warning_messages) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
2094{
2095
2097 LogPrintf("%s%s: new best=%s height=%d version=0x%08x log2_work=%f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)%s\n",
2098 prefix, func_name,
2099 tip->GetBlockHash().ToString(), tip->nHeight, tip->nVersion,
2100 log(tip->nChainWork.getdouble()) / log(2.0), (unsigned long)tip->nChainTx,
2101 FormatISO8601DateTime(tip->GetBlockTime()),
2102 GuessVerificationProgress(params.TxData(), tip),
2103 coins_tip.DynamicMemoryUsage() * (1.0 / (1 << 20)),
2104 coins_tip.GetCacheSize(),
2105 !warning_messages.empty() ? strprintf(" warning='%s'", warning_messages) : "");
2106}
2107
2108void CChainState::UpdateTip(const CBlockIndex* pindexNew)
2109{
2110 const auto& coins_tip = this->CoinsTip();
2111
2112 // The remainder of the function isn't relevant if we are not acting on
2113 // the active chainstate, so return if need be.
2114 if (this != &m_chainman.ActiveChainstate()) {
2115 // Only log every so often so that we don't bury log messages at the tip.
2116 constexpr int BACKGROUND_LOG_INTERVAL = 2000;
2117 if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
2118 UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "[background validation] ", "");
2119 }
2120 return;
2121 }
2122
2123 // New best block
2124 if (m_mempool) {
2126 }
2127
2128 {
2130 g_best_block = pindexNew->GetBlockHash();
2131 g_best_block_cv.notify_all();
2132 }
2133
2134 bilingual_str warning_messages;
2135 if (!this->IsInitialBlockDownload()) {
2136 const CBlockIndex* pindex = pindexNew;
2137 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2138 WarningBitsConditionChecker checker(bit);
2139 ThresholdState state = checker.GetStateFor(pindex, m_params.GetConsensus(), warningcache[bit]);
2140 if (state == ThresholdState::ACTIVE || state == ThresholdState::LOCKED_IN) {
2141 const bilingual_str warning = strprintf(_("Unknown new rules activated (versionbit %i)"), bit);
2142 if (state == ThresholdState::ACTIVE) {
2143 DoWarning(warning);
2144 } else {
2145 AppendWarning(warning_messages, warning);
2146 }
2147 }
2148 }
2149 }
2150 UpdateTipLog(coins_tip, pindexNew, m_params, __func__, "", warning_messages.original);
2151}
2152
2164{
2167
2168 CBlockIndex *pindexDelete = m_chain.Tip();
2169 assert(pindexDelete);
2170 // Read block from disk.
2171 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2172 CBlock& block = *pblock;
2173 if (!ReadBlockFromDisk(block, pindexDelete, m_params.GetConsensus())) {
2174 return error("DisconnectTip(): Failed to read block");
2175 }
2176 // Apply the block atomically to the chain state.
2177 int64_t nStart = GetTimeMicros();
2178 {
2179 CCoinsViewCache view(&CoinsTip());
2180 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2181 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2182 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2183 bool flushed = view.Flush();
2184 assert(flushed);
2185 }
2186 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2187 // Write the chain state to disk, if necessary.
2189 return false;
2190 }
2191
2192 if (disconnectpool && m_mempool) {
2193 // Save transactions to re-add to mempool at end of reorg
2194 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2195 disconnectpool->addTransaction(*it);
2196 }
2197 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2198 // Drop the earliest entry, and remove its children from the mempool.
2199 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2201 disconnectpool->removeEntry(it);
2202 }
2203 }
2204
2205 m_chain.SetTip(pindexDelete->pprev);
2206
2207 UpdateTip(pindexDelete->pprev);
2208 // Let wallets know transactions went from 1-confirmed to
2209 // 0-confirmed or conflicted:
2210 GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2211 return true;
2212}
2213
2214static int64_t nTimeReadFromDisk = 0;
2215static int64_t nTimeConnectTotal = 0;
2216static int64_t nTimeFlush = 0;
2217static int64_t nTimeChainState = 0;
2218static int64_t nTimePostConnect = 0;
2219
2222 std::shared_ptr<const CBlock> pblock;
2224};
2233private:
2234 std::vector<PerBlockConnectTrace> blocksConnected;
2235
2236public:
2238
2239 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2240 assert(!blocksConnected.back().pindex);
2241 assert(pindex);
2242 assert(pblock);
2243 blocksConnected.back().pindex = pindex;
2244 blocksConnected.back().pblock = std::move(pblock);
2245 blocksConnected.emplace_back();
2246 }
2247
2248 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2249 // We always keep one extra block at the end of our list because
2250 // blocks are added after all the conflicted transactions have
2251 // been filled in. Thus, the last entry should always be an empty
2252 // one waiting for the transactions from the next block. We pop
2253 // the last entry here to make sure the list we return is sane.
2254 assert(!blocksConnected.back().pindex);
2255 blocksConnected.pop_back();
2256 return blocksConnected;
2257 }
2258};
2259
2266bool CChainState::ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool)
2267{
2270
2271 assert(pindexNew->pprev == m_chain.Tip());
2272 // Read block from disk.
2273 int64_t nTime1 = GetTimeMicros();
2274 std::shared_ptr<const CBlock> pthisBlock;
2275 if (!pblock) {
2276 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2277 if (!ReadBlockFromDisk(*pblockNew, pindexNew, m_params.GetConsensus())) {
2278 return AbortNode(state, "Failed to read block");
2279 }
2280 pthisBlock = pblockNew;
2281 } else {
2282 pthisBlock = pblock;
2283 }
2284 const CBlock& blockConnecting = *pthisBlock;
2285 // Apply the block atomically to the chain state.
2286 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2287 int64_t nTime3;
2288 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2289 {
2290 CCoinsViewCache view(&CoinsTip());
2291 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view);
2292 GetMainSignals().BlockChecked(blockConnecting, state);
2293 if (!rv) {
2294 if (state.IsInvalid())
2295 InvalidBlockFound(pindexNew, state);
2296 return error("%s: ConnectBlock %s failed, %s", __func__, pindexNew->GetBlockHash().ToString(), state.ToString());
2297 }
2298 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2299 assert(nBlocksTotal > 0);
2300 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2301 bool flushed = view.Flush();
2302 assert(flushed);
2303 }
2304 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2305 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2306 // Write the chain state to disk, if necessary.
2308 return false;
2309 }
2310 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2311 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2312 // Remove conflicting transactions from the mempool.;
2313 if (m_mempool) {
2314 m_mempool->removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2315 disconnectpool.removeForBlock(blockConnecting.vtx);
2316 }
2317 // Update m_chain & related variables.
2318 m_chain.SetTip(pindexNew);
2319 UpdateTip(pindexNew);
2320
2321 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2322 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2323 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2324
2325 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2326 return true;
2327}
2328
2334 do {
2335 CBlockIndex *pindexNew = nullptr;
2336
2337 // Find the best candidate header.
2338 {
2339 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2340 if (it == setBlockIndexCandidates.rend())
2341 return nullptr;
2342 pindexNew = *it;
2343 }
2344
2345 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2346 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2347 CBlockIndex *pindexTest = pindexNew;
2348 bool fInvalidAncestor = false;
2349 while (pindexTest && !m_chain.Contains(pindexTest)) {
2350 assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0);
2351
2352 // Pruned nodes may have entries in setBlockIndexCandidates for
2353 // which block files have been deleted. Remove those as candidates
2354 // for the most work chain if we come across them; we can't switch
2355 // to a chain unless we have all the non-active-chain parent blocks.
2356 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2357 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2358 if (fFailedChain || fMissingData) {
2359 // Candidate chain is not usable (either invalid or missing data)
2360 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2361 pindexBestInvalid = pindexNew;
2362 CBlockIndex *pindexFailed = pindexNew;
2363 // Remove the entire chain from the set.
2364 while (pindexTest != pindexFailed) {
2365 if (fFailedChain) {
2366 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2367 } else if (fMissingData) {
2368 // If we're missing data, then add back to m_blocks_unlinked,
2369 // so that if the block arrives in the future we can try adding
2370 // to setBlockIndexCandidates again.
2372 std::make_pair(pindexFailed->pprev, pindexFailed));
2373 }
2374 setBlockIndexCandidates.erase(pindexFailed);
2375 pindexFailed = pindexFailed->pprev;
2376 }
2377 setBlockIndexCandidates.erase(pindexTest);
2378 fInvalidAncestor = true;
2379 break;
2380 }
2381 pindexTest = pindexTest->pprev;
2382 }
2383 if (!fInvalidAncestor)
2384 return pindexNew;
2385 } while(true);
2386}
2387
2390 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2391 // reorganization to a better block fails.
2392 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2393 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) {
2394 setBlockIndexCandidates.erase(it++);
2395 }
2396 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2398}
2399
2406bool CChainState::ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2407{
2410
2411 const CBlockIndex* pindexOldTip = m_chain.Tip();
2412 const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);
2413
2414 // Disconnect active blocks which are no longer in the best chain.
2415 bool fBlocksDisconnected = false;
2416 DisconnectedBlockTransactions disconnectpool;
2417 while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
2418 if (!DisconnectTip(state, &disconnectpool)) {
2419 // This is likely a fatal error, but keep the mempool consistent,
2420 // just in case. Only remove from the mempool in this case.
2421 MaybeUpdateMempoolForReorg(disconnectpool, false);
2422
2423 // If we're unable to disconnect a block during normal operation,
2424 // then that is a failure of our local system -- we should abort
2425 // rather than stay on a less work chain.
2426 AbortNode(state, "Failed to disconnect block; see debug.log for details");
2427 return false;
2428 }
2429 fBlocksDisconnected = true;
2430 }
2431
2432 // Build list of new blocks to connect (in descending height order).
2433 std::vector<CBlockIndex*> vpindexToConnect;
2434 bool fContinue = true;
2435 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2436 while (fContinue && nHeight != pindexMostWork->nHeight) {
2437 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2438 // a few blocks along the way.
2439 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2440 vpindexToConnect.clear();
2441 vpindexToConnect.reserve(nTargetHeight - nHeight);
2442 CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2443 while (pindexIter && pindexIter->nHeight != nHeight) {
2444 vpindexToConnect.push_back(pindexIter);
2445 pindexIter = pindexIter->pprev;
2446 }
2447 nHeight = nTargetHeight;
2448
2449 // Connect new blocks.
2450 for (CBlockIndex* pindexConnect : reverse_iterate(vpindexToConnect)) {
2451 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2452 if (state.IsInvalid()) {
2453 // The block violates a consensus rule.
2455 InvalidChainFound(vpindexToConnect.front());
2456 }
2457 state = BlockValidationState();
2458 fInvalidFound = true;
2459 fContinue = false;
2460 break;
2461 } else {
2462 // A system error occurred (disk space, database error, ...).
2463 // Make the mempool consistent with the current tip, just in case
2464 // any observers try to use it before shutdown.
2465 MaybeUpdateMempoolForReorg(disconnectpool, false);
2466 return false;
2467 }
2468 } else {
2470 if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) {
2471 // We're in a better position than we were. Return temporarily to release the lock.
2472 fContinue = false;
2473 break;
2474 }
2475 }
2476 }
2477 }
2478
2479 if (fBlocksDisconnected) {
2480 // If any blocks were disconnected, disconnectpool may be non empty. Add
2481 // any disconnected transactions back to the mempool.
2482 MaybeUpdateMempoolForReorg(disconnectpool, true);
2483 }
2484 if (m_mempool) m_mempool->check(this->CoinsTip(), this->m_chain.Height() + 1);
2485
2487
2488 return true;
2489}
2490
2492{
2496}
2497
2499 bool fNotify = false;
2500 bool fInitialBlockDownload = false;
2501 static CBlockIndex* pindexHeaderOld = nullptr;
2502 CBlockIndex* pindexHeader = nullptr;
2503 {
2504 LOCK(cs_main);
2505 pindexHeader = pindexBestHeader;
2506
2507 if (pindexHeader != pindexHeaderOld) {
2508 fNotify = true;
2509 fInitialBlockDownload = chainstate.IsInitialBlockDownload();
2510 pindexHeaderOld = pindexHeader;
2511 }
2512 }
2513 // Send block tip changed notifications without cs_main
2514 if (fNotify) {
2515 uiInterface.NotifyHeaderTip(GetSynchronizationState(fInitialBlockDownload), pindexHeader);
2516 }
2517 return fNotify;
2518}
2519
2522
2523 if (GetMainSignals().CallbacksPending() > 10) {
2525 }
2526}
2527
2528bool CChainState::ActivateBestChain(BlockValidationState& state, std::shared_ptr<const CBlock> pblock)
2529{
2530 // Note that while we're often called here from ProcessNewBlock, this is
2531 // far from a guarantee. Things in the P2P/RPC will often end up calling
2532 // us in the middle of ProcessNewBlock - do not assume pblock is set
2533 // sanely for performance or correctness!
2535
2536 // ABC maintains a fair degree of expensive-to-calculate internal state
2537 // because this function periodically releases cs_main so that it does not lock up other threads for too long
2538 // during large connects - and to allow for e.g. the callback queue to drain
2539 // we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
2541
2542 CBlockIndex *pindexMostWork = nullptr;
2543 CBlockIndex *pindexNewTip = nullptr;
2544 int nStopAtHeight = gArgs.GetIntArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2545 do {
2546 // Block until the validation queue drains. This should largely
2547 // never happen in normal operation, however may happen during
2548 // reindex, causing memory blowup if we run too far ahead.
2549 // Note that if a validationinterface callback ends up calling
2550 // ActivateBestChain this may lead to a deadlock! We should
2551 // probably have a DEBUG_LOCKORDER test for this in the future.
2553
2554 {
2555 LOCK(cs_main);
2556 // Lock transaction pool for at least as long as it takes for connectTrace to be consumed
2557 LOCK(MempoolMutex());
2558 CBlockIndex* starting_tip = m_chain.Tip();
2559 bool blocks_connected = false;
2560 do {
2561 // We absolutely may not unlock cs_main until we've made forward progress
2562 // (with the exception of shutdown due to hardware issues, low disk space, etc).
2563 ConnectTrace connectTrace; // Destructed before cs_main is unlocked
2564
2565 if (pindexMostWork == nullptr) {
2566 pindexMostWork = FindMostWorkChain();
2567 }
2568
2569 // Whether we have anything to do at all.
2570 if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) {
2571 break;
2572 }
2573
2574 bool fInvalidFound = false;
2575 std::shared_ptr<const CBlock> nullBlockPtr;
2576 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace)) {
2577 // A system error occurred
2578 return false;
2579 }
2580 blocks_connected = true;
2581
2582 if (fInvalidFound) {
2583 // Wipe cache, we may need another branch now.
2584 pindexMostWork = nullptr;
2585 }
2586 pindexNewTip = m_chain.Tip();
2587
2588 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2589 assert(trace.pblock && trace.pindex);
2590 GetMainSignals().BlockConnected(trace.pblock, trace.pindex);
2591 }
2592 } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip)));
2593 if (!blocks_connected) return true;
2594
2595 const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip);
2596 bool fInitialDownload = IsInitialBlockDownload();
2597
2598 // Notify external listeners about the new tip.
2599 // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
2600 if (pindexFork != pindexNewTip) {
2601 // Notify ValidationInterface subscribers
2602 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2603
2604 // Always notify the UI if a new block tip was connected
2605 uiInterface.NotifyBlockTip(GetSynchronizationState(fInitialDownload), pindexNewTip);
2606 }
2607 }
2608 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2609
2610 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2611
2612 // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
2613 // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
2614 // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
2615 // that the best block hash is non-null.
2616 if (ShutdownRequested()) break;
2617 } while (pindexNewTip != pindexMostWork);
2619
2620 // Write changes periodically to disk, after relay.
2622 return false;
2623 }
2624
2625 return true;
2626}
2627
2629{
2630 {
2631 LOCK(cs_main);
2632 if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
2633 // Nothing to do, this block is not at the tip.
2634 return true;
2635 }
2637 // The chain has been extended since the last call, reset the counter.
2639 }
2641 setBlockIndexCandidates.erase(pindex);
2643 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2644 // We can't keep reducing the counter if somebody really wants to
2645 // call preciousblock 2**31-1 times on the same set of tips...
2647 }
2648 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->HaveTxsDownloaded()) {
2649 setBlockIndexCandidates.insert(pindex);
2651 }
2652 }
2653
2654 return ActivateBestChain(state, std::shared_ptr<const CBlock>());
2655}
2656
2658{
2659 // Genesis block can't be invalidated
2660 assert(pindex);
2661 if (pindex->nHeight == 0) return false;
2662
2663 CBlockIndex* to_mark_failed = pindex;
2664 bool pindex_was_in_chain = false;
2665 int disconnected = 0;
2666
2667 // We do not allow ActivateBestChain() to run while InvalidateBlock() is
2668 // running, as that could cause the tip to change while we disconnect
2669 // blocks.
2671
2672 // We'll be acquiring and releasing cs_main below, to allow the validation
2673 // callbacks to run. However, we should keep the block index in a
2674 // consistent state as we disconnect blocks -- in particular we need to
2675 // add equal-work blocks to setBlockIndexCandidates as we disconnect.
2676 // To avoid walking the block index repeatedly in search of candidates,
2677 // build a map once so that we can look up candidate blocks by chain
2678 // work as we go.
2679 std::multimap<const arith_uint256, CBlockIndex *> candidate_blocks_by_work;
2680
2681 {
2682 LOCK(cs_main);
2683 for (const auto& entry : m_blockman.m_block_index) {
2684 CBlockIndex *candidate = entry.second;
2685 // We don't need to put anything in our active chain into the
2686 // multimap, because those candidates will be found and considered
2687 // as we disconnect.
2688 // Instead, consider only non-active-chain blocks that have at
2689 // least as much work as where we expect the new tip to end up.
2690 if (!m_chain.Contains(candidate) &&
2691 !CBlockIndexWorkComparator()(candidate, pindex->pprev) &&
2692 candidate->IsValid(BLOCK_VALID_TRANSACTIONS) &&
2693 candidate->HaveTxsDownloaded()) {
2694 candidate_blocks_by_work.insert(std::make_pair(candidate->nChainWork, candidate));
2695 }
2696 }
2697 }
2698
2699 // Disconnect (descendants of) pindex, and mark them invalid.
2700 while (true) {
2701 if (ShutdownRequested()) break;
2702
2703 // Make sure the queue of validation callbacks doesn't grow unboundedly.
2705
2706 LOCK(cs_main);
2707 // Lock for as long as disconnectpool is in scope to make sure MaybeUpdateMempoolForReorg is
2708 // called after DisconnectTip without unlocking in between
2709 LOCK(MempoolMutex());
2710 if (!m_chain.Contains(pindex)) break;
2711 pindex_was_in_chain = true;
2712 CBlockIndex *invalid_walk_tip = m_chain.Tip();
2713
2714 // ActivateBestChain considers blocks already in m_chain
2715 // unconditionally valid already, so force disconnect away from it.
2716 DisconnectedBlockTransactions disconnectpool;
2717 bool ret = DisconnectTip(state, &disconnectpool);
2718 // DisconnectTip will add transactions to disconnectpool.
2719 // Adjust the mempool to be consistent with the new tip, adding
2720 // transactions back to the mempool if disconnecting was successful,
2721 // and we're not doing a very deep invalidation (in which case
2722 // keeping the mempool up to date is probably futile anyway).
2723 MaybeUpdateMempoolForReorg(disconnectpool, /* fAddToMempool = */ (++disconnected <= 10) && ret);
2724 if (!ret) return false;
2725 assert(invalid_walk_tip->pprev == m_chain.Tip());
2726
2727 // We immediately mark the disconnected blocks as invalid.
2728 // This prevents a case where pruned nodes may fail to invalidateblock
2729 // and be left unable to start as they have no tip candidates (as there
2730 // are no blocks that meet the "have data and are not invalid per
2731 // nStatus" criteria for inclusion in setBlockIndexCandidates).
2732 invalid_walk_tip->nStatus |= BLOCK_FAILED_VALID;
2733 setDirtyBlockIndex.insert(invalid_walk_tip);
2734 setBlockIndexCandidates.erase(invalid_walk_tip);
2735 setBlockIndexCandidates.insert(invalid_walk_tip->pprev);
2736 if (invalid_walk_tip->pprev == to_mark_failed && (to_mark_failed->nStatus & BLOCK_FAILED_VALID)) {
2737 // We only want to mark the last disconnected block as BLOCK_FAILED_VALID; its children
2738 // need to be BLOCK_FAILED_CHILD instead.
2739 to_mark_failed->nStatus = (to_mark_failed->nStatus ^ BLOCK_FAILED_VALID) | BLOCK_FAILED_CHILD;
2740 setDirtyBlockIndex.insert(to_mark_failed);
2741 }
2742
2743 // Add any equal or more work headers to setBlockIndexCandidates
2744 auto candidate_it = candidate_blocks_by_work.lower_bound(invalid_walk_tip->pprev->nChainWork);
2745 while (candidate_it != candidate_blocks_by_work.end()) {
2746 if (!CBlockIndexWorkComparator()(candidate_it->second, invalid_walk_tip->pprev)) {
2747 setBlockIndexCandidates.insert(candidate_it->second);
2748 candidate_it = candidate_blocks_by_work.erase(candidate_it);
2749 } else {
2750 ++candidate_it;
2751 }
2752 }
2753
2754 // Track the last disconnected block, so we can correct its BLOCK_FAILED_CHILD status in future
2755 // iterations, or, if it's the last one, call InvalidChainFound on it.
2756 to_mark_failed = invalid_walk_tip;
2757 }
2758
2760
2761 {
2762 LOCK(cs_main);
2763 if (m_chain.Contains(to_mark_failed)) {
2764 // If the to-be-marked invalid block is in the active chain, something is interfering and we can't proceed.
2765 return false;
2766 }
2767
2768 // Mark pindex (or the last disconnected block) as invalid, even when it never was in the main chain
2769 to_mark_failed->nStatus |= BLOCK_FAILED_VALID;
2770 setDirtyBlockIndex.insert(to_mark_failed);
2771 setBlockIndexCandidates.erase(to_mark_failed);
2772 m_blockman.m_failed_blocks.insert(to_mark_failed);
2773
2774 // If any new blocks somehow arrived while we were disconnecting
2775 // (above), then the pre-calculation of what should go into
2776 // setBlockIndexCandidates may have missed entries. This would
2777 // technically be an inconsistency in the block index, but if we clean
2778 // it up here, this should be an essentially unobservable error.
2779 // Loop back over all block index entries and add any missing entries
2780 // to setBlockIndexCandidates.
2781 BlockMap::iterator it = m_blockman.m_block_index.begin();
2782 while (it != m_blockman.m_block_index.end()) {
2783 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) {
2784 setBlockIndexCandidates.insert(it->second);
2785 }
2786 it++;
2787 }
2788
2789 InvalidChainFound(to_mark_failed);
2790 }
2791
2792 // Only notify about a new block tip if the active chain was modified.
2793 if (pindex_was_in_chain) {
2794 uiInterface.NotifyBlockTip(GetSynchronizationState(IsInitialBlockDownload()), to_mark_failed->pprev);
2795 }
2796 return true;
2797}
2798
2801
2802 int nHeight = pindex->nHeight;
2803
2804 // Remove the invalidity flag from this block and all its descendants.
2805 BlockMap::iterator it = m_blockman.m_block_index.begin();
2806 while (it != m_blockman.m_block_index.end()) {
2807 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2808 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2809 setDirtyBlockIndex.insert(it->second);
2810 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) {
2811 setBlockIndexCandidates.insert(it->second);
2812 }
2813 if (it->second == pindexBestInvalid) {
2814 // Reset invalid block marker if it was pointing to one of those.
2815 pindexBestInvalid = nullptr;
2816 }
2817 m_blockman.m_failed_blocks.erase(it->second);
2818 }
2819 it++;
2820 }
2821
2822 // Remove the invalidity flag from all ancestors too.
2823 while (pindex != nullptr) {
2824 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2825 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2826 setDirtyBlockIndex.insert(pindex);
2827 m_blockman.m_failed_blocks.erase(pindex);
2828 }
2829 pindex = pindex->pprev;
2830 }
2831}
2832
2834{
2836
2837 // Check for duplicate
2838 uint256 hash = block.GetHash();
2839 BlockMap::iterator it = m_block_index.find(hash);
2840 if (it != m_block_index.end())
2841 return it->second;
2842
2843 // Construct new block index object
2844 CBlockIndex* pindexNew = new CBlockIndex(block);
2845 // We assign the sequence id to blocks only when the full data is available,
2846 // to avoid miners withholding blocks but broadcasting headers, to get a
2847 // competitive advantage.
2848 pindexNew->nSequenceId = 0;
2849 BlockMap::iterator mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
2850 pindexNew->phashBlock = &((*mi).first);
2851 BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
2852 if (miPrev != m_block_index.end())
2853 {
2854 pindexNew->pprev = (*miPrev).second;
2855 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2856 pindexNew->BuildSkip();
2857 }
2858 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2859 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2860 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2861 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2862 pindexBestHeader = pindexNew;
2863
2864 setDirtyBlockIndex.insert(pindexNew);
2865
2866 return pindexNew;
2867}
2868
2871{
2872 pindexNew->nTx = block.vtx.size();
2873 pindexNew->nChainTx = 0;
2874 pindexNew->nFile = pos.nFile;
2875 pindexNew->nDataPos = pos.nPos;
2876 pindexNew->nUndoPos = 0;
2877 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2879 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2880 }
2882 setDirtyBlockIndex.insert(pindexNew);
2883
2884 if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveTxsDownloaded()) {
2885 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2886 std::deque<CBlockIndex*> queue;
2887 queue.push_back(pindexNew);
2888
2889 // Recursively process any descendant blocks that now may be eligible to be connected.
2890 while (!queue.empty()) {
2891 CBlockIndex *pindex = queue.front();
2892 queue.pop_front();
2893 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2894 pindex->nSequenceId = nBlockSequenceId++;
2895 if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {
2896 setBlockIndexCandidates.insert(pindex);
2897 }
2898 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);
2899 while (range.first != range.second) {
2900 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2901 queue.push_back(it->second);
2902 range.first++;
2903 m_blockman.m_blocks_unlinked.erase(it);
2904 }
2905 }
2906 } else {
2907 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2908 m_blockman.m_blocks_unlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2909 }
2910 }
2911}
2912
2913static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2914{
2915 // Check proof of work matches claimed amount
2916 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2917 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");
2918
2919 return true;
2920}
2921
2922bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2923{
2924 // These are checks that are independent of context.
2925
2926 if (block.fChecked)
2927 return true;
2928
2929 // Check that the header is valid (particularly PoW). This is mostly
2930 // redundant with the call in AcceptBlockHeader.
2931 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2932 return false;
2933
2934 // Signet only: check block solution
2935 if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {
2936 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");
2937 }
2938
2939 // Check the merkle root.
2940 if (fCheckMerkleRoot) {
2941 bool mutated;
2942 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2943 if (block.hashMerkleRoot != hashMerkleRoot2)
2944 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txnmrklroot", "hashMerkleRoot mismatch");
2945
2946 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2947 // of transactions in a block without affecting the merkle root of a block,
2948 // while still invalidating it.
2949 if (mutated)
2950 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-txns-duplicate", "duplicate transaction");
2951 }
2952
2953 // All potential-corruption validation must be done before we do any
2954 // transaction validation, as otherwise we may mark the header as invalid
2955 // because we receive the wrong transactions for it.
2956 // Note that witness malleability is checked in ContextualCheckBlock, so no
2957 // checks that use witness data may be performed here.
2958
2959 // Size limits
2961 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");
2962
2963 // First transaction must be coinbase, the rest must not be
2964 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2965 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");
2966 for (unsigned int i = 1; i < block.vtx.size(); i++)
2967 if (block.vtx[i]->IsCoinBase())
2968 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");
2969
2970 // Check transactions
2971 // Must check for duplicate inputs (see CVE-2018-17144)
2972 for (const auto& tx : block.vtx) {
2973 TxValidationState tx_state;
2974 if (!CheckTransaction(*tx, tx_state)) {
2975 // CheckBlock() does context-free validation checks. The only
2976 // possible failures are consensus failures.
2979 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));
2980 }
2981 }
2982 unsigned int nSigOps = 0;
2983 for (const auto& tx : block.vtx)
2984 {
2985 nSigOps += GetLegacySigOpCount(*tx);
2986 }
2988 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");
2989
2990 if (fCheckPOW && fCheckMerkleRoot)
2991 block.fChecked = true;
2992
2993 return true;
2994}
2995
2996void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2997{
2998 int commitpos = GetWitnessCommitmentIndex(block);
2999 static const std::vector<unsigned char> nonce(32, 0x00);
3000 if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {
3001 CMutableTransaction tx(*block.vtx[0]);
3002 tx.vin[0].scriptWitness.stack.resize(1);
3003 tx.vin[0].scriptWitness.stack[0] = nonce;
3004 block.vtx[0] = MakeTransactionRef(std::move(tx));
3005 }
3006}
3007
3008std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3009{
3010 std::vector<unsigned char> commitment;
3011 int commitpos = GetWitnessCommitmentIndex(block);
3012 std::vector<unsigned char> ret(32, 0x00);
3013 if (commitpos == NO_WITNESS_COMMITMENT) {
3014 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3015 CHash256().Write(witnessroot).Write(ret).Finalize(witnessroot);
3016 CTxOut out;
3017 out.nValue = 0;
3019 out.scriptPubKey[0] = OP_RETURN;
3020 out.scriptPubKey[1] = 0x24;
3021 out.scriptPubKey[2] = 0xaa;
3022 out.scriptPubKey[3] = 0x21;
3023 out.scriptPubKey[4] = 0xa9;
3024 out.scriptPubKey[5] = 0xed;
3025 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3026 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3027 CMutableTransaction tx(*block.vtx[0]);
3028 tx.vout.push_back(out);
3029 block.vtx[0] = MakeTransactionRef(std::move(tx));
3030 }
3031 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3032 return commitment;
3033}
3034
3036{
3037 const MapCheckpoints& checkpoints = data.mapCheckpoints;
3038
3039 for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
3040 {
3041 const uint256& hash = i.second;
3042 CBlockIndex* pindex = LookupBlockIndex(hash);
3043 if (pindex) {
3044 return pindex;
3045 }
3046 }
3047 return nullptr;
3048}
3049
3059static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
3060{
3061 assert(pindexPrev != nullptr);
3062 const int nHeight = pindexPrev->nHeight + 1;
3063
3064 // Check proof of work
3065 const Consensus::Params& consensusParams = params.GetConsensus();
3066 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3067 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "bad-diffbits", "incorrect proof of work");
3068
3069 // Check against checkpoints
3070 if (fCheckpointsEnabled) {
3071 // Don't accept any forks from the main chain prior to last checkpoint.
3072 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3073 // BlockIndex().
3074 CBlockIndex* pcheckpoint = blockman.GetLastCheckpoint(params.Checkpoints());
3075 if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3076 LogPrintf("ERROR: %s: forked chain older than last checkpoint (height %d)\n", __func__, nHeight);
3077 return state.Invalid(BlockValidationResult::BLOCK_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3078 }
3079 }
3080
3081 // Check timestamp against prev
3082 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3083 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", "block's timestamp is too early");
3084
3085 // Check timestamp
3086 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3087 return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", "block timestamp too far in the future");
3088
3089 // Reject blocks with outdated version
3090 if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_HEIGHTINCB)) ||
3091 (block.nVersion < 3 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_DERSIG)) ||
3092 (block.nVersion < 4 && DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CLTV))) {
3093 return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, strprintf("bad-version(0x%08x)", block.nVersion),
3094 strprintf("rejected nVersion=0x%08x block", block.nVersion));
3095 }
3096
3097 return true;
3098}
3099
3106static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3107{
3108 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3109
3110 // Enforce BIP113 (Median Time Past).
3111 int nLockTimeFlags = 0;
3112 if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV)) {
3113 assert(pindexPrev != nullptr);
3114 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3115 }
3116
3117 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3118 ? pindexPrev->GetMedianTimePast()
3119 : block.GetBlockTime();
3120
3121 // Check that all transactions are finalized
3122 for (const auto& tx : block.vtx) {
3123 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3124 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-nonfinal", "non-final transaction");
3125 }
3126 }
3127
3128 // Enforce rule that the coinbase starts with serialized block height
3129 if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_HEIGHTINCB))
3130 {
3132 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3133 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3134 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-height", "block height mismatch in coinbase");
3135 }
3136 }
3137
3138 // Validation for witness commitments.
3139 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3140 // coinbase (where 0x0000....0000 is used instead).
3141 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness reserved value (unconstrained).
3142 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3143 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3144 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness reserved value). In case there are
3145 // multiple, the last one is used.
3146 bool fHaveWitness = false;
3147 if (DeploymentActiveAfter(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT)) {
3148 int commitpos = GetWitnessCommitmentIndex(block);
3149 if (commitpos != NO_WITNESS_COMMITMENT) {
3150 bool malleated = false;
3151 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3152 // The malleation check is ignored; as the transaction tree itself
3153 // already does not permit it, it is impossible to trigger in the
3154 // witness tree.
3155 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3156 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
3157 }
3158 CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
3159 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3160 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
3161 }
3162 fHaveWitness = true;
3163 }
3164 }
3165
3166 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3167 if (!fHaveWitness) {
3168 for (const auto& tx : block.vtx) {
3169 if (tx->HasWitness()) {
3170 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "unexpected-witness", strprintf("%s : unexpected witness data found", __func__));
3171 }
3172 }
3173 }
3174
3175 // After the coinbase witness reserved value and commitment are verified,
3176 // we can check if the block weight passes (before we've checked the
3177 // coinbase witness, it would be possible for the weight to be too
3178 // large by filling up the coinbase witness, which doesn't change
3179 // the block hash, so we couldn't mark the block as permanently
3180 // failed).
3181 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3182 return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-weight", strprintf("%s : weight limit failed", __func__));
3183 }
3184
3185 return true;
3186}
3187
3188bool BlockManager::AcceptBlockHeader(const CBlockHeader& block, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3189{
3191 // Check for duplicate
3192 uint256 hash = block.GetHash();
3193 BlockMap::iterator miSelf = m_block_index.find(hash);
3194 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3195 if (miSelf != m_block_index.end()) {
3196 // Block header is already known.
3197 CBlockIndex* pindex = miSelf->second;
3198 if (ppindex)
3199 *ppindex = pindex;
3200 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3201 LogPrint(BCLog::VALIDATION, "%s: block %s is marked invalid\n", __func__, hash.ToString());
3202 return state.Invalid(BlockValidationResult::BLOCK_CACHED_INVALID, "duplicate");
3203 }
3204 return true;
3205 }
3206
3207 if (!CheckBlockHeader(block, state, chainparams.GetConsensus())) {
3208 LogPrint(BCLog::VALIDATION, "%s: Consensus::CheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
3209 return false;
3210 }
3211
3212 // Get prev block index
3213 CBlockIndex* pindexPrev = nullptr;
3214 BlockMap::iterator mi = m_block_index.find(block.hashPrevBlock);
3215 if (mi == m_block_index.end()) {
3216 LogPrint(BCLog::VALIDATION, "%s: %s prev block not found\n", __func__, hash.ToString());
3217 return state.Invalid(BlockValidationResult::BLOCK_MISSING_PREV, "prev-blk-not-found");
3218 }
3219 pindexPrev = (*mi).second;
3220 if (pindexPrev->nStatus & BLOCK_FAILED_MASK) {
3221 LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
3222 return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3223 }
3224 if (!ContextualCheckBlockHeader(block, state, *this, chainparams, pindexPrev, GetAdjustedTime())) {
3225 LogPrint(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
3226 return false;
3227 }
3228
3229 /* Determine if this block descends from any block which has been found
3230 * invalid (m_failed_blocks), then mark pindexPrev and any blocks between
3231 * them as failed. For example:
3232 *
3233 * D3
3234 * /
3235 * B2 - C2
3236 * / \
3237 * A D2 - E2 - F2
3238 * \
3239 * B1 - C1 - D1 - E1
3240 *
3241 * In the case that we attempted to reorg from E1 to F2, only to find
3242 * C2 to be invalid, we would mark D2, E2, and F2 as BLOCK_FAILED_CHILD
3243 * but NOT D3 (it was not in any of our candidate sets at the time).
3244 *
3245 * In any case D3 will also be marked as BLOCK_FAILED_CHILD at restart
3246 * in LoadBlockIndex.
3247 */
3248 if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3249 // The above does not mean "invalid": it checks if the previous block
3250 // hasn't been validated up to BLOCK_VALID_SCRIPTS. This is a performance
3251 // optimization, in the common case of adding a new block to the tip,
3252 // we don't need to iterate over the failed blocks list.
3253 for (const CBlockIndex* failedit : m_failed_blocks) {
3254 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3255 assert(failedit->nStatus & BLOCK_FAILED_VALID);
3256 CBlockIndex* invalid_walk = pindexPrev;
3257 while (invalid_walk != failedit) {
3258 invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3259 setDirtyBlockIndex.insert(invalid_walk);
3260 invalid_walk = invalid_walk->pprev;
3261 }
3262 LogPrint(BCLog::VALIDATION, "%s: %s prev block invalid\n", __func__, hash.ToString());
3263 return state.Invalid(BlockValidationResult::BLOCK_INVALID_PREV, "bad-prevblk");
3264 }
3265 }
3266 }
3267 }
3268 CBlockIndex* pindex = AddToBlockIndex(block);
3269
3270 if (ppindex)
3271 *ppindex = pindex;
3272
3273 return true;
3274}
3275
3276// Exposed wrapper for AcceptBlockHeader
3277bool ChainstateManager::ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3278{
3280 {
3281 LOCK(cs_main);
3282 for (const CBlockHeader& header : headers) {
3283 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3284 bool accepted = m_blockman.AcceptBlockHeader(
3285 header, state, chainparams, &pindex);
3287
3288 if (!accepted) {
3289 return false;
3290 }
3291 if (ppindex) {
3292 *ppindex = pindex;
3293 }
3294 }
3295 }
3297 if (ActiveChainstate().IsInitialBlockDownload() && ppindex && *ppindex) {
3298 LogPrintf("Synchronizing blockheaders, height: %d (~%.2f%%)\n", (*ppindex)->nHeight, 100.0/((*ppindex)->nHeight+(GetAdjustedTime() - (*ppindex)->GetBlockTime()) / Params().GetConsensus().nPowTargetSpacing) * (*ppindex)->nHeight);
3299 }
3300 }
3301 return true;
3302}
3303
3305bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock)
3306{
3307 const CBlock& block = *pblock;
3308
3309 if (fNewBlock) *fNewBlock = false;
3311
3312 CBlockIndex *pindexDummy = nullptr;
3313 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3314
3315 bool accepted_header = m_blockman.AcceptBlockHeader(block, state, m_params, &pindex);
3317
3318 if (!accepted_header)
3319 return false;
3320
3321 // Try to process all requested blocks that we don't have, but only
3322 // process an unrequested block if it's new and has enough work to
3323 // advance our tip, and isn't too many blocks ahead.
3324 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3325 bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
3326 // Blocks that are too out-of-order needlessly limit the effectiveness of
3327 // pruning, because pruning will not delete block files that contain any
3328 // blocks which are too close in height to the tip. Apply this test
3329 // regardless of whether pruning is enabled; it should generally be safe to
3330 // not process unrequested blocks.
3331 bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP));
3332
3333 // TODO: Decouple this function from the block download logic by removing fRequested
3334 // This requires some new chain data structure to efficiently look up if a
3335 // block is in a chain leading to a candidate for best tip, despite not
3336 // being such a candidate itself.
3337
3338 // TODO: deal better with return value and error conditions for duplicate
3339 // and unrequested blocks.
3340 if (fAlreadyHave) return true;
3341 if (!fRequested) { // If we didn't ask for it:
3342 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3343 if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3344 if (fTooFarAhead) return true; // Block height is too high
3345
3346 // Protect against DoS attacks from low-work chains.
3347 // If our tip is behind, a peer could try to send us
3348 // low-work blocks on a fake chain that we would never
3349 // request; don't process these.
3350 if (pindex->nChainWork < nMinimumChainWork) return true;
3351 }
3352
3353 if (!CheckBlock(block, state, m_params.GetConsensus()) ||
3354 !ContextualCheckBlock(block, state, m_params.GetConsensus(), pindex->pprev)) {
3355 if (state.IsInvalid() && state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
3356 pindex->nStatus |= BLOCK_FAILED_VALID;
3357 setDirtyBlockIndex.insert(pindex);
3358 }
3359 return error("%s: %s", __func__, state.ToString());
3360 }
3361
3362 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3363 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3364 if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev)
3365 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3366
3367 // Write block to history file
3368 if (fNewBlock) *fNewBlock = true;
3369 try {
3370 FlatFilePos blockPos = SaveBlockToDisk(block, pindex->nHeight, m_chain, m_params, dbp);
3371 if (blockPos.IsNull()) {
3372 state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3373 return false;
3374 }
3375 ReceivedBlockTransactions(block, pindex, blockPos);
3376 } catch (const std::runtime_error& e) {
3377 return AbortNode(state, std::string("System error: ") + e.what());
3378 }
3379
3381
3383
3384 return true;
3385}
3386
3387bool ChainstateManager::ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock>& block, bool force_processing, bool* new_block)
3388{
3390
3391 {
3392 CBlockIndex *pindex = nullptr;
3393 if (new_block) *new_block = false;
3395
3396 // CheckBlock() does not support multi-threaded block validation because CBlock::fChecked can cause data race.
3397 // Therefore, the following critical section must include the CheckBlock() call as well.
3398 LOCK(cs_main);
3399
3400 // Skipping AcceptBlock() for CheckBlock() failures means that we will never mark a block as invalid if
3401 // CheckBlock() fails. This is protective against consensus failure if there are any unknown forms of block
3402 // malleability that cause CheckBlock() to fail; see e.g. CVE-2012-2459 and
3403 // https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2019-February/016697.html. Because CheckBlock() is
3404 // not very expensive, the anti-DoS benefits of caching failure (of a definitely-invalid block) are not substantial.
3405 bool ret = CheckBlock(*block, state, chainparams.GetConsensus());
3406 if (ret) {
3407 // Store to disk
3408 ret = ActiveChainstate().AcceptBlock(block, state, &pindex, force_processing, nullptr, new_block);
3409 }
3410 if (!ret) {
3411 GetMainSignals().BlockChecked(*block, state);
3412 return error("%s: AcceptBlock FAILED (%s)", __func__, state.ToString());
3413 }
3414 }
3415
3417
3418 BlockValidationState state; // Only used to report errors, not invalidity - ignore it
3419 if (!ActiveChainstate().ActivateBestChain(state, block)) {
3420 return error("%s: ActivateBestChain failed (%s)", __func__, state.ToString());
3421 }
3422
3423 return true;
3424}
3425
3427 const CChainParams& chainparams,
3428 CChainState& chainstate,
3429 const CBlock& block,
3430 CBlockIndex* pindexPrev,
3431 bool fCheckPOW,
3432 bool fCheckMerkleRoot)
3433{
3435 assert(pindexPrev && pindexPrev == chainstate.m_chain.Tip());
3436 CCoinsViewCache viewNew(&chainstate.CoinsTip());
3437 uint256 block_hash(block.GetHash());
3438 CBlockIndex indexDummy(block);
3439 indexDummy.pprev = pindexPrev;
3440 indexDummy.nHeight = pindexPrev->nHeight + 1;
3441 indexDummy.phashBlock = &block_hash;
3442
3443 // NOTE: CheckBlockHeader is called by CheckBlock
3444 if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainparams, pindexPrev, GetAdjustedTime()))
3445 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
3446 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3447 return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
3448 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3449 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, state.ToString());
3450 if (!chainstate.ConnectBlock(block, state, &indexDummy, viewNew, true)) {
3451 return false;
3452 }
3453 assert(state.IsValid());
3454
3455 return true;
3456}
3457
3462void BlockManager::PruneOneBlockFile(const int fileNumber)
3463{
3466
3467 for (const auto& entry : m_block_index) {
3468 CBlockIndex* pindex = entry.second;
3469 if (pindex->nFile == fileNumber) {
3470 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3471 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3472 pindex->nFile = 0;
3473 pindex->nDataPos = 0;
3474 pindex->nUndoPos = 0;
3475 setDirtyBlockIndex.insert(pindex);
3476
3477 // Prune from m_blocks_unlinked -- any block we prune would have
3478 // to be downloaded again in order to consider its chain, at which
3479 // point it would be considered as a candidate for
3480 // m_blocks_unlinked or setBlockIndexCandidates.
3481 auto range = m_blocks_unlinked.equal_range(pindex->pprev);
3482 while (range.first != range.second) {
3483 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3484 range.first++;
3485 if (_it->second == pindex) {
3486 m_blocks_unlinked.erase(_it);
3487 }
3488 }
3489 }
3490 }
3491
3492 vinfoBlockFile[fileNumber].SetNull();
3493 setDirtyFileInfo.insert(fileNumber);
3494}
3495
3496void BlockManager::FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
3497{
3498 assert(fPruneMode && nManualPruneHeight > 0);
3499
3501 if (chain_tip_height < 0) {
3502 return;
3503 }
3504
3505 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3506 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP);
3507 int count = 0;
3508 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3509 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
3510 continue;
3511 }
3512 PruneOneBlockFile(fileNumber);
3513 setFilesToPrune.insert(fileNumber);
3514 count++;
3515 }
3516 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3517}
3518
3519/* This function is called from the RPC code for pruneblockchain */
3520void PruneBlockFilesManual(CChainState& active_chainstate, int nManualPruneHeight)
3521{
3523 if (!active_chainstate.FlushStateToDisk(
3524 state, FlushStateMode::NONE, nManualPruneHeight)) {
3525 LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
3526 }
3527}
3528
3529void BlockManager::FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
3530{
3532 if (chain_tip_height < 0 || nPruneTarget == 0) {
3533 return;
3534 }
3535 if ((uint64_t)chain_tip_height <= nPruneAfterHeight) {
3536 return;
3537 }
3538
3539 unsigned int nLastBlockWeCanPrune = std::min(prune_height, chain_tip_height - static_cast<int>(MIN_BLOCKS_TO_KEEP));
3540 uint64_t nCurrentUsage = CalculateCurrentUsage();
3541 // We don't check to prune until after we've allocated new space for files
3542 // So we should leave a buffer under our target to account for another allocation
3543 // before the next pruning.
3544 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3545 uint64_t nBytesToPrune;
3546 int count = 0;
3547
3548 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3549 // On a prune event, the chainstate DB is flushed.
3550 // To avoid excessive prune events negating the benefit of high dbcache
3551 // values, we should not prune too rapidly.
3552 // So when pruning in IBD, increase the buffer a bit to avoid a re-prune too soon.
3553 if (is_ibd) {
3554 // Since this is only relevant during IBD, we use a fixed 10%
3555 nBuffer += nPruneTarget / 10;
3556 }
3557
3558 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3559 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3560
3561 if (vinfoBlockFile[fileNumber].nSize == 0) {
3562 continue;
3563 }
3564
3565 if (nCurrentUsage + nBuffer < nPruneTarget) { // are we below our target?
3566 break;
3567 }
3568
3569 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3570 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
3571 continue;
3572 }
3573
3574 PruneOneBlockFile(fileNumber);
3575 // Queue up the files for removal
3576 setFilesToPrune.insert(fileNumber);
3577 nCurrentUsage -= nBytesToPrune;
3578 count++;
3579 }
3580 }
3581
3582 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3583 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3584 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3585 nLastBlockWeCanPrune, count);
3586}
3587
3589{
3591
3592 if (hash.IsNull())
3593 return nullptr;
3594
3595 // Return existing
3596 BlockMap::iterator mi = m_block_index.find(hash);
3597 if (mi != m_block_index.end())
3598 return (*mi).second;
3599
3600 // Create new
3601 CBlockIndex* pindexNew = new CBlockIndex();
3602 mi = m_block_index.insert(std::make_pair(hash, pindexNew)).first;
3603 pindexNew->phashBlock = &((*mi).first);
3604
3605 return pindexNew;
3606}
3607
3609 const Consensus::Params& consensus_params,
3610 std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
3611{
3612 if (!m_block_tree_db->LoadBlockIndexGuts(consensus_params, [this](const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return this->InsertBlockIndex(hash); })) {
3613 return false;
3614 }
3615
3616 // Calculate nChainWork
3617 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3618 vSortedByHeight.reserve(m_block_index.size());
3619 for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index)
3620 {
3621 CBlockIndex* pindex = item.second;
3622 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3623 }
3624 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3625 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3626 {
3627 if (ShutdownRequested()) return false;
3628 CBlockIndex* pindex = item.second;
3629 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3630 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3631 // We can link the chain of blocks for which we've received transactions at some point.
3632 // Pruned nodes may have deleted the block.
3633 if (pindex->nTx > 0) {
3634 if (pindex->pprev) {
3635 if (pindex->pprev->HaveTxsDownloaded()) {
3636 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3637 } else {
3638 pindex->nChainTx = 0;
3639 m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
3640 }
3641 } else {
3642 pindex->nChainTx = pindex->nTx;
3643 }
3644 }
3645 if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
3646 pindex->nStatus |= BLOCK_FAILED_CHILD;
3647 setDirtyBlockIndex.insert(pindex);
3648 }
3649 if (pindex->IsAssumedValid() ||
3651 (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
3652 block_index_candidates.insert(pindex);
3653 }
3654 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3655 pindexBestInvalid = pindex;
3656 if (pindex->pprev)
3657 pindex->BuildSkip();
3658 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3659 pindexBestHeader = pindex;
3660 }
3661
3662 return true;
3663}
3664
3666 m_failed_blocks.clear();
3667 m_blocks_unlinked.clear();
3668
3669 for (const BlockMap::value_type& entry : m_block_index) {
3670 delete entry.second;
3671 }
3672
3673 m_block_index.clear();
3674}
3675
3676bool BlockManager::LoadBlockIndexDB(std::set<CBlockIndex*, CBlockIndexWorkComparator>& setBlockIndexCandidates)
3677{
3678 if (!LoadBlockIndex(
3679 ::Params().GetConsensus(),
3680 setBlockIndexCandidates)) {
3681 return false;
3682 }
3683
3684 // Load block file info
3685 m_block_tree_db->ReadLastBlockFile(nLastBlockFile);
3686 vinfoBlockFile.resize(nLastBlockFile + 1);
3687 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3688 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3689 m_block_tree_db->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3690 }
3691 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3692 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3693 CBlockFileInfo info;
3694 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
3695 vinfoBlockFile.push_back(info);
3696 } else {
3697 break;
3698 }
3699 }
3700
3701 // Check presence of blk files
3702 LogPrintf("Checking all blk files are present...\n");
3703 std::set<int> setBlkDataFiles;
3704 for (const std::pair<const uint256, CBlockIndex*>& item : m_block_index) {
3705 CBlockIndex* pindex = item.second;
3706 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3707 setBlkDataFiles.insert(pindex->nFile);
3708 }
3709 }
3710 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3711 {
3712 FlatFilePos pos(*it, 0);
3713 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3714 return false;
3715 }
3716 }
3717
3718 // Check whether we have ever pruned block & undo files
3719 m_block_tree_db->ReadFlag("prunedblockfiles", fHavePruned);
3720 if (fHavePruned)
3721 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3722
3723 // Check whether we need to continue reindexing
3724 bool fReindexing = false;
3725 m_block_tree_db->ReadReindexing(fReindexing);
3726 if(fReindexing) fReindex = true;
3727
3728 return true;
3729}
3730
3732{
3733 if (!m_mempool) return;
3734 if (args.GetBoolArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
3735 ::LoadMempool(*m_mempool, *this);
3736 }
3738}
3739
3741{
3743 const CCoinsViewCache& coins_cache = CoinsTip();
3744 assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
3745 const CBlockIndex* tip = m_chain.Tip();
3746
3747 if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
3748 return true;
3749 }
3750
3751 // Load pointer to end of best chain
3752 CBlockIndex* pindex = m_blockman.LookupBlockIndex(coins_cache.GetBestBlock());
3753 if (!pindex) {
3754 return false;
3755 }
3756 m_chain.SetTip(pindex);
3758
3759 tip = m_chain.Tip();
3760 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3761 tip->GetBlockHash().ToString(),
3762 m_chain.Height(),
3765 return true;
3766}
3767
3769{
3770 uiInterface.ShowProgress(_("Verifying blocks…").translated, 0, false);
3771}
3772
3774{
3775 uiInterface.ShowProgress("", 100, false);
3776}
3777
3779 CChainState& chainstate,
3780 const CChainParams& chainparams,
3781 CCoinsView& coinsview,
3782 int nCheckLevel, int nCheckDepth)
3783{
3785
3786 if (chainstate.m_chain.Tip() == nullptr || chainstate.m_chain.Tip()->pprev == nullptr)
3787 return true;
3788
3789 // Verify blocks in the best chain
3790 if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height())
3791 nCheckDepth = chainstate.m_chain.Height();
3792 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3793 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3794 CCoinsViewCache coins(&coinsview);
3795 CBlockIndex* pindex;
3796 CBlockIndex* pindexFailure = nullptr;
3797 int nGoodTransactions = 0;
3799 int reportDone = 0;
3800 LogPrintf("[0%%]..."); /* Continued */
3801
3802 const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};
3803
3804 for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
3805 const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3806 if (reportDone < percentageDone/10) {
3807 // report every 10% step
3808 LogPrintf("[%d%%]...", percentageDone); /* Continued */
3809 reportDone = percentageDone/10;
3810 }
3811 uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
3812 if (pindex->nHeight <= chainstate.m_chain.Height()-nCheckDepth)
3813 break;
3814 if ((fPruneMode || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3815 // If pruning or running under an assumeutxo snapshot, only go
3816 // back as far as we have data.
3817 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3818 break;
3819 }
3820 CBlock block;
3821 // check level 0: read from disk
3822 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3823 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3824 // check level 1: verify block validity
3825 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3826 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3827 pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
3828 // check level 2: verify undo validity
3829 if (nCheckLevel >= 2 && pindex) {
3830 CBlockUndo undo;
3831 if (!pindex->GetUndoPos().IsNull()) {
3832 if (!UndoReadFromDisk(undo, pindex)) {
3833 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3834 }
3835 }
3836 }
3837 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3838 size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();
3839
3840 if (nCheckLevel >= 3 && curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
3841 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3842 DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
3843 if (res == DISCONNECT_FAILED) {
3844 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3845 }
3846 if (res == DISCONNECT_UNCLEAN) {
3847 nGoodTransactions = 0;
3848 pindexFailure = pindex;
3849 } else {
3850 nGoodTransactions += block.vtx.size();
3851 }
3852 }
3853 if (ShutdownRequested()) return true;
3854 }
3855 if (pindexFailure)
3856 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3857
3858 // store block count as we move pindex at check level >= 4
3859 int block_count = chainstate.m_chain.Height() - pindex->nHeight;
3860
3861 // check level 4: try reconnecting blocks
3862 if (nCheckLevel >= 4) {
3863 while (pindex != chainstate.m_chain.Tip()) {
3864 const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
3865 if (reportDone < percentageDone/10) {
3866 // report every 10% step
3867 LogPrintf("[%d%%]...", percentageDone); /* Continued */
3868 reportDone = percentageDone/10;
3869 }
3870 uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
3871 pindex = chainstate.m_chain.Next(pindex);
3872 CBlock block;
3873 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3874 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3875 if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
3876 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
3877 }
3878 if (ShutdownRequested()) return true;
3879 }
3880 }
3881
3882 LogPrintf("[DONE].\n");
3883 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", block_count, nGoodTransactions);
3884
3885 return true;
3886}
3887
3890{
3891 // TODO: merge with ConnectBlock
3892 CBlock block;
3893 if (!ReadBlockFromDisk(block, pindex, m_params.GetConsensus())) {
3894 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3895 }
3896
3897 for (const CTransactionRef& tx : block.vtx) {
3898 if (!tx->IsCoinBase()) {
3899 for (const CTxIn &txin : tx->vin) {
3900 inputs.SpendCoin(txin.prevout);
3901 }
3902 }
3903 // Pass check = true as every addition may be an overwrite.
3904 AddCoins(inputs, *tx, pindex->nHeight, true);
3905 }
3906 return true;
3907}
3908
3910{
3911 LOCK(cs_main);
3912
3913 CCoinsView& db = this->CoinsDB();
3914 CCoinsViewCache cache(&db);
3915
3916 std::vector<uint256> hashHeads = db.GetHeadBlocks();
3917 if (hashHeads.empty()) return true; // We're already in a consistent state.
3918 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3919
3920 uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, false);
3921 LogPrintf("Replaying blocks\n");
3922
3923 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3924 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3925 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3926
3927 if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
3928 return error("ReplayBlocks(): reorganization to unknown block requested");
3929 }
3930 pindexNew = m_blockman.m_block_index[hashHeads[0]];
3931
3932 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3933 if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
3934 return error("ReplayBlocks(): reorganization from unknown block requested");
3935 }
3936 pindexOld = m_blockman.m_block_index[hashHeads[1]];
3937 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3938 assert(pindexFork != nullptr);
3939 }
3940
3941 // Rollback along the old branch.
3942 while (pindexOld != pindexFork) {
3943 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3944 CBlock block;
3945 if (!ReadBlockFromDisk(block, pindexOld, m_params.GetConsensus())) {
3946 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3947 }
3948 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3949 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3950 if (res == DISCONNECT_FAILED) {
3951 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3952 }
3953 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3954 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3955 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3956 // the result is still a version of the UTXO set with the effects of that block undone.
3957 }
3958 pindexOld = pindexOld->pprev;
3959 }
3960
3961 // Roll forward from the forking point to the new tip.
3962 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3963 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3964 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3965 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3966 uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
3967 if (!RollforwardBlock(pindex, cache)) return false;
3968 }
3969
3970 cache.SetBestBlock(pindexNew->GetBlockHash());
3971 cache.Flush();
3972 uiInterface.ShowProgress("", 100, false);
3973 return true;
3974}
3975
3977{
3979
3980 // At and above m_params.SegwitHeight, segwit consensus rules must be validated
3981 CBlockIndex* block{m_chain.Tip()};
3982
3983 while (block != nullptr && DeploymentActiveAt(*block, m_params.GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
3984 if (!(block->nStatus & BLOCK_OPT_WITNESS)) {
3985 // block is insufficiently validated for a segwit client
3986 return true;
3987 }
3988 block = block->pprev;
3989 }
3990
3991 return false;
3992}
3993
3995 nBlockSequenceId = 1;
3997}
3998
3999// May NOT be used after any connections are up as much
4000// of the peer-processing logic assumes a consistent
4001// block index state
4003{
4004 LOCK(cs_main);
4005 chainman.Unload();
4006 pindexBestInvalid = nullptr;
4007 pindexBestHeader = nullptr;
4008 if (mempool) mempool->clear();
4009 vinfoBlockFile.clear();
4010 nLastBlockFile = 0;
4011 setDirtyBlockIndex.clear();
4012 setDirtyFileInfo.clear();
4014 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
4015 warningcache[b].clear();
4016 }
4017 fHavePruned = false;
4018}
4019
4021{
4023 // Load block index from databases
4024 bool needs_init = fReindex;
4025 if (!fReindex) {
4026 bool ret = m_blockman.LoadBlockIndexDB(ActiveChainstate().setBlockIndexCandidates);
4027 if (!ret) return false;
4028 needs_init = m_blockman.m_block_index.empty();
4029 }
4030
4031 if (needs_init) {
4032 // Everything here is for *new* reindex/DBs. Thus, though
4033 // LoadBlockIndexDB may have set fReindex if we shut down
4034 // mid-reindex previously, we don't check fReindex and
4035 // instead only check it prior to LoadBlockIndexDB to set
4036 // needs_init.
4037
4038 LogPrintf("Initializing databases...\n");
4039 }
4040 return true;
4041}
4042
4044{
4045 LOCK(cs_main);
4046
4047 // Check whether we're already initialized by checking for genesis in
4048 // m_blockman.m_block_index. Note that we can't use m_chain here, since it is
4049 // set based on the coins db, not the block index db, which is the only
4050 // thing loaded at this point.
4051 if (m_blockman.m_block_index.count(m_params.GenesisBlock().GetHash()))
4052 return true;
4053
4054 try {
4055 const CBlock& block = m_params.GenesisBlock();
4056 FlatFilePos blockPos = SaveBlockToDisk(block, 0, m_chain, m_params, nullptr);
4057 if (blockPos.IsNull())
4058 return error("%s: writing genesis block to disk failed", __func__);
4059 CBlockIndex *pindex = m_blockman.AddToBlockIndex(block);
4060 ReceivedBlockTransactions(block, pindex, blockPos);
4061 } catch (const std::runtime_error& e) {
4062 return error("%s: failed to write genesis block: %s", __func__, e.what());
4063 }
4064
4065 return true;
4066}
4067
4069{
4070 // Map of disk positions for blocks with unknown parent (only used for reindex)
4071 static std::multimap<uint256, FlatFilePos> mapBlocksUnknownParent;
4072 int64_t nStart = GetTimeMillis();
4073
4074 int nLoaded = 0;
4075 try {
4076 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4078 uint64_t nRewind = blkdat.GetPos();
4079 while (!blkdat.eof()) {
4080 if (ShutdownRequested()) return;
4081
4082 blkdat.SetPos(nRewind);
4083 nRewind++; // start one byte further next time, in case of failure
4084 blkdat.SetLimit(); // remove former limit
4085 unsigned int nSize = 0;
4086 try {
4087 // locate a header
4088 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4089 blkdat.FindByte(m_params.MessageStart()[0]);
4090 nRewind = blkdat.GetPos()+1;
4091 blkdat >> buf;
4093 continue;
4094 }
4095 // read size
4096 blkdat >> nSize;
4097 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4098 continue;
4099 } catch (const std::exception&) {
4100 // no valid block header found; don't complain
4101 break;
4102 }
4103 try {
4104 // read block
4105 uint64_t nBlockPos = blkdat.GetPos();
4106 if (dbp)
4107 dbp->nPos = nBlockPos;
4108 blkdat.SetLimit(nBlockPos + nSize);
4109 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4110 CBlock& block = *pblock;
4111 blkdat >> block;
4112 nRewind = blkdat.GetPos();
4113
4114 uint256 hash = block.GetHash();
4115 {
4116 LOCK(cs_main);
4117 // detect out of order blocks, and store them for later
4119 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4120 block.hashPrevBlock.ToString());
4121 if (dbp)
4122 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4123 continue;
4124 }
4125
4126 // process in case the block isn't known yet
4127 CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
4128 if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
4130 if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr)) {
4131 nLoaded++;
4132 }
4133 if (state.IsError()) {
4134 break;
4135 }
4136 } else if (hash != m_params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
4137 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
4138 }
4139 }
4140
4141 // Activate the genesis block so normal node progress can continue
4142 if (hash == m_params.GetConsensus().hashGenesisBlock) {
4144 if (!ActivateBestChain(state, nullptr)) {
4145 break;
4146 }
4147 }
4148
4149 NotifyHeaderTip(*this);
4150
4151 // Recursively process earlier encountered successors of this block
4152 std::deque<uint256> queue;
4153 queue.push_back(hash);
4154 while (!queue.empty()) {
4155 uint256 head = queue.front();
4156 queue.pop_front();
4157 std::pair<std::multimap<uint256, FlatFilePos>::iterator, std::multimap<uint256, FlatFilePos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4158 while (range.first != range.second) {
4159 std::multimap<uint256, FlatFilePos>::iterator it = range.first;
4160 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4161 if (ReadBlockFromDisk(*pblockrecursive, it->second, m_params.GetConsensus())) {
4162 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4163 head.ToString());
4164 LOCK(cs_main);
4166 if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr)) {
4167 nLoaded++;
4168 queue.push_back(pblockrecursive->GetHash());
4169 }
4170 }
4171 range.first++;
4172 mapBlocksUnknownParent.erase(it);
4173 NotifyHeaderTip(*this);
4174 }
4175 }
4176 } catch (const std::exception& e) {
4177 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4178 }
4179 }
4180 } catch (const std::runtime_error& e) {
4181 AbortNode(std::string("System error: ") + e.what());
4182 }
4183 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4184}
4185
4187{
4188 if (!fCheckBlockIndex) {
4189 return;
4190 }
4191
4192 LOCK(cs_main);
4193
4194 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4195 // so we have the genesis block in m_blockman.m_block_index but no active chain. (A few of the
4196 // tests when iterating the block tree require that m_chain has been initialized.)
4197 if (m_chain.Height() < 0) {
4198 assert(m_blockman.m_block_index.size() <= 1);
4199 return;
4200 }
4201
4202 // Build forward-pointing map of the entire block tree.
4203 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4204 for (const std::pair<const uint256, CBlockIndex*>& entry : m_blockman.m_block_index) {
4205 forward.insert(std::make_pair(entry.second->pprev, entry.second));
4206 }
4207
4208 assert(forward.size() == m_blockman.m_block_index.size());
4209
4210 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4211 CBlockIndex *pindex = rangeGenesis.first->second;
4212 rangeGenesis.first++;
4213 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4214
4215 // Iterate over the entire block tree, using depth-first search.
4216 // Along the way, remember whether there are blocks on the path from genesis
4217 // block being explored which are the first to have certain properties.
4218 size_t nNodes = 0;
4219 int nHeight = 0;
4220 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4221 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4222 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4223 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4224 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4225 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4226 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4227 while (pindex != nullptr) {
4228 nNodes++;
4229 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4230 // Assumed-valid index entries will not have data since we haven't downloaded the
4231 // full block yet.
4232 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA) && !pindex->IsAssumedValid()) {
4233 pindexFirstMissing = pindex;
4234 }
4235 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4236 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4237
4238 if (pindex->pprev != nullptr && !pindex->IsAssumedValid()) {
4239 // Skip validity flag checks for BLOCK_ASSUMED_VALID index entries, since these
4240 // *_VALID_MASK flags will not be present for index entries we are temporarily assuming
4241 // valid.
4242 if (pindexFirstNotTransactionsValid == nullptr &&
4244 pindexFirstNotTransactionsValid = pindex;
4245 }
4246
4247 if (pindexFirstNotChainValid == nullptr &&
4249 pindexFirstNotChainValid = pindex;
4250 }
4251
4252 if (pindexFirstNotScriptsValid == nullptr &&
4254 pindexFirstNotScriptsValid = pindex;
4255 }
4256 }
4257
4258 // Begin: actual consistency checks.
4259 if (pindex->pprev == nullptr) {
4260 // Genesis block checks.
4261 assert(pindex->GetBlockHash() == m_params.GetConsensus().hashGenesisBlock); // Genesis block's hash must match.
4262 assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block.
4263 }
4264 if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4265 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4266 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4267 // Unless these indexes are assumed valid and pending block download on a
4268 // background chainstate.
4269 if (!fHavePruned && !pindex->IsAssumedValid()) {
4270 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4271 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4272 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4273 } else {
4274 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4275 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4276 }
4277 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4278 if (pindex->IsAssumedValid()) {
4279 // Assumed-valid blocks should have some nTx value.
4280 assert(pindex->nTx > 0);
4281 // Assumed-valid blocks should connect to the main chain.
4283 } else {
4284 // Otherwise there should only be an nTx value if we have
4285 // actually seen a block's transactions.
4286 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4287 }
4288 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to HaveTxsDownloaded().
4289 assert((pindexFirstNeverProcessed == nullptr) == pindex->HaveTxsDownloaded());
4290 assert((pindexFirstNotTransactionsValid == nullptr) == pindex->HaveTxsDownloaded());
4291 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4292 assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4293 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4294 assert(pindexFirstNotTreeValid == nullptr); // All m_blockman.m_block_index entries must at least be TREE valid
4295 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4296 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4297 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4298 if (pindexFirstInvalid == nullptr) {
4299 // Checks for not-invalid blocks.
4300 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4301 }
4302 if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) {
4303 if (pindexFirstInvalid == nullptr) {
4304 const bool is_active = this == &m_chainman.ActiveChainstate();
4305
4306 // If this block sorts at least as good as the current tip and
4307 // is valid and we have all data for its parents, it must be in
4308 // setBlockIndexCandidates. m_chain.Tip() must also be there
4309 // even if some data has been pruned.
4310 //
4311 // Don't perform this check for the background chainstate since
4312 // its setBlockIndexCandidates shouldn't have some entries (i.e. those past the
4313 // snapshot block) which do exist in the block index for the active chainstate.
4314 if (is_active && (pindexFirstMissing == nullptr || pindex == m_chain.Tip())) {
4315 assert(setBlockIndexCandidates.count(pindex));
4316 }
4317 // If some parent is missing, then it could be that this block was in
4318 // setBlockIndexCandidates but had to be removed because of the missing data.
4319 // In this case it must be in m_blocks_unlinked -- see test below.
4320 }
4321 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4322 assert(setBlockIndexCandidates.count(pindex) == 0);
4323 }
4324 // Check whether this block is in m_blocks_unlinked.
4325 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = m_blockman.m_blocks_unlinked.equal_range(pindex->pprev);
4326 bool foundInUnlinked = false;
4327 while (rangeUnlinked.first != rangeUnlinked.second) {
4328 assert(rangeUnlinked.first->first == pindex->pprev);
4329 if (rangeUnlinked.first->second == pindex) {
4330 foundInUnlinked = true;
4331 break;
4332 }
4333 rangeUnlinked.first++;
4334 }
4335 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4336 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in m_blocks_unlinked.
4337 assert(foundInUnlinked);
4338 }
4339 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in m_blocks_unlinked if we don't HAVE_DATA
4340 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in m_blocks_unlinked.
4341 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4342 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4343 assert(fHavePruned); // We must have pruned.
4344 // This block may have entered m_blocks_unlinked if:
4345 // - it has a descendant that at some point had more work than the
4346 // tip, and
4347 // - we tried switching to that descendant but were missing
4348 // data for some intermediate block between m_chain and the
4349 // tip.
4350 // So if this block is itself better than m_chain.Tip() and it wasn't in
4351 // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
4352 if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4353 if (pindexFirstInvalid == nullptr) {
4354 assert(foundInUnlinked);
4355 }
4356 }
4357 }
4358 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4359 // End: actual consistency checks.
4360
4361 // Try descending into the first subnode.
4362 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4363 if (range.first != range.second) {
4364 // A subnode was found.
4365 pindex = range.first->second;
4366 nHeight++;
4367 continue;
4368 }
4369 // This is a leaf node.
4370 // Move upwards until we reach a node of which we have not yet visited the last child.
4371 while (pindex) {
4372 // We are going to either move to a parent or a sibling of pindex.
4373 // If pindex was the first with a certain property, unset the corresponding variable.
4374 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4375 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4376 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4377 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4378 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4379 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4380 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4381 // Find our parent.
4382 CBlockIndex* pindexPar = pindex->pprev;
4383 // Find which child we just visited.
4384 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4385 while (rangePar.first->second != pindex) {
4386 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4387 rangePar.first++;
4388 }
4389 // Proceed to the next one.
4390 rangePar.first++;
4391 if (rangePar.first != rangePar.second) {
4392 // Move to the sibling.
4393 pindex = rangePar.first->second;
4394 break;
4395 } else {
4396 // Move up further.
4397 pindex = pindexPar;
4398 nHeight--;
4399 continue;
4400 }
4401 }
4402 }
4403
4404 // Check that we actually traversed the entire map.
4405 assert(nNodes == forward.size());
4406}
4407
4408std::string CChainState::ToString()
4409{
4410 CBlockIndex* tip = m_chain.Tip();
4411 return strprintf("Chainstate [%s] @ height %d (%s)",
4412 m_from_snapshot_blockhash ? "snapshot" : "ibd",
4413 tip ? tip->nHeight : -1, tip ? tip->GetBlockHash().ToString() : "null");
4414}
4415
4416bool CChainState::ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
4417{
4418 if (coinstip_size == m_coinstip_cache_size_bytes &&
4419 coinsdb_size == m_coinsdb_cache_size_bytes) {
4420 // Cache sizes are unchanged, no need to continue.
4421 return true;
4422 }
4423 size_t old_coinstip_size = m_coinstip_cache_size_bytes;
4424 m_coinstip_cache_size_bytes = coinstip_size;
4425 m_coinsdb_cache_size_bytes = coinsdb_size;
4426 CoinsDB().ResizeCache(coinsdb_size);
4427
4428 LogPrintf("[%s] resized coinsdb cache to %.1f MiB\n",
4429 this->ToString(), coinsdb_size * (1.0 / 1024 / 1024));
4430 LogPrintf("[%s] resized coinstip cache to %.1f MiB\n",
4431 this->ToString(), coinstip_size * (1.0 / 1024 / 1024));
4432
4434 bool ret;
4435
4436 if (coinstip_size > old_coinstip_size) {
4437 // Likely no need to flush if cache sizes have grown.
4439 } else {
4440 // Otherwise, flush state to disk and deallocate the in-memory coins map.
4443 }
4444 return ret;
4445}
4446
4447static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4448
4449bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function)
4450{
4451 const CChainParams& chainparams = Params();
4452 int64_t nExpiryTimeout = gArgs.GetIntArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4453 FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat", "rb")};
4454 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4455 if (file.IsNull()) {
4456 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4457 return false;
4458 }
4459
4460 int64_t count = 0;
4461 int64_t expired = 0;
4462 int64_t failed = 0;
4463 int64_t already_there = 0;
4464 int64_t unbroadcast = 0;
4465 int64_t nNow = GetTime();
4466
4467 try {
4468 uint64_t version;
4469 file >> version;
4470 if (version != MEMPOOL_DUMP_VERSION) {
4471 return false;
4472 }
4473 uint64_t num;
4474 file >> num;
4475 while (num--) {
4476 CTransactionRef tx;
4477 int64_t nTime;
4478 int64_t nFeeDelta;
4479 file >> tx;
4480 file >> nTime;
4481 file >> nFeeDelta;
4482
4483 CAmount amountdelta = nFeeDelta;
4484 if (amountdelta) {
4485 pool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4486 }
4487 if (nTime > nNow - nExpiryTimeout) {
4488 LOCK(cs_main);
4489 if (AcceptToMemoryPoolWithTime(chainparams, pool, active_chainstate, tx, nTime, false /* bypass_limits */,
4490 false /* test_accept */).m_result_type == MempoolAcceptResult::ResultType::VALID) {
4491 ++count;
4492 } else {
4493 // mempool may contain the transaction already, e.g. from
4494 // wallet(s) having loaded it while we were processing
4495 // mempool transactions; consider these as valid, instead of
4496 // failed, but mark them as 'already there'
4497 if (pool.exists(GenTxid::Txid(tx->GetHash()))) {
4498 ++already_there;
4499 } else {
4500 ++failed;
4501 }
4502 }
4503 } else {
4504 ++expired;
4505 }
4506 if (ShutdownRequested())
4507 return false;
4508 }
4509 std::map<uint256, CAmount> mapDeltas;
4510 file >> mapDeltas;
4511
4512 for (const auto& i : mapDeltas) {
4513 pool.PrioritiseTransaction(i.first, i.second);
4514 }
4515
4516 std::set<uint256> unbroadcast_txids;
4517 file >> unbroadcast_txids;
4518 unbroadcast = unbroadcast_txids.size();
4519 for (const auto& txid : unbroadcast_txids) {
4520 // Ensure transactions were accepted to mempool then add to
4521 // unbroadcast set.
4522 if (pool.get(txid) != nullptr) pool.AddUnbroadcastTx(txid);
4523 }
4524 } catch (const std::exception& e) {
4525 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4526 return false;
4527 }
4528
4529 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there, %i waiting for initial broadcast\n", count, failed, expired, already_there, unbroadcast);
4530 return true;
4531}
4532
4533bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function, bool skip_file_commit)
4534{
4535 int64_t start = GetTimeMicros();
4536
4537 std::map<uint256, CAmount> mapDeltas;
4538 std::vector<TxMempoolInfo> vinfo;
4539 std::set<uint256> unbroadcast_txids;
4540
4541 static Mutex dump_mutex;
4542 LOCK(dump_mutex);
4543
4544 {
4545 LOCK(pool.cs);
4546 for (const auto &i : pool.mapDeltas) {
4547 mapDeltas[i.first] = i.second;
4548 }
4549 vinfo = pool.infoAll();
4550 unbroadcast_txids = pool.GetUnbroadcastTxs();
4551 }
4552
4553 int64_t mid = GetTimeMicros();
4554
4555 try {
4556 FILE* filestr{mockable_fopen_function(gArgs.GetDataDirNet() / "mempool.dat.new", "wb")};
4557 if (!filestr) {
4558 return false;
4559 }
4560
4561 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4562
4563 uint64_t version = MEMPOOL_DUMP_VERSION;
4564 file << version;
4565
4566 file << (uint64_t)vinfo.size();
4567 for (const auto& i : vinfo) {
4568 file << *(i.tx);
4569 file << int64_t{count_seconds(i.m_time)};
4570 file << int64_t{i.nFeeDelta};
4571 mapDeltas.erase(i.tx->GetHash());
4572 }
4573
4574 file << mapDeltas;
4575
4576 LogPrintf("Writing %d unbroadcast transactions to disk.\n", unbroadcast_txids.size());
4577 file << unbroadcast_txids;
4578
4579 if (!skip_file_commit && !FileCommit(file.Get()))
4580 throw std::runtime_error("FileCommit failed");
4581 file.fclose();
4582 if (!RenameOver(gArgs.GetDataDirNet() / "mempool.dat.new", gArgs.GetDataDirNet() / "mempool.dat")) {
4583 throw std::runtime_error("Rename failed");
4584 }
4585 int64_t last = GetTimeMicros();
4586 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4587 } catch (const std::exception& e) {
4588 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4589 return false;
4590 }
4591 return true;
4592}
4593
4596double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
4597 if (pindex == nullptr)
4598 return 0.0;
4599
4600 int64_t nNow = time(nullptr);
4601
4602 double fTxTotal;
4603
4604 if (pindex->nChainTx <= data.nTxCount) {
4605 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4606 } else {
4607 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4608 }
4609
4610 return std::min<double>(pindex->nChainTx / fTxTotal, 1.0);
4611}
4612
4613std::optional<uint256> ChainstateManager::SnapshotBlockhash() const
4614{
4615 LOCK(::cs_main);
4616 if (m_active_chainstate && m_active_chainstate->m_from_snapshot_blockhash) {
4617 // If a snapshot chainstate exists, it will always be our active.
4618 return m_active_chainstate->m_from_snapshot_blockhash;
4619 }
4620 return std::nullopt;
4621}
4622
4623std::vector<CChainState*> ChainstateManager::GetAll()
4624{
4625 LOCK(::cs_main);
4626 std::vector<CChainState*> out;
4627
4628 if (!IsSnapshotValidated() && m_ibd_chainstate) {
4629 out.push_back(m_ibd_chainstate.get());
4630 }
4631
4632 if (m_snapshot_chainstate) {
4633 out.push_back(m_snapshot_chainstate.get());
4634 }
4635
4636 return out;
4637}
4638
4639CChainState& ChainstateManager::InitializeChainstate(
4640 CTxMemPool* mempool, const std::optional<uint256>& snapshot_blockhash)
4641{
4642 bool is_snapshot = snapshot_blockhash.has_value();
4643 std::unique_ptr<CChainState>& to_modify =
4644 is_snapshot ? m_snapshot_chainstate : m_ibd_chainstate;
4645
4646 if (to_modify) {
4647 throw std::logic_error("should not be overwriting a chainstate");
4648 }
4649 to_modify.reset(new CChainState(mempool, m_blockman, *this, snapshot_blockhash));
4650
4651 // Snapshot chainstates and initial IBD chaintates always become active.
4652 if (is_snapshot || (!is_snapshot && !m_active_chainstate)) {
4653 LogPrintf("Switching active chainstate to %s\n", to_modify->ToString());
4654 m_active_chainstate = to_modify.get();
4655 } else {
4656 throw std::logic_error("unexpected chainstate activation");
4657 }
4658
4659 return *to_modify;
4660}
4661
4663 const int height, const CChainParams& chainparams)
4664{
4665 const MapAssumeutxo& valid_assumeutxos_map = chainparams.Assumeutxo();
4666 const auto assumeutxo_found = valid_assumeutxos_map.find(height);
4667
4668 if (assumeutxo_found != valid_assumeutxos_map.end()) {
4669 return &assumeutxo_found->second;
4670 }
4671 return nullptr;
4672}
4673
4675 CAutoFile& coins_file,
4676 const SnapshotMetadata& metadata,
4677 bool in_memory)
4678{
4679 uint256 base_blockhash = metadata.m_base_blockhash;
4680
4681 if (this->SnapshotBlockhash()) {
4682 LogPrintf("[snapshot] can't activate a snapshot-based chainstate more than once\n");
4683 return false;
4684 }
4685
4686 int64_t current_coinsdb_cache_size{0};
4687 int64_t current_coinstip_cache_size{0};
4688
4689 // Cache percentages to allocate to each chainstate.
4690 //
4691 // These particular percentages don't matter so much since they will only be
4692 // relevant during snapshot activation; caches are rebalanced at the conclusion of
4693 // this function. We want to give (essentially) all available cache capacity to the
4694 // snapshot to aid the bulk load later in this function.
4695 static constexpr double IBD_CACHE_PERC = 0.01;
4696 static constexpr double SNAPSHOT_CACHE_PERC = 0.99;
4697
4698 {
4699 LOCK(::cs_main);
4700 // Resize the coins caches to ensure we're not exceeding memory limits.
4701 //
4702 // Allocate the majority of the cache to the incoming snapshot chainstate, since
4703 // (optimistically) getting to its tip will be the top priority. We'll need to call
4704 // `MaybeRebalanceCaches()` once we're done with this function to ensure
4705 // the right allocation (including the possibility that no snapshot was activated
4706 // and that we should restore the active chainstate caches to their original size).
4707 //
4708 current_coinsdb_cache_size = this->ActiveChainstate().m_coinsdb_cache_size_bytes;
4709 current_coinstip_cache_size = this->ActiveChainstate().m_coinstip_cache_size_bytes;
4710
4711 // Temporarily resize the active coins cache to make room for the newly-created
4712 // snapshot chain.
4713 this->ActiveChainstate().ResizeCoinsCaches(
4714 static_cast<size_t>(current_coinstip_cache_size * IBD_CACHE_PERC),
4715 static_cast<size_t>(current_coinsdb_cache_size * IBD_CACHE_PERC));
4716 }
4717
4718 auto snapshot_chainstate = WITH_LOCK(::cs_main,
4719 return std::make_unique<CChainState>(
4720 /* mempool */ nullptr, m_blockman, *this, base_blockhash));
4721
4722 {
4723 LOCK(::cs_main);
4724 snapshot_chainstate->InitCoinsDB(
4725 static_cast<size_t>(current_coinsdb_cache_size * SNAPSHOT_CACHE_PERC),
4726 in_memory, false, "chainstate");
4727 snapshot_chainstate->InitCoinsCache(
4728 static_cast<size_t>(current_coinstip_cache_size * SNAPSHOT_CACHE_PERC));
4729 }
4730
4731 const bool snapshot_ok = this->PopulateAndValidateSnapshot(
4732 *snapshot_chainstate, coins_file, metadata);
4733
4734 if (!snapshot_ok) {
4735 WITH_LOCK(::cs_main, this->MaybeRebalanceCaches());
4736 return false;
4737 }
4738
4739 {
4740 LOCK(::cs_main);
4741 assert(!m_snapshot_chainstate);
4742 m_snapshot_chainstate.swap(snapshot_chainstate);
4743 const bool chaintip_loaded = m_snapshot_chainstate->LoadChainTip();
4744 assert(chaintip_loaded);
4745
4746 m_active_chainstate = m_snapshot_chainstate.get();
4747
4748 LogPrintf("[snapshot] successfully activated snapshot %s\n", base_blockhash.ToString());
4749 LogPrintf("[snapshot] (%.2f MB)\n",
4750 m_snapshot_chainstate->CoinsTip().DynamicMemoryUsage() / (1000 * 1000));
4751
4752 this->MaybeRebalanceCaches();
4753 }
4754 return true;
4755}
4756
4758 CChainState& snapshot_chainstate,
4759 CAutoFile& coins_file,
4760 const SnapshotMetadata& metadata)
4761{
4762 // It's okay to release cs_main before we're done using `coins_cache` because we know
4763 // that nothing else will be referencing the newly created snapshot_chainstate yet.
4764 CCoinsViewCache& coins_cache = *WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsTip());
4765
4766 uint256 base_blockhash = metadata.m_base_blockhash;
4767
4768 CBlockIndex* snapshot_start_block = WITH_LOCK(::cs_main, return m_blockman.LookupBlockIndex(base_blockhash));
4769
4770 if (!snapshot_start_block) {
4771 // Needed for GetUTXOStats and ExpectedAssumeutxo to determine the height and to avoid a crash when base_blockhash.IsNull()
4772 LogPrintf("[snapshot] Did not find snapshot start blockheader %s\n",
4773 base_blockhash.ToString());
4774 return false;
4775 }
4776
4777 int base_height = snapshot_start_block->nHeight;
4778 auto maybe_au_data = ExpectedAssumeutxo(base_height, ::Params());
4779
4780 if (!maybe_au_data) {
4781 LogPrintf("[snapshot] assumeutxo height in snapshot metadata not recognized " /* Continued */
4782 "(%d) - refusing to load snapshot\n", base_height);
4783 return false;
4784 }
4785
4786 const AssumeutxoData& au_data = *maybe_au_data;
4787
4788 COutPoint outpoint;
4789 Coin coin;
4790 const uint64_t coins_count = metadata.m_coins_count;
4791 uint64_t coins_left = metadata.m_coins_count;
4792
4793 LogPrintf("[snapshot] loading coins from snapshot %s\n", base_blockhash.ToString());
4794 int64_t flush_now{0};
4795 int64_t coins_processed{0};
4796
4797 while (coins_left > 0) {
4798 try {
4799 coins_file >> outpoint;
4800 coins_file >> coin;
4801 } catch (const std::ios_base::failure&) {
4802 LogPrintf("[snapshot] bad snapshot format or truncated snapshot after deserializing %d coins\n",
4803 coins_count - coins_left);
4804 return false;
4805 }
4806 if (coin.nHeight > base_height ||
4807 outpoint.n >= std::numeric_limits<decltype(outpoint.n)>::max() // Avoid integer wrap-around in coinstats.cpp:ApplyHash
4808 ) {
4809 LogPrintf("[snapshot] bad snapshot data after deserializing %d coins\n",
4810 coins_count - coins_left);
4811 return false;
4812 }
4813
4814 coins_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
4815
4816 --coins_left;
4817 ++coins_processed;
4818
4819 if (coins_processed % 1000000 == 0) {
4820 LogPrintf("[snapshot] %d coins loaded (%.2f%%, %.2f MB)\n",
4821 coins_processed,
4822 static_cast<float>(coins_processed) * 100 / static_cast<float>(coins_count),
4823 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
4824 }
4825
4826 // Batch write and flush (if we need to) every so often.
4827 //
4828 // If our average Coin size is roughly 41 bytes, checking every 120,000 coins
4829 // means <5MB of memory imprecision.
4830 if (coins_processed % 120000 == 0) {
4831 if (ShutdownRequested()) {
4832 return false;
4833 }
4834
4835 const auto snapshot_cache_state = WITH_LOCK(::cs_main,
4836 return snapshot_chainstate.GetCoinsCacheSizeState());
4837
4838 if (snapshot_cache_state >=
4840 LogPrintf("[snapshot] flushing coins cache (%.2f MB)... ", /* Continued */
4841 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
4842 flush_now = GetTimeMillis();
4843
4844 // This is a hack - we don't know what the actual best block is, but that
4845 // doesn't matter for the purposes of flushing the cache here. We'll set this
4846 // to its correct value (`base_blockhash`) below after the coins are loaded.
4847 coins_cache.SetBestBlock(GetRandHash());
4848
4849 coins_cache.Flush();
4850 LogPrintf("done (%.2fms)\n", GetTimeMillis() - flush_now);
4851 }
4852 }
4853 }
4854
4855 // Important that we set this. This and the coins_cache accesses above are
4856 // sort of a layer violation, but either we reach into the innards of
4857 // CCoinsViewCache here or we have to invert some of the CChainState to
4858 // embed them in a snapshot-activation-specific CCoinsViewCache bulk load
4859 // method.
4860 coins_cache.SetBestBlock(base_blockhash);
4861
4862 bool out_of_coins{false};
4863 try {
4864 coins_file >> outpoint;
4865 } catch (const std::ios_base::failure&) {
4866 // We expect an exception since we should be out of coins.
4867 out_of_coins = true;
4868 }
4869 if (!out_of_coins) {
4870 LogPrintf("[snapshot] bad snapshot - coins left over after deserializing %d coins\n",
4871 coins_count);
4872 return false;
4873 }
4874
4875 LogPrintf("[snapshot] loaded %d (%.2f MB) coins from snapshot %s\n",
4876 coins_count,
4877 coins_cache.DynamicMemoryUsage() / (1000 * 1000),
4878 base_blockhash.ToString());
4879
4880 LogPrintf("[snapshot] flushing snapshot chainstate to disk\n");
4881 // No need to acquire cs_main since this chainstate isn't being used yet.
4882 coins_cache.Flush(); // TODO: if #17487 is merged, add erase=false here for better performance.
4883
4884 assert(coins_cache.GetBestBlock() == base_blockhash);
4885
4887 auto breakpoint_fnc = [] { /* TODO insert breakpoint here? */ };
4888
4889 // As above, okay to immediately release cs_main here since no other context knows
4890 // about the snapshot_chainstate.
4891 CCoinsViewDB* snapshot_coinsdb = WITH_LOCK(::cs_main, return &snapshot_chainstate.CoinsDB());
4892
4893 if (!GetUTXOStats(snapshot_coinsdb, WITH_LOCK(::cs_main, return std::ref(m_blockman)), stats, breakpoint_fnc)) {
4894 LogPrintf("[snapshot] failed to generate coins stats\n");
4895 return false;
4896 }
4897
4898 // Assert that the deserialized chainstate contents match the expected assumeutxo value.
4899 if (AssumeutxoHash{stats.hashSerialized} != au_data.hash_serialized) {
4900 LogPrintf("[snapshot] bad snapshot content hash: expected %s, got %s\n",
4901 au_data.hash_serialized.ToString(), stats.hashSerialized.ToString());
4902 return false;
4903 }
4904
4905 snapshot_chainstate.m_chain.SetTip(snapshot_start_block);
4906
4907 // The remainder of this function requires modifying data protected by cs_main.
4908 LOCK(::cs_main);
4909
4910 // Fake various pieces of CBlockIndex state:
4911 CBlockIndex* index = nullptr;
4912 for (int i = 0; i <= snapshot_chainstate.m_chain.Height(); ++i) {
4913 index = snapshot_chainstate.m_chain[i];
4914
4915 // Fake nTx so that LoadBlockIndex() loads assumed-valid CBlockIndex
4916 // entries (among other things)
4917 if (!index->nTx) {
4918 index->nTx = 1;
4919 }
4920 // Fake nChainTx so that GuessVerificationProgress reports accurately
4921 index->nChainTx = index->pprev ? index->pprev->nChainTx + index->nTx : 1;
4922
4923 // Mark unvalidated block index entries beneath the snapshot base block as assumed-valid.
4924 if (!index->IsValid(BLOCK_VALID_SCRIPTS)) {
4925 // This flag will be removed once the block is fully validated by a
4926 // background chainstate.
4927 index->nStatus |= BLOCK_ASSUMED_VALID;
4928 }
4929
4930 // Fake BLOCK_OPT_WITNESS so that CChainState::NeedsRedownload()
4931 // won't ask to rewind the entire assumed-valid chain on startup.
4932 if (index->pprev && DeploymentActiveAt(*index, ::Params().GetConsensus(), Consensus::DEPLOYMENT_SEGWIT)) {
4933 index->nStatus |= BLOCK_OPT_WITNESS;
4934 }
4935
4936 setDirtyBlockIndex.insert(index);
4937 // Changes to the block index will be flushed to disk after this call
4938 // returns in `ActivateSnapshot()`, when `MaybeRebalanceCaches()` is
4939 // called, since we've added a snapshot chainstate and therefore will
4940 // have to downsize the IBD chainstate, which will result in a call to
4941 // `FlushStateToDisk(ALWAYS)`.
4942 }
4943
4944 assert(index);
4945 index->nChainTx = au_data.nChainTx;
4946 snapshot_chainstate.setBlockIndexCandidates.insert(snapshot_start_block);
4947
4948 LogPrintf("[snapshot] validated snapshot (%.2f MB)\n",
4949 coins_cache.DynamicMemoryUsage() / (1000 * 1000));
4950 return true;
4951}
4952
4954{
4955 LOCK(::cs_main);
4956 assert(m_active_chainstate);
4957 return *m_active_chainstate;
4958}
4959
4961{
4962 LOCK(::cs_main);
4963 return m_snapshot_chainstate && m_active_chainstate == m_snapshot_chainstate.get();
4964}
4965
4966void ChainstateManager::Unload()
4967{
4968 for (CChainState* chainstate : this->GetAll()) {
4969 chainstate->m_chain.SetTip(nullptr);
4970 chainstate->UnloadBlockIndex();
4971 }
4972
4973 m_blockman.Unload();
4974}
4975
4977{
4978 LOCK(::cs_main);
4979 m_ibd_chainstate.reset();
4980 m_snapshot_chainstate.reset();
4981 m_active_chainstate = nullptr;
4982 m_snapshot_validated = false;
4983}
4984
4985void ChainstateManager::MaybeRebalanceCaches()
4986{
4987 if (m_ibd_chainstate && !m_snapshot_chainstate) {
4988 LogPrintf("[snapshot] allocating all cache to the IBD chainstate\n");
4989 // Allocate everything to the IBD chainstate.
4990 m_ibd_chainstate->ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
4991 }
4992 else if (m_snapshot_chainstate && !m_ibd_chainstate) {
4993 LogPrintf("[snapshot] allocating all cache to the snapshot chainstate\n");
4994 // Allocate everything to the snapshot chainstate.
4995 m_snapshot_chainstate->ResizeCoinsCaches(m_total_coinstip_cache, m_total_coinsdb_cache);
4996 }
4997 else if (m_ibd_chainstate && m_snapshot_chainstate) {
4998 // If both chainstates exist, determine who needs more cache based on IBD status.
4999 //
5000 // Note: shrink caches first so that we don't inadvertently overwhelm available memory.
5001 if (m_snapshot_chainstate->IsInitialBlockDownload()) {
5002 m_ibd_chainstate->ResizeCoinsCaches(
5004 m_snapshot_chainstate->ResizeCoinsCaches(
5006 } else {
5007 m_snapshot_chainstate->ResizeCoinsCaches(
5009 m_ibd_chainstate->ResizeCoinsCaches(
5011 }
5012 }
5013}
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
int flags
Definition: bitcoin-tx.cpp:525
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
bool fHavePruned
Pruning-related variables and constants.
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams)
bool fPruneMode
True if we're running in -prune mode.
FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, CChain &active_chain, const CChainParams &chainparams, const FlatFilePos *dbp)
Store block on disk.
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: blockstorage.h:34
std::atomic_bool fReindex
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:32
std::atomic_bool fImporting
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:122
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:137
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:156
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:112
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:118
@ BLOCK_ASSUMED_VALID
If set, this indicates that the block index entry is assumed-valid.
Definition: chain.h:137
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:108
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:115
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:101
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:122
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:121
@ BLOCK_FAILED_CHILD
descends from failed block
Definition: chain.h:126
@ BLOCK_FAILED_MASK
Definition: chain.h:127
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:125
@ BLOCK_OPT_WITNESS
block data in blk*.dat was received with a witness-enforcing client
Definition: chain.h:129
static constexpr int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current network-adjusted time ...
Definition: chain.h:22
const CChainParams & Params()
Return the currently selected parameters.
std::map< int, const AssumeutxoData > MapAssumeutxo
Definition: chainparams.h:51
std::map< int, uint256 > MapCheckpoints
Definition: chainparams.h:20
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
Abstract class that implements BIP9-style threshold logic, and caches results.
Definition: versionbits.h:57
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:401
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:288
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:596
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:590
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:602
std::string ToString() const
Definition: hash_type.h:43
IndexSummary GetSummary() const
Get a summary of the index and its state.
Definition: base.cpp:366
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:375
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
CBlockIndex * AddToBlockIndex(const CBlockHeader &block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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:420
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:150
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
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 AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
bool LoadBlockIndexDB(std::set< CBlockIndex *, CBlockIndexWorkComparator > &setBlockIndexCandidates) EXCLUSIVE_LOCKS_REQUIRED(boo LoadBlockIndex)(const Consensus::Params &consensus_params, std::set< CBlockIndex *, CBlockIndexWorkComparator > &block_index_candidates) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
Definition: validation.h:440
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
int GetSpendHeight(const CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the spend height, which is one more than the inputs.GetBestBlock().
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: validation.h:426
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:157
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:565
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:609
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:605
void fclose()
Definition: streams.h:587
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
uint32_t nBits
Definition: block.h:28
int64_t GetBlockTime() const
Definition: block.h:55
uint256 hashPrevBlock
Definition: block.h:25
uint256 hashMerkleRoot
Definition: block.h:26
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:63
std::vector< CTransactionRef > vtx
Definition: block.h:66
bool fChecked
Definition: block.h:69
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:317
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:152
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:116
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:170
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:161
bool HaveTxsDownloaded() const
Check whether this block's and all previous blocks' transactions have been downloaded (and stored to ...
Definition: chain.h:266
uint32_t nTime
Definition: chain.h:200
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:208
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:205
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:167
uint256 GetBlockHash() const
Definition: chain.h:254
int64_t GetBlockTime() const
Definition: chain.h:268
int64_t GetMedianTimePast() const
Definition: chain.h:280
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:155
bool IsAssumedValid() const
Definition: chain.h:313
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:177
FlatFilePos GetUndoPos() const
Definition: chain.h:232
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:303
int32_t nVersion
block header
Definition: chain.h:198
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:111
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:158
uint32_t nStatus
Verification status of this block.
Definition: chain.h:195
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:164
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:187
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:149
Undo information for a CBlock.
Definition: undo.h:64
std::vector< CTxUndo > vtxundo
Definition: undo.h:66
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from.
Definition: streams.h:674
bool SetLimit(uint64_t nPos=std::numeric_limits< uint64_t >::max())
prevent reading beyond a certain position no argument removes the limit
Definition: streams.h:782
void FindByte(char ch)
search for a given byte in the stream, and remain positioned on it
Definition: streams.h:797
uint64_t GetPos() const
return the current reading position
Definition: streams.h:759
bool SetPos(uint64_t nPos)
rewind to a given reading position
Definition: streams.h:764
bool eof() const
check whether we're at the end of the source file
Definition: streams.h:734
An in-memory indexed chain of blocks.
Definition: chain.h:410
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:23
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:416
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:438
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:11
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:433
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
const CBlock & GenesisBlock() const
Definition: chainparams.h:95
const ChainTxData & TxData() const
Definition: chainparams.h:124
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:83
uint64_t PruneAfterHeight() const
Definition: chainparams.h:104
const MapAssumeutxo & Assumeutxo() const
Get allowed assumeutxo configuration.
Definition: chainparams.h:122
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
void CheckBlockIndex()
Make various assertions about the state of the block index.
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
Definition: validation.h:569
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, CBlockIndex **ppindex, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Store block on disk.
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:555
const CChainParams & m_params
Definition: validation.h:575
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:645
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:588
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
Definition: validation.cpp:333
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:573
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:561
CChainState(CTxMemPool *mempool, BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:635
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:638
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition: validation.h:627
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
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.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(void LoadExternalBlockFile(FILE *fileIn, FlatFilePos *dbp=nullptr)
Resize the CoinsViews caches dynamically and flush state to disk.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:661
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
Definition: validation.h:790
bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
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.
bool ConnectBlock(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:578
void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network)
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:553
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
Definition: validation.h:583
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:620
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
Definition: validation.h:614
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
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 LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:664
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as invalid.
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Dictates whether we need to flush the cache to disk or not.
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
CBlockIndex * FindMostWorkChain() 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...
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:207
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:233
Queue for verifications that have to be performed.
Definition: checkqueue.h:31
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:214
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:119
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:229
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:66
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:238
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:156
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:162
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:151
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:222
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:36
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:100
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:146
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:137
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:254
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:50
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Dynamically alter the underlying leveldb cache size.
Definition: txdb.cpp:70
Abstract view on the open txout dataset.
Definition: coins.h:158
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:12
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:14
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:852
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
CAmount GetFee(uint32_t num_bytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:24
void Finalize(Span< unsigned char > output)
Definition: hash.h:30
CHash256 & Write(Span< const unsigned char > input)
Definition: hash.h:37
void TransactionAddedToMempool(const CTransactionRef &, 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:33
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:27
uint32_t n
Definition: transaction.h:30
uint256 hash
Definition: transaction.h:29
A hasher class for SHA-256.
Definition: sha256.h:14
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:663
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:637
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:279
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:306
PrecomputedTransactionData * txdata
Definition: validation.h:287
void swap(CScriptCheck &check)
Definition: validation.h:296
CTxOut m_tx_out
Definition: validation.h:281
bool cacheStore
Definition: validation.h:285
ScriptError error
Definition: validation.h:286
unsigned int nFlags
Definition: validation.h:284
const CTransaction * ptxTo
Definition: validation.h:282
unsigned int nIn
Definition: validation.h:283
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
const uint256 & GetWitnessHash() const
Definition: transaction.h:303
bool HasWitness() const
Definition: transaction.h:332
const uint256 & GetHash() const
Definition: transaction.h:302
const std::vector< CTxOut > vout
Definition: transaction.h:271
bool IsCoinBase() const
Definition: transaction.h:315
const std::vector< CTxIn > vin
Definition: transaction.h:270
An input of a transaction.
Definition: transaction.h:66
COutPoint prevout
Definition: transaction.h:68
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:80
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:424
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:929
std::set< uint256 > GetUnbroadcastTxs() const
Returns transactions in unbroadcast set.
Definition: txmempool.h:758
void AddUnbroadcastTx(const uint256 &txid)
Adds a transaction to the unbroadcast set.
Definition: txmempool.h:746
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:511
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.cpp:589
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:162
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:464
void removeForReorg(CChainState &active_chainstate, int flags) EXCLUSIVE_LOCKS_REQUIRED(cs
Definition: txmempool.cpp:619
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:911
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1038
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:897
void SetIsLoaded(bool loaded)
Sets the current loaded state.
Definition: txmempool.cpp:1224
void clear()
Definition: txmempool.cpp:721
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:517
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs)
Called when a block is connected.
Definition: txmempool.cpp:679
indexed_transaction_set::nth_index< 0 >::type::const_iterator txiter
Definition: txmempool.h:514
bool exists(const GenTxid &gtxid) const
Definition: txmempool.h:725
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
CAmount nValue
Definition: transaction.h:131
Undo information for a CTransaction.
Definition: undo.h:54
std::vector< Coin > vprevout
Definition: undo.h:57
bool VerifyDB(CChainState &chainstate, const CChainParams &chainparams, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
void Unload() EXCLUSIVE_LOCKS_REQUIRED(void Reset()
Unload block index and chain data before shutdown.
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:906
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:910
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:925
CChainState & ActiveChainstate() const
The most-work chain.
bool PopulateAndValidateSnapshot(CChainState &snapshot_chainstate, CAutoFile &coins_file, const SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
bool IsSnapshotActive() const
bool m_snapshot_validated
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
Definition: validation.h:890
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
std::optional< uint256 > SnapshotBlockhash() const
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
bool ActivateSnapshot(CAutoFile &coins_file, const SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:961
A UTXO entry.
Definition: coins.h:31
bool IsCoinBase() const
Definition: coins.h:55
CTxOut out
unspent transaction output
Definition: coins.h:34
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
std::vector< PerBlockConnectTrace > & GetBlocksConnected()
std::vector< PerBlockConnectTrace > blocksConnected
void BlockConnected(CBlockIndex *pindex, std::shared_ptr< const CBlock > pblock)
cache implements a cache with properties similar to a cuckoo-set.
Definition: cuckoocache.h:159
static GenTxid Wtxid(const uint256 &hash)
Definition: transaction.h:398
static GenTxid Txid(const uint256 &hash)
Definition: transaction.h:397
Metadata describing a serialized version of a UTXO set from which an assumeutxo CChainState can be co...
Definition: utxo_snapshot.h:15
uint256 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:19
uint64_t m_coins_count
The number of coins in the UTXO set contained in this snapshot.
Definition: utxo_snapshot.h:23
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:102
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
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
Threshold condition checker that triggers when unknown versionbits are seen on the network.
int64_t EndTime(const Consensus::Params &params) const override
bool Condition(const CBlockIndex *pindex, const Consensus::Params &params) const override
WarningBitsConditionChecker(int bitIn)
int Threshold(const Consensus::Params &params) const override
int64_t BeginTime(const Consensus::Params &params) const override
int Period(const Consensus::Params &params) const override
256-bit unsigned big integer.
const unsigned char * data() const
Definition: uint256.h:55
unsigned char * begin()
Definition: uint256.h:58
std::string ToString() const
Definition: uint256.cpp:64
bool IsNull() const
Definition: uint256.h:31
double getdouble() const
iterator begin()
Definition: prevector.h:290
iterator end()
Definition: prevector.h:292
void resize(size_type new_size)
Definition: prevector.h:316
256-bit opaque blob.
Definition: uint256.h:124
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:265
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:108
static bool GetUTXOStats(CCoinsView *view, BlockManager &blockman, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point, const CBlockIndex *pindex)
Calculate statistics about the unspent transaction output set.
Definition: coinstats.cpp:92
static constexpr int NO_WITNESS_COMMITMENT
Index marker for when no witness commitment is present in a coinbase transaction.
Definition: validation.h:16
static constexpr size_t MINIMUM_WITNESS_COMMITMENT
Minimum size of a witness commitment structure.
Definition: validation.h:19
static int64_t GetBlockWeight(const CBlock &block)
Definition: validation.h:150
@ BLOCK_CHECKPOINT
the block failed to meet one of our checkpoints
@ 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)
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
Definition: validation.h:161
@ TX_MISSING_INPUTS
transaction was missing some of its inputs
@ TX_MEMPOOL_POLICY
violated mempool's fee/size/descendant/RBF/etc limits
@ TX_PREMATURE_SPEND
transaction spends a coinbase too early, or violates locktime/sequence locks
@ TX_INPUTS_NOT_STANDARD
inputs (covered by txid) failed policy rules
@ TX_WITNESS_STRIPPED
Transaction is missing a witness.
@ TX_CONFLICT
Tx already in mempool or conflicts with a tx in the chain (if it conflicts with another tx in mempool...
@ TX_NOT_STANDARD
otherwise didn't meet our local policy rules
@ TX_WITNESS_MUTATED
Transaction might have a witness prior to SegWit activation, or witness may have been malleated (whic...
@ TX_CONSENSUS
invalid by consensus rules
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:28
static constexpr unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
Definition: consensus.h:30
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
static const unsigned int MAX_BLOCK_SERIALIZED_SIZE
The maximum allowed size for a serialized block, in bytes (only for buffer size limits)
Definition: consensus.h:13
static const int64_t MAX_BLOCK_SIGOPS_COST
The maximum allowed number of signature check operations in a block (network rule)
Definition: consensus.h:17
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
VersionBitsCache g_versionbitscache
Global cache for versionbits deployment status.
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.
bool mutated
static feebumper::Result CheckFeeRate(const CWallet &wallet, const CWalletTx &wtx, const CFeeRate &newFeerate, const int64_t maxTxSize, std::vector< bilingual_str > &errors)
Check if the user provided a valid feeRate.
Definition: feebumper.cpp:63
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
@ SCRIPT_VERIFY_NULLDUMMY
Definition: interpreter.h:61
@ SCRIPT_VERIFY_P2SH
Definition: interpreter.h:46
@ SCRIPT_VERIFY_WITNESS
Definition: interpreter.h:105
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
Definition: interpreter.h:96
@ SCRIPT_VERIFY_TAPROOT
Definition: interpreter.h:131
@ SCRIPT_VERIFY_DERSIG
Definition: interpreter.h:54
@ SCRIPT_VERIFY_CLEANSTACK
Definition: interpreter.h:91
@ SCRIPT_VERIFY_NONE
Definition: interpreter.h:43
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
Definition: interpreter.h:101
#define LogPrint(category,...)
Definition: logging.h:191
#define LogPrintf(...)
Definition: logging.h:187
unsigned int nHeight
LockPoints lp
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
uint256 BlockWitnessMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:75
unsigned int nonce
Definition: miner_tests.cpp:54
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:15
@ REINDEX
Definition: logging.h:49
@ VALIDATION
Definition: logging.h:59
@ PRUNE
Definition: logging.h:52
@ MEMPOOL
Definition: logging.h:40
@ BENCH
Definition: logging.h:42
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:169
@ DEPLOYMENT_TAPROOT
Definition: params.h:30
@ DEPLOYMENT_DERSIG
Definition: params.h:22
@ DEPLOYMENT_CSV
Definition: params.h:23
@ DEPLOYMENT_SEGWIT
Definition: params.h:24
@ DEPLOYMENT_HEIGHTINCB
Definition: params.h:20
@ DEPLOYMENT_CLTV
Definition: params.h:21
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:32
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
@ PCKG_TX
At least one tx is invalid.
std::optional< std::string > HasNoNewUnconfirmed(const CTransaction &tx, const CTxMemPool &pool, const CTxMemPool::setEntries &iters_conflicting)
BIP125 Rule #2: "The replacement transaction may only include an unconfirmed input if that input was ...
Definition: rbf.cpp:78
std::optional< std::string > PaysForRBF(CAmount original_fees, CAmount replacement_fees, size_t replacement_vsize, CFeeRate relay_fee, const uint256 &txid)
Enforce BIP125 Rule #3 "The replacement transaction pays an absolute fee of at least the sum paid by ...
Definition: rbf.cpp:151
std::optional< std::string > EntriesAndTxidsDisjoint(const CTxMemPool::setEntries &ancestors, const std::set< uint256 > &direct_conflicts, const uint256 &txid)
Check the intersection between two sets of transactions (a set of mempool entries and a set of txids)...
Definition: rbf.cpp:110
std::optional< std::string > PaysMoreThanConflicts(const CTxMemPool::setEntries &iters_conflicting, CFeeRate replacement_feerate, const uint256 &txid)
Check that the feerate of the replacement transaction(s) is higher than the feerate of each of the tr...
Definition: rbf.cpp:125
std::optional< std::string > GetEntriesForConflicts(const CTransaction &tx, CTxMemPool &pool, const CTxMemPool::setEntries &iters_conflicting, CTxMemPool::setEntries &all_conflicts)
Get all descendants of iters_conflicting.
Definition: rbf.cpp:50
CFeeRate incrementalRelayFee
Definition: settings.cpp:12
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs, bool taproot_active)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:164
bool IsStandardTx(const CTransaction &tx, bool permit_bare_multisig, const CFeeRate &dust_relay_fee, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:81
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:201
static const unsigned int MAX_STANDARD_TX_SIGOPS_COST
The maximum number of sigops we're willing to relay/mine in a single tx.
Definition: policy.h:30
static constexpr unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
Definition: policy.h:85
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:32
static const unsigned int MIN_STANDARD_TX_NONWITNESS_SIZE
The minimum non-witness size for transactions we're willing to relay/mine (1 segwit input + 1 P2WPKH ...
Definition: policy.h:26
static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:60
static constexpr unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS
For convenience, standard but not mandatory verify flags.
Definition: policy.h:82
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:13
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:74
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:23
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:387
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
uint256 GetRandHash() noexcept
Definition: random.cpp:601
const char * prefix
Definition: rest.cpp:714
reverse_range< T > reverse_iterate(T &x)
@ OP_RETURN
Definition: script.h:104
std::string ScriptErrorString(const ScriptError serror)
@ SER_DISK
Definition: serialize.h:139
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:87
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:56
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:18
static const int64_t MAX_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:20
bool CheckSignetBlockSolution(const CBlock &block, const Consensus::Params &consensusParams)
Extract signature and check whether a block has a valid solution.
Definition: signet.cpp:124
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
const AssumeutxoHash hash_serialized
The expected hash of the deserialized UTXO set.
Definition: chainparams.h:42
const unsigned int nChainTx
Used to populate the nChainTx value, which is used during BlockManager::LoadBlockIndex().
Definition: chainparams.h:48
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
Definition: validation.cpp:90
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:115
std::vector< uint256 > vHave
Definition: block.h:116
MapCheckpoints mapCheckpoints
Definition: chainparams.h:23
A mutable version of CTransaction.
Definition: transaction.h:345
std::vector< CTxOut > vout
Definition: transaction.h:347
std::vector< CTxIn > vin
Definition: transaction.h:346
Holds various statistics on transactions within a chain.
Definition: chainparams.h:59
double dTxRate
estimated number of transactions per second after that timestamp
Definition: chainparams.h:62
int64_t nTime
UNIX timestamp of last known number of transactions.
Definition: chainparams.h:60
int64_t nTxCount
total number of transactions between genesis and that timestamp
Definition: chainparams.h:61
Parameters that influence chain consensus.
Definition: params.h:70
uint256 BIP34Hash
Definition: params.h:77
uint32_t nMinerConfirmationWindow
Definition: params.h:97
bool signet_blocks
If true, witness commitments contain a payload equal to a Bitcoin Script solution to the signet chall...
Definition: params.h:115
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:76
int nSubsidyHalvingInterval
Definition: params.h:72
uint256 hashGenesisBlock
Definition: params.h:71
int MinBIP9WarningHeight
Don't warn about unknown BIP 9 activations below this height.
Definition: params.h:90
uint32_t nRuleChangeActivationThreshold
Minimum blocks including miner confirmation of the total of 2016 blocks in a retargeting period,...
Definition: params.h:96
uint256 BIP16Exception
Definition: params.h:74
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:947
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:915
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:931
size_t DynamicMemoryUsage() const
Definition: txmempool.h:920
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:924
int nFile
Definition: flatfile.h:16
unsigned int nPos
Definition: flatfile.h:17
bool IsNull() const
Definition: flatfile.h:37
int best_block_height
Definition: base.h:19
CBlockIndex * maxInputBlock
Definition: txmempool.h:49
int height
Definition: txmempool.h:44
int64_t time
Definition: txmempool.h:45
Validation result for a single transaction mempool acceptance.
Definition: validation.h:149
const ResultType m_result_type
Definition: validation.h:155
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
Definition: validation.h:167
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:163
Validation result for package mempool acceptance.
Definition: validation.h:189
std::shared_ptr< const CBlock > pblock
CBlockIndex * pindex
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:169
std::vector< CTxOut > m_spent_outputs
Definition: interpreter.h:167
Bilingual messages:
Definition: translation.h:16
bool empty() const
Definition: translation.h:27
std::string original
Definition: translation.h:17
#define AssertLockNotHeld(cs)
Definition: sync.h:84
#define LOCK2(cs1, cs2)
Definition: sync.h:227
#define LOCK(cs)
Definition: sync.h:226
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
static int count
Definition: tests.c:41
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:122
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:117
int64_t GetTime()
DEPRECATED Use either GetTimeSeconds (not mockable) or GetTime<T> (mockable)
Definition: time.cpp:26
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:132
constexpr int64_t count_seconds(std::chrono::seconds t)
Helper to count the seconds of a duration.
Definition: time.h:29
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
#define LOG_TIME_MILLIS_WITH_CATEGORY(end_msg, log_category)
Definition: timer.h:92
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
#define TRACE6(context, event, a, b, c, d, e, f)
Definition: trace.h:34
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:63
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:11
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:102
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:40
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, uint32_t flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:148
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:117
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:112
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:18
@ REPLACED
Removed for replacement.
@ REORG
Removed for reorganization.
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0....
Definition: txmempool.h:38
CClientUIInterface uiInterface
uint256 uint256S(const char *str)
Definition: uint256.h:137
#define expect(bit)
bool SignalsOptInRBF(const CTransaction &tx)
Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee,...
Definition: rbf.cpp:9
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1065
ArgsManager gArgs
Definition: system.cpp:85
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: system.cpp:145
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: system.cpp:1095
static void UpdateTipLog(const CCoinsViewCache &coins_tip, const CBlockIndex *tip, const CChainParams &params, const std::string &func_name, const std::string &prefix, const std::string &warning_messages) EXCLUSIVE_LOCKS_REQUIRED(
void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
static CSHA256 g_scriptExecutionCacheHasher
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:130
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:131
static const uint64_t MEMPOOL_DUMP_VERSION
std::vector< COutPoint > vNoSpendsRemaining
Definition: validation.cpp:315
static int64_t nTimeConnectTotal
bool fCheckBlockIndex
Definition: validation.cpp:126
static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS] GUARDED_BY(cs_main)
std::condition_variable g_best_block_cv
Definition: validation.cpp:122
static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT
An extra transaction can be added to a package, as long as it only has one ancestor and is no larger ...
Definition: validation.cpp:72
static bool pool cs
Definition: validation.cpp:390
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE
Maximum kilobytes for transactions to store for processing during reorg.
Definition: validation.cpp:74
static void AlertNotify(const std::string &strMessage)
std::set< CBlockIndex * > setDirtyBlockIndex
Dirty block index entries.
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...
#define MICRO
Definition: validation.cpp:64
static int64_t nBlocksTotal
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:124
static int64_t nTimePostConnect
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
static SynchronizationState GetSynchronizationState(bool init)
static bool ContextualCheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
static int64_t nTimeFlush
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
int ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
std::vector< CBlockFileInfo > vinfoBlockFile
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:133
if(expired !=0)
Definition: validation.cpp:311
static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL
Time to wait between flushing chainstate to disk.
Definition: validation.cpp:78
static bool NotifyHeaderTip(CChainState &chainstate) LOCKS_EXCLUDED(cs_main)
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
bool LoadMempool(CTxMemPool &pool, CChainState &active_chainstate, FopenFn mockable_fopen_function)
Load the mempool from disk.
RecursiveMutex cs_LastBlockFile
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
static void AppendWarning(bilingual_str &res, const bilingual_str &warn)
Private helper function that concatenates warning messages.
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &chainparams)
Return the expected assumeutxo value for a given height, if one exists.
static bool ContextualCheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, BlockManager &blockman, const CChainParams &params, const CBlockIndex *pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Context-dependent validity checks.
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
void InitScriptExecutionCache()
Initializes the script-execution cache.
static int64_t nTimeVerify
static MempoolAcceptResult AcceptToMemoryPoolWithTime(const CChainParams &chainparams, CTxMemPool &pool, CChainState &active_chainstate, const CTransactionRef &tx, int64_t nAcceptTime, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool with a specified acceptance time
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const CTxMemPool &pool, unsigned int flags, PrecomputedTransactionData &txdata, CCoinsViewCache &coins_tip) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Checks to avoid mempool polluting consensus critical paths since cached signature and script validity...
Mutex g_best_block_mutex
Definition: validation.cpp:121
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
static void LimitValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main)
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
PackageMempoolAcceptResult ProcessNewPackage(CChainState &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Atomically test acceptance of a package.
bool CheckSequenceLocks(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:233
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block)
static int64_t nTimeTotal
bool fCheckForPruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
static int64_t nTimeConnect
static void LimitMempoolSize(CTxMemPool &pool, CCoinsViewCache &coins_cache, size_t limit, std::chrono::seconds age) EXCLUSIVE_LOCKS_REQUIRED(pool.cs
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:81
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE
Maximum age of our tip for us to be considered current for fee estimation.
Definition: validation.cpp:80
static int64_t nTimeIndex
static unsigned int GetBlockScriptFlags(const CBlockIndex *pindex, const Consensus::Params &chainparams)
static bool IsCurrentForFeeEstimation(CChainState &active_chainstate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:321
static CuckooCache::cache< uint256, SignatureCacheHasher > g_scriptExecutionCache
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
AssertLockHeld(pool.cs)
MempoolAcceptResult AcceptToMemoryPool(CChainState &active_chainstate, CTxMemPool &pool, const CTransactionRef &tx, bool bypass_limits, bool test_accept)
(Try to) add a transaction to the memory pool.
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage)
static bool CheckBlockHeader(const CBlockHeader &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true)
bool CheckFinalTx(const CBlockIndex *active_chain_tip, const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:182
bool fCheckpointsEnabled
Definition: validation.cpp:127
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:120
static int64_t nTimeForks
int nLastBlockFile
static int64_t nTimeCheck
#define MILLI
Definition: validation.cpp:65
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function, bool skip_file_commit)
Dump the mempool to disk.
std::set< int > setDirtyFileInfo
Dirty block file entries.
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:123
bool TestLockPointValidity(CChain &active_chain, const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain.
Definition: validation.cpp:215
bool fRequireStandard
Definition: validation.cpp:125
static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL
Time to wait between writing blocks/block index to disk.
Definition: validation.cpp:76
static int64_t nTimeChainState
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:128
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
assert(!tx.IsCoinBase())
static int64_t nTimeReadFromDisk
static void DoWarning(const bilingual_str &warning)
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:70
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:60
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: validation.h:1017
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:62
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:79
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:93
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:54
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:64
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:58
CoinsCacheSizeState
Definition: validation.h:521
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:56
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:69
FlushStateMode
Definition: validation.h:355
DisconnectResult
Definition: validation.h:346
@ DISCONNECT_FAILED
Definition: validation.h:349
@ DISCONNECT_UNCLEAN
Definition: validation.h:348
@ DISCONNECT_OK
Definition: validation.h:347
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:75
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:77
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:12
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
Definition: versionbits.h:38
static const int32_t VERSIONBITS_NUM_BITS
Total bits available for versionbits.
Definition: versionbits.h:20
static const int32_t VERSIONBITS_TOP_BITS
What bits to set in version for versionbits blocks.
Definition: versionbits.h:16
static const int32_t VERSIONBITS_TOP_MASK
What bitmask determines whether versionbits is in use.
Definition: versionbits.h:18
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:27
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:25
void SetMiscWarning(const bilingual_str &warning)
Definition: warnings.cpp:19