Add required space to [[ -n "$1" ]] (previously [[ -n"$1" ]])
[bitcoinplatinum.git] / src / validation.cpp
blob1a1c1941ef8c47b10537cd5e0912a89e7f50728d
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #include "validation.h"
8 #include "arith_uint256.h"
9 #include "chain.h"
10 #include "chainparams.h"
11 #include "checkpoints.h"
12 #include "checkqueue.h"
13 #include "consensus/consensus.h"
14 #include "consensus/merkle.h"
15 #include "consensus/tx_verify.h"
16 #include "consensus/validation.h"
17 #include "cuckoocache.h"
18 #include "fs.h"
19 #include "hash.h"
20 #include "init.h"
21 #include "policy/fees.h"
22 #include "policy/policy.h"
23 #include "policy/rbf.h"
24 #include "pow.h"
25 #include "primitives/block.h"
26 #include "primitives/transaction.h"
27 #include "random.h"
28 #include "reverse_iterator.h"
29 #include "script/script.h"
30 #include "script/sigcache.h"
31 #include "script/standard.h"
32 #include "timedata.h"
33 #include "tinyformat.h"
34 #include "txdb.h"
35 #include "txmempool.h"
36 #include "ui_interface.h"
37 #include "undo.h"
38 #include "util.h"
39 #include "utilmoneystr.h"
40 #include "utilstrencodings.h"
41 #include "validationinterface.h"
42 #include "versionbits.h"
43 #include "warnings.h"
45 #include <atomic>
46 #include <sstream>
48 #include <boost/algorithm/string/replace.hpp>
49 #include <boost/algorithm/string/join.hpp>
50 #include <boost/thread.hpp>
52 #if defined(NDEBUG)
53 # error "Bitcoin cannot be compiled without assertions."
54 #endif
56 #define MICRO 0.000001
57 #define MILLI 0.001
59 /**
60 * Global state
63 CCriticalSection cs_main;
65 BlockMap mapBlockIndex;
66 CChain chainActive;
67 CBlockIndex *pindexBestHeader = nullptr;
68 CWaitableCriticalSection csBestBlock;
69 CConditionVariable cvBlockChange;
70 int nScriptCheckThreads = 0;
71 std::atomic_bool fImporting(false);
72 std::atomic_bool fReindex(false);
73 bool fTxIndex = false;
74 bool fHavePruned = false;
75 bool fPruneMode = false;
76 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
77 bool fRequireStandard = true;
78 bool fCheckBlockIndex = false;
79 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
80 size_t nCoinCacheUsage = 5000 * 300;
81 uint64_t nPruneTarget = 0;
82 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
83 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
85 uint256 hashAssumeValid;
86 arith_uint256 nMinimumChainWork;
88 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
89 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
91 CBlockPolicyEstimator feeEstimator;
92 CTxMemPool mempool(&feeEstimator);
94 static void CheckBlockIndex(const Consensus::Params& consensusParams);
96 /** Constant stuff for coinbase transactions we create: */
97 CScript COINBASE_FLAGS;
99 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
101 // Internal stuff
102 namespace {
104 struct CBlockIndexWorkComparator
106 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
107 // First sort by most total work, ...
108 if (pa->nChainWork > pb->nChainWork) return false;
109 if (pa->nChainWork < pb->nChainWork) return true;
111 // ... then by earliest time received, ...
112 if (pa->nSequenceId < pb->nSequenceId) return false;
113 if (pa->nSequenceId > pb->nSequenceId) return true;
115 // Use pointer address as tie breaker (should only happen with blocks
116 // loaded from disk, as those all have id 0).
117 if (pa < pb) return false;
118 if (pa > pb) return true;
120 // Identical blocks.
121 return false;
125 CBlockIndex *pindexBestInvalid;
128 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
129 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
130 * missing the data for the block.
132 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
133 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
134 * Pruned nodes may have entries where B is missing data.
136 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
138 CCriticalSection cs_LastBlockFile;
139 std::vector<CBlockFileInfo> vinfoBlockFile;
140 int nLastBlockFile = 0;
141 /** Global flag to indicate we should check to see if there are
142 * block/undo files that should be deleted. Set on startup
143 * or if we allocate more file space when we're in prune mode
145 bool fCheckForPruning = false;
148 * Every received block is assigned a unique and increasing identifier, so we
149 * know which one to give priority in case of a fork.
151 CCriticalSection cs_nBlockSequenceId;
152 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
153 int32_t nBlockSequenceId = 1;
154 /** Decreasing counter (used by subsequent preciousblock calls). */
155 int32_t nBlockReverseSequenceId = -1;
156 /** chainwork for the last block that preciousblock has been applied to. */
157 arith_uint256 nLastPreciousChainwork = 0;
159 /** Dirty block index entries. */
160 std::set<CBlockIndex*> setDirtyBlockIndex;
162 /** Dirty block file entries. */
163 std::set<int> setDirtyFileInfo;
164 } // anon namespace
166 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
168 // Find the first block the caller has in the main chain
169 for (const uint256& hash : locator.vHave) {
170 BlockMap::iterator mi = mapBlockIndex.find(hash);
171 if (mi != mapBlockIndex.end())
173 CBlockIndex* pindex = (*mi).second;
174 if (chain.Contains(pindex))
175 return pindex;
176 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
177 return chain.Tip();
181 return chain.Genesis();
184 CCoinsViewDB *pcoinsdbview = nullptr;
185 CCoinsViewCache *pcoinsTip = nullptr;
186 CBlockTreeDB *pblocktree = nullptr;
188 enum FlushStateMode {
189 FLUSH_STATE_NONE,
190 FLUSH_STATE_IF_NEEDED,
191 FLUSH_STATE_PERIODIC,
192 FLUSH_STATE_ALWAYS
195 // See definition for documentation
196 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
197 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
198 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
199 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
200 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
202 bool CheckFinalTx(const CTransaction &tx, int flags)
204 AssertLockHeld(cs_main);
206 // By convention a negative value for flags indicates that the
207 // current network-enforced consensus rules should be used. In
208 // a future soft-fork scenario that would mean checking which
209 // rules would be enforced for the next block and setting the
210 // appropriate flags. At the present time no soft-forks are
211 // scheduled, so no flags are set.
212 flags = std::max(flags, 0);
214 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
215 // nLockTime because when IsFinalTx() is called within
216 // CBlock::AcceptBlock(), the height of the block *being*
217 // evaluated is what is used. Thus if we want to know if a
218 // transaction can be part of the *next* block, we need to call
219 // IsFinalTx() with one more than chainActive.Height().
220 const int nBlockHeight = chainActive.Height() + 1;
222 // BIP113 requires that time-locked transactions have nLockTime set to
223 // less than the median time of the previous block they're contained in.
224 // When the next block is created its previous block will be the current
225 // chain tip, so we use that to calculate the median time passed to
226 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
227 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
228 ? chainActive.Tip()->GetMedianTimePast()
229 : GetAdjustedTime();
231 return IsFinalTx(tx, nBlockHeight, nBlockTime);
234 bool TestLockPointValidity(const LockPoints* lp)
236 AssertLockHeld(cs_main);
237 assert(lp);
238 // If there are relative lock times then the maxInputBlock will be set
239 // If there are no relative lock times, the LockPoints don't depend on the chain
240 if (lp->maxInputBlock) {
241 // Check whether chainActive is an extension of the block at which the LockPoints
242 // calculation was valid. If not LockPoints are no longer valid
243 if (!chainActive.Contains(lp->maxInputBlock)) {
244 return false;
248 // LockPoints still valid
249 return true;
252 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
254 AssertLockHeld(cs_main);
255 AssertLockHeld(mempool.cs);
257 CBlockIndex* tip = chainActive.Tip();
258 assert(tip != nullptr);
260 CBlockIndex index;
261 index.pprev = tip;
262 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
263 // height based locks because when SequenceLocks() is called within
264 // ConnectBlock(), the height of the block *being*
265 // evaluated is what is used.
266 // Thus if we want to know if a transaction can be part of the
267 // *next* block, we need to use one more than chainActive.Height()
268 index.nHeight = tip->nHeight + 1;
270 std::pair<int, int64_t> lockPair;
271 if (useExistingLockPoints) {
272 assert(lp);
273 lockPair.first = lp->height;
274 lockPair.second = lp->time;
276 else {
277 // pcoinsTip contains the UTXO set for chainActive.Tip()
278 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
279 std::vector<int> prevheights;
280 prevheights.resize(tx.vin.size());
281 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
282 const CTxIn& txin = tx.vin[txinIndex];
283 Coin coin;
284 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
285 return error("%s: Missing input", __func__);
287 if (coin.nHeight == MEMPOOL_HEIGHT) {
288 // Assume all mempool transaction confirm in the next block
289 prevheights[txinIndex] = tip->nHeight + 1;
290 } else {
291 prevheights[txinIndex] = coin.nHeight;
294 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
295 if (lp) {
296 lp->height = lockPair.first;
297 lp->time = lockPair.second;
298 // Also store the hash of the block with the highest height of
299 // all the blocks which have sequence locked prevouts.
300 // This hash needs to still be on the chain
301 // for these LockPoint calculations to be valid
302 // Note: It is impossible to correctly calculate a maxInputBlock
303 // if any of the sequence locked inputs depend on unconfirmed txs,
304 // except in the special case where the relative lock time/height
305 // is 0, which is equivalent to no sequence lock. Since we assume
306 // input height of tip+1 for mempool txs and test the resulting
307 // lockPair from CalculateSequenceLocks against tip+1. We know
308 // EvaluateSequenceLocks will fail if there was a non-zero sequence
309 // lock on a mempool input, so we can use the return value of
310 // CheckSequenceLocks to indicate the LockPoints validity
311 int maxInputHeight = 0;
312 for (int height : prevheights) {
313 // Can ignore mempool inputs since we'll fail if they had non-zero locks
314 if (height != tip->nHeight+1) {
315 maxInputHeight = std::max(maxInputHeight, height);
318 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
321 return EvaluateSequenceLocks(index, lockPair);
324 // Returns the script flags which should be checked for a given block
325 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
327 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
328 int expired = pool.Expire(GetTime() - age);
329 if (expired != 0) {
330 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
333 std::vector<COutPoint> vNoSpendsRemaining;
334 pool.TrimToSize(limit, &vNoSpendsRemaining);
335 for (const COutPoint& removed : vNoSpendsRemaining)
336 pcoinsTip->Uncache(removed);
339 /** Convert CValidationState to a human-readable message for logging */
340 std::string FormatStateMessage(const CValidationState &state)
342 return strprintf("%s%s (code %i)",
343 state.GetRejectReason(),
344 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
345 state.GetRejectCode());
348 static bool IsCurrentForFeeEstimation()
350 AssertLockHeld(cs_main);
351 if (IsInitialBlockDownload())
352 return false;
353 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
354 return false;
355 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
356 return false;
357 return true;
360 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
361 * disconnected block transactions from the mempool, and also removing any
362 * other transactions from the mempool that are no longer valid given the new
363 * tip/height.
365 * Note: we assume that disconnectpool only contains transactions that are NOT
366 * confirmed in the current chain nor already in the mempool (otherwise,
367 * in-mempool descendants of such transactions would be removed).
369 * Passing fAddToMempool=false will skip trying to add the transactions back,
370 * and instead just erase from the mempool as needed.
373 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
375 AssertLockHeld(cs_main);
376 std::vector<uint256> vHashUpdate;
377 // disconnectpool's insertion_order index sorts the entries from
378 // oldest to newest, but the oldest entry will be the last tx from the
379 // latest mined block that was disconnected.
380 // Iterate disconnectpool in reverse, so that we add transactions
381 // back to the mempool starting with the earliest transaction that had
382 // been previously seen in a block.
383 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
384 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
385 // ignore validation errors in resurrected transactions
386 CValidationState stateDummy;
387 if (!fAddToMempool || (*it)->IsCoinBase() ||
388 !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
389 nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
390 // If the transaction doesn't make it in to the mempool, remove any
391 // transactions that depend on it (which would now be orphans).
392 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
393 } else if (mempool.exists((*it)->GetHash())) {
394 vHashUpdate.push_back((*it)->GetHash());
396 ++it;
398 disconnectpool.queuedTx.clear();
399 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
400 // no in-mempool children, which is generally not true when adding
401 // previously-confirmed transactions back to the mempool.
402 // UpdateTransactionsFromBlock finds descendants of any transactions in
403 // the disconnectpool that were added back and cleans up the mempool state.
404 mempool.UpdateTransactionsFromBlock(vHashUpdate);
406 // We also need to remove any now-immature transactions
407 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
408 // Re-limit mempool size, in case we added any transactions
409 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
412 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
413 // were somehow broken and returning the wrong scriptPubKeys
414 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
415 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
416 AssertLockHeld(cs_main);
418 // pool.cs should be locked already, but go ahead and re-take the lock here
419 // to enforce that mempool doesn't change between when we check the view
420 // and when we actually call through to CheckInputs
421 LOCK(pool.cs);
423 assert(!tx.IsCoinBase());
424 for (const CTxIn& txin : tx.vin) {
425 const Coin& coin = view.AccessCoin(txin.prevout);
427 // At this point we haven't actually checked if the coins are all
428 // available (or shouldn't assume we have, since CheckInputs does).
429 // So we just return failure if the inputs are not available here,
430 // and then only have to check equivalence for available inputs.
431 if (coin.IsSpent()) return false;
433 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
434 if (txFrom) {
435 assert(txFrom->GetHash() == txin.prevout.hash);
436 assert(txFrom->vout.size() > txin.prevout.n);
437 assert(txFrom->vout[txin.prevout.n] == coin.out);
438 } else {
439 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
440 assert(!coinFromDisk.IsSpent());
441 assert(coinFromDisk.out == coin.out);
445 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
448 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
449 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
450 bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
452 const CTransaction& tx = *ptx;
453 const uint256 hash = tx.GetHash();
454 AssertLockHeld(cs_main);
455 if (pfMissingInputs)
456 *pfMissingInputs = false;
458 if (!CheckTransaction(tx, state))
459 return false; // state filled in by CheckTransaction
461 // Coinbase is only valid in a block, not as a loose transaction
462 if (tx.IsCoinBase())
463 return state.DoS(100, false, REJECT_INVALID, "coinbase");
465 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
466 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
467 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
468 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
471 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
472 std::string reason;
473 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
474 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
476 // Only accept nLockTime-using transactions that can be mined in the next
477 // block; we don't want our mempool filled up with transactions that can't
478 // be mined yet.
479 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
480 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
482 // is it already in the memory pool?
483 if (pool.exists(hash)) {
484 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
487 // Check for conflicts with in-memory transactions
488 std::set<uint256> setConflicts;
490 LOCK(pool.cs); // protect pool.mapNextTx
491 for (const CTxIn &txin : tx.vin)
493 auto itConflicting = pool.mapNextTx.find(txin.prevout);
494 if (itConflicting != pool.mapNextTx.end())
496 const CTransaction *ptxConflicting = itConflicting->second;
497 if (!setConflicts.count(ptxConflicting->GetHash()))
499 // Allow opt-out of transaction replacement by setting
500 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
502 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
503 // non-replaceable transactions. All inputs rather than just one
504 // is for the sake of multi-party protocols, where we don't
505 // want a single party to be able to disable replacement.
507 // The opt-out ignores descendants as anyone relying on
508 // first-seen mempool behavior should be checking all
509 // unconfirmed ancestors anyway; doing otherwise is hopelessly
510 // insecure.
511 bool fReplacementOptOut = true;
512 if (fEnableReplacement)
514 for (const CTxIn &_txin : ptxConflicting->vin)
516 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
518 fReplacementOptOut = false;
519 break;
523 if (fReplacementOptOut) {
524 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
527 setConflicts.insert(ptxConflicting->GetHash());
534 CCoinsView dummy;
535 CCoinsViewCache view(&dummy);
537 LockPoints lp;
539 LOCK(pool.cs);
540 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
541 view.SetBackend(viewMemPool);
543 // do all inputs exist?
544 for (const CTxIn txin : tx.vin) {
545 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
546 coins_to_uncache.push_back(txin.prevout);
548 if (!view.HaveCoin(txin.prevout)) {
549 // Are inputs missing because we already have the tx?
550 for (size_t out = 0; out < tx.vout.size(); out++) {
551 // Optimistically just do efficient check of cache for outputs
552 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
553 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
556 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
557 if (pfMissingInputs) {
558 *pfMissingInputs = true;
560 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
564 // Bring the best block into scope
565 view.GetBestBlock();
567 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
568 view.SetBackend(dummy);
570 // Only accept BIP68 sequence locked transactions that can be mined in the next
571 // block; we don't want our mempool filled up with transactions that can't
572 // be mined yet.
573 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
574 // CoinsViewCache instead of create its own
575 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
576 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
578 } // end LOCK(pool.cs)
580 CAmount nFees = 0;
581 if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
582 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
585 // Check for non-standard pay-to-script-hash in inputs
586 if (fRequireStandard && !AreInputsStandard(tx, view))
587 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
589 // Check for non-standard witness in P2WSH
590 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
591 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
593 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
595 // nModifiedFees includes any fee deltas from PrioritiseTransaction
596 CAmount nModifiedFees = nFees;
597 pool.ApplyDelta(hash, nModifiedFees);
599 // Keep track of transactions that spend a coinbase, which we re-scan
600 // during reorgs to ensure COINBASE_MATURITY is still met.
601 bool fSpendsCoinbase = false;
602 for (const CTxIn &txin : tx.vin) {
603 const Coin &coin = view.AccessCoin(txin.prevout);
604 if (coin.IsCoinBase()) {
605 fSpendsCoinbase = true;
606 break;
610 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
611 fSpendsCoinbase, nSigOpsCost, lp);
612 unsigned int nSize = entry.GetTxSize();
614 // Check that the transaction doesn't have an excessive number of
615 // sigops, making it impossible to mine. Since the coinbase transaction
616 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
617 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
618 // merely non-standard transaction.
619 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
620 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
621 strprintf("%d", nSigOpsCost));
623 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
624 if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
625 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
628 // No transactions are allowed below minRelayTxFee except from disconnected blocks
629 if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
630 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
633 if (nAbsurdFee && nFees > nAbsurdFee)
634 return state.Invalid(false,
635 REJECT_HIGHFEE, "absurdly-high-fee",
636 strprintf("%d > %d", nFees, nAbsurdFee));
638 // Calculate in-mempool ancestors, up to a limit.
639 CTxMemPool::setEntries setAncestors;
640 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
641 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
642 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
643 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
644 std::string errString;
645 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
646 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
649 // A transaction that spends outputs that would be replaced by it is invalid. Now
650 // that we have the set of all ancestors we can detect this
651 // pathological case by making sure setConflicts and setAncestors don't
652 // intersect.
653 for (CTxMemPool::txiter ancestorIt : setAncestors)
655 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
656 if (setConflicts.count(hashAncestor))
658 return state.DoS(10, false,
659 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
660 strprintf("%s spends conflicting transaction %s",
661 hash.ToString(),
662 hashAncestor.ToString()));
666 // Check if it's economically rational to mine this transaction rather
667 // than the ones it replaces.
668 CAmount nConflictingFees = 0;
669 size_t nConflictingSize = 0;
670 uint64_t nConflictingCount = 0;
671 CTxMemPool::setEntries allConflicting;
673 // If we don't hold the lock allConflicting might be incomplete; the
674 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
675 // mempool consistency for us.
676 LOCK(pool.cs);
677 const bool fReplacementTransaction = setConflicts.size();
678 if (fReplacementTransaction)
680 CFeeRate newFeeRate(nModifiedFees, nSize);
681 std::set<uint256> setConflictsParents;
682 const int maxDescendantsToVisit = 100;
683 CTxMemPool::setEntries setIterConflicting;
684 for (const uint256 &hashConflicting : setConflicts)
686 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
687 if (mi == pool.mapTx.end())
688 continue;
690 // Save these to avoid repeated lookups
691 setIterConflicting.insert(mi);
693 // Don't allow the replacement to reduce the feerate of the
694 // mempool.
696 // We usually don't want to accept replacements with lower
697 // feerates than what they replaced as that would lower the
698 // feerate of the next block. Requiring that the feerate always
699 // be increased is also an easy-to-reason about way to prevent
700 // DoS attacks via replacements.
702 // The mining code doesn't (currently) take children into
703 // account (CPFP) so we only consider the feerates of
704 // transactions being directly replaced, not their indirect
705 // descendants. While that does mean high feerate children are
706 // ignored when deciding whether or not to replace, we do
707 // require the replacement to pay more overall fees too,
708 // mitigating most cases.
709 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
710 if (newFeeRate <= oldFeeRate)
712 return state.DoS(0, false,
713 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
714 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
715 hash.ToString(),
716 newFeeRate.ToString(),
717 oldFeeRate.ToString()));
720 for (const CTxIn &txin : mi->GetTx().vin)
722 setConflictsParents.insert(txin.prevout.hash);
725 nConflictingCount += mi->GetCountWithDescendants();
727 // This potentially overestimates the number of actual descendants
728 // but we just want to be conservative to avoid doing too much
729 // work.
730 if (nConflictingCount <= maxDescendantsToVisit) {
731 // If not too many to replace, then calculate the set of
732 // transactions that would have to be evicted
733 for (CTxMemPool::txiter it : setIterConflicting) {
734 pool.CalculateDescendants(it, allConflicting);
736 for (CTxMemPool::txiter it : allConflicting) {
737 nConflictingFees += it->GetModifiedFee();
738 nConflictingSize += it->GetTxSize();
740 } else {
741 return state.DoS(0, false,
742 REJECT_NONSTANDARD, "too many potential replacements", false,
743 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
744 hash.ToString(),
745 nConflictingCount,
746 maxDescendantsToVisit));
749 for (unsigned int j = 0; j < tx.vin.size(); j++)
751 // We don't want to accept replacements that require low
752 // feerate junk to be mined first. Ideally we'd keep track of
753 // the ancestor feerates and make the decision based on that,
754 // but for now requiring all new inputs to be confirmed works.
755 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
757 // Rather than check the UTXO set - potentially expensive -
758 // it's cheaper to just check if the new input refers to a
759 // tx that's in the mempool.
760 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
761 return state.DoS(0, false,
762 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
763 strprintf("replacement %s adds unconfirmed input, idx %d",
764 hash.ToString(), j));
768 // The replacement must pay greater fees than the transactions it
769 // replaces - if we did the bandwidth used by those conflicting
770 // transactions would not be paid for.
771 if (nModifiedFees < nConflictingFees)
773 return state.DoS(0, false,
774 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
775 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
776 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
779 // Finally in addition to paying more fees than the conflicts the
780 // new transaction must pay for its own bandwidth.
781 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
782 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
784 return state.DoS(0, false,
785 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
786 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
787 hash.ToString(),
788 FormatMoney(nDeltaFees),
789 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
793 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
794 if (!chainparams.RequireStandard()) {
795 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
798 // Check against previous transactions
799 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
800 PrecomputedTransactionData txdata(tx);
801 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
802 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
803 // need to turn both off, and compare against just turning off CLEANSTACK
804 // to see if the failure is specifically due to witness validation.
805 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
806 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
807 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
808 // Only the witness is missing, so the transaction itself may be fine.
809 state.SetCorruptionPossible();
811 return false; // state filled in by CheckInputs
814 // Check again against the current block tip's script verification
815 // flags to cache our script execution flags. This is, of course,
816 // useless if the next block has different script flags from the
817 // previous one, but because the cache tracks script flags for us it
818 // will auto-invalidate and we'll just have a few blocks of extra
819 // misses on soft-fork activation.
821 // This is also useful in case of bugs in the standard flags that cause
822 // transactions to pass as valid when they're actually invalid. For
823 // instance the STRICTENC flag was incorrectly allowing certain
824 // CHECKSIG NOT scripts to pass, even though they were invalid.
826 // There is a similar check in CreateNewBlock() to prevent creating
827 // invalid blocks (using TestBlockValidity), however allowing such
828 // transactions into the mempool can be exploited as a DoS attack.
829 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
830 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
832 // If we're using promiscuousmempoolflags, we may hit this normally
833 // Check if current block has some flags that scriptVerifyFlags
834 // does not before printing an ominous warning
835 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
836 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
837 __func__, hash.ToString(), FormatStateMessage(state));
838 } else {
839 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
840 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
841 __func__, hash.ToString(), FormatStateMessage(state));
842 } else {
843 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
848 // Remove conflicting transactions from the mempool
849 for (const CTxMemPool::txiter it : allConflicting)
851 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
852 it->GetTx().GetHash().ToString(),
853 hash.ToString(),
854 FormatMoney(nModifiedFees - nConflictingFees),
855 (int)nSize - (int)nConflictingSize);
856 if (plTxnReplaced)
857 plTxnReplaced->push_back(it->GetSharedTx());
859 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
861 // This transaction should only count for fee estimation if:
862 // - it isn't a BIP 125 replacement transaction (may not be widely supported)
863 // - it's not being readded during a reorg which bypasses typical mempool fee limits
864 // - the node is not behind
865 // - the transaction is not dependent on any other transactions in the mempool
866 bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
868 // Store transaction in memory
869 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
871 // trim mempool and check if tx was trimmed
872 if (!bypass_limits) {
873 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
874 if (!pool.exists(hash))
875 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
879 GetMainSignals().TransactionAddedToMempool(ptx);
881 return true;
884 /** (try to) add transaction to memory pool with a specified acceptance time **/
885 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
886 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
887 bool bypass_limits, const CAmount nAbsurdFee)
889 std::vector<COutPoint> coins_to_uncache;
890 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
891 if (!res) {
892 for (const COutPoint& hashTx : coins_to_uncache)
893 pcoinsTip->Uncache(hashTx);
895 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
896 CValidationState stateDummy;
897 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
898 return res;
901 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
902 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
903 bool bypass_limits, const CAmount nAbsurdFee)
905 const CChainParams& chainparams = Params();
906 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
909 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
910 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
912 CBlockIndex *pindexSlow = nullptr;
914 LOCK(cs_main);
916 CTransactionRef ptx = mempool.get(hash);
917 if (ptx)
919 txOut = ptx;
920 return true;
923 if (fTxIndex) {
924 CDiskTxPos postx;
925 if (pblocktree->ReadTxIndex(hash, postx)) {
926 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
927 if (file.IsNull())
928 return error("%s: OpenBlockFile failed", __func__);
929 CBlockHeader header;
930 try {
931 file >> header;
932 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
933 file >> txOut;
934 } catch (const std::exception& e) {
935 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
937 hashBlock = header.GetHash();
938 if (txOut->GetHash() != hash)
939 return error("%s: txid mismatch", __func__);
940 return true;
944 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
945 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
946 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
949 if (pindexSlow) {
950 CBlock block;
951 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
952 for (const auto& tx : block.vtx) {
953 if (tx->GetHash() == hash) {
954 txOut = tx;
955 hashBlock = pindexSlow->GetBlockHash();
956 return true;
962 return false;
970 //////////////////////////////////////////////////////////////////////////////
972 // CBlock and CBlockIndex
975 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
977 // Open history file to append
978 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
979 if (fileout.IsNull())
980 return error("WriteBlockToDisk: OpenBlockFile failed");
982 // Write index header
983 unsigned int nSize = GetSerializeSize(fileout, block);
984 fileout << FLATDATA(messageStart) << nSize;
986 // Write block
987 long fileOutPos = ftell(fileout.Get());
988 if (fileOutPos < 0)
989 return error("WriteBlockToDisk: ftell failed");
990 pos.nPos = (unsigned int)fileOutPos;
991 fileout << block;
993 return true;
996 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
998 block.SetNull();
1000 // Open history file to read
1001 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1002 if (filein.IsNull())
1003 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1005 // Read block
1006 try {
1007 filein >> block;
1009 catch (const std::exception& e) {
1010 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1013 // Check the header
1014 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1015 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1017 return true;
1020 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1022 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1023 return false;
1024 if (block.GetHash() != pindex->GetBlockHash())
1025 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1026 pindex->ToString(), pindex->GetBlockPos().ToString());
1027 return true;
1030 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1032 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1033 // Force block reward to zero when right shift is undefined.
1034 if (halvings >= 64)
1035 return 0;
1037 CAmount nSubsidy = 50 * COIN;
1038 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1039 nSubsidy >>= halvings;
1040 return nSubsidy;
1043 bool IsInitialBlockDownload()
1045 // Once this function has returned false, it must remain false.
1046 static std::atomic<bool> latchToFalse{false};
1047 // Optimization: pre-test latch before taking the lock.
1048 if (latchToFalse.load(std::memory_order_relaxed))
1049 return false;
1051 LOCK(cs_main);
1052 if (latchToFalse.load(std::memory_order_relaxed))
1053 return false;
1054 if (fImporting || fReindex)
1055 return true;
1056 if (chainActive.Tip() == nullptr)
1057 return true;
1058 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1059 return true;
1060 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1061 return true;
1062 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1063 latchToFalse.store(true, std::memory_order_relaxed);
1064 return false;
1067 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1069 static void AlertNotify(const std::string& strMessage)
1071 uiInterface.NotifyAlertChanged();
1072 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1073 if (strCmd.empty()) return;
1075 // Alert text should be plain ascii coming from a trusted source, but to
1076 // be safe we first strip anything not in safeChars, then add single quotes around
1077 // the whole string before passing it to the shell:
1078 std::string singleQuote("'");
1079 std::string safeStatus = SanitizeString(strMessage);
1080 safeStatus = singleQuote+safeStatus+singleQuote;
1081 boost::replace_all(strCmd, "%s", safeStatus);
1083 boost::thread t(runCommand, strCmd); // thread runs free
1086 static void CheckForkWarningConditions()
1088 AssertLockHeld(cs_main);
1089 // Before we get past initial download, we cannot reliably alert about forks
1090 // (we assume we don't get stuck on a fork before finishing our initial sync)
1091 if (IsInitialBlockDownload())
1092 return;
1094 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1095 // of our head, drop it
1096 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1097 pindexBestForkTip = nullptr;
1099 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1101 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1103 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1104 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1105 AlertNotify(warning);
1107 if (pindexBestForkTip && pindexBestForkBase)
1109 LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
1110 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1111 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1112 SetfLargeWorkForkFound(true);
1114 else
1116 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1117 SetfLargeWorkInvalidChainFound(true);
1120 else
1122 SetfLargeWorkForkFound(false);
1123 SetfLargeWorkInvalidChainFound(false);
1127 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1129 AssertLockHeld(cs_main);
1130 // If we are on a fork that is sufficiently large, set a warning flag
1131 CBlockIndex* pfork = pindexNewForkTip;
1132 CBlockIndex* plonger = chainActive.Tip();
1133 while (pfork && pfork != plonger)
1135 while (plonger && plonger->nHeight > pfork->nHeight)
1136 plonger = plonger->pprev;
1137 if (pfork == plonger)
1138 break;
1139 pfork = pfork->pprev;
1142 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1143 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1144 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1145 // hash rate operating on the fork.
1146 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1147 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1148 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1149 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1150 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1151 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1153 pindexBestForkTip = pindexNewForkTip;
1154 pindexBestForkBase = pfork;
1157 CheckForkWarningConditions();
1160 void static InvalidChainFound(CBlockIndex* pindexNew)
1162 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1163 pindexBestInvalid = pindexNew;
1165 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1166 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1167 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1168 pindexNew->GetBlockTime()));
1169 CBlockIndex *tip = chainActive.Tip();
1170 assert (tip);
1171 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1172 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1173 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1174 CheckForkWarningConditions();
1177 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1178 if (!state.CorruptionPossible()) {
1179 pindex->nStatus |= BLOCK_FAILED_VALID;
1180 setDirtyBlockIndex.insert(pindex);
1181 setBlockIndexCandidates.erase(pindex);
1182 InvalidChainFound(pindex);
1186 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1188 // mark inputs spent
1189 if (!tx.IsCoinBase()) {
1190 txundo.vprevout.reserve(tx.vin.size());
1191 for (const CTxIn &txin : tx.vin) {
1192 txundo.vprevout.emplace_back();
1193 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1194 assert(is_spent);
1197 // add outputs
1198 AddCoins(inputs, tx, nHeight);
1201 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1203 CTxUndo txundo;
1204 UpdateCoins(tx, inputs, txundo, nHeight);
1207 bool CScriptCheck::operator()() {
1208 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1209 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1210 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1213 int GetSpendHeight(const CCoinsViewCache& inputs)
1215 LOCK(cs_main);
1216 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1217 return pindexPrev->nHeight + 1;
1221 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1222 static uint256 scriptExecutionCacheNonce(GetRandHash());
1224 void InitScriptExecutionCache() {
1225 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1226 // setup_bytes creates the minimum possible cache (2 elements).
1227 size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1228 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1229 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1230 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1234 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1235 * This does not modify the UTXO set.
1237 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1238 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1239 * not pushed onto pvChecks/run.
1241 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1242 * which are matched. This is useful for checking blocks where we will likely never need the cache
1243 * entry again.
1245 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1247 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1249 if (!tx.IsCoinBase())
1251 if (pvChecks)
1252 pvChecks->reserve(tx.vin.size());
1254 // The first loop above does all the inexpensive checks.
1255 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1256 // Helps prevent CPU exhaustion attacks.
1258 // Skip script verification when connecting blocks under the
1259 // assumevalid block. Assuming the assumevalid block is valid this
1260 // is safe because block merkle hashes are still computed and checked,
1261 // Of course, if an assumed valid block is invalid due to false scriptSigs
1262 // this optimization would allow an invalid chain to be accepted.
1263 if (fScriptChecks) {
1264 // First check if script executions have been cached with the same
1265 // flags. Note that this assumes that the inputs provided are
1266 // correct (ie that the transaction hash which is in tx's prevouts
1267 // properly commits to the scriptPubKey in the inputs view of that
1268 // transaction).
1269 uint256 hashCacheEntry;
1270 // We only use the first 19 bytes of nonce to avoid a second SHA
1271 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1272 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1273 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1274 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1275 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1276 return true;
1279 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1280 const COutPoint &prevout = tx.vin[i].prevout;
1281 const Coin& coin = inputs.AccessCoin(prevout);
1282 assert(!coin.IsSpent());
1284 // We very carefully only pass in things to CScriptCheck which
1285 // are clearly committed to by tx' witness hash. This provides
1286 // a sanity check that our caching is not introducing consensus
1287 // failures through additional data in, eg, the coins being
1288 // spent being checked as a part of CScriptCheck.
1290 // Verify signature
1291 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1292 if (pvChecks) {
1293 pvChecks->push_back(CScriptCheck());
1294 check.swap(pvChecks->back());
1295 } else if (!check()) {
1296 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1297 // Check whether the failure was caused by a
1298 // non-mandatory script verification check, such as
1299 // non-standard DER encodings or non-null dummy
1300 // arguments; if so, don't trigger DoS protection to
1301 // avoid splitting the network between upgraded and
1302 // non-upgraded nodes.
1303 CScriptCheck check2(coin.out, tx, i,
1304 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1305 if (check2())
1306 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1308 // Failures of other flags indicate a transaction that is
1309 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1310 // such nodes as they are not following the protocol. That
1311 // said during an upgrade careful thought should be taken
1312 // as to the correct behavior - we may want to continue
1313 // peering with non-upgraded nodes even after soft-fork
1314 // super-majority signaling has occurred.
1315 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1319 if (cacheFullScriptStore && !pvChecks) {
1320 // We executed all of the provided scripts, and were told to
1321 // cache the result. Do so now.
1322 scriptExecutionCache.insert(hashCacheEntry);
1327 return true;
1330 namespace {
1332 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1334 // Open history file to append
1335 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1336 if (fileout.IsNull())
1337 return error("%s: OpenUndoFile failed", __func__);
1339 // Write index header
1340 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1341 fileout << FLATDATA(messageStart) << nSize;
1343 // Write undo data
1344 long fileOutPos = ftell(fileout.Get());
1345 if (fileOutPos < 0)
1346 return error("%s: ftell failed", __func__);
1347 pos.nPos = (unsigned int)fileOutPos;
1348 fileout << blockundo;
1350 // calculate & write checksum
1351 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1352 hasher << hashBlock;
1353 hasher << blockundo;
1354 fileout << hasher.GetHash();
1356 return true;
1359 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1361 // Open history file to read
1362 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1363 if (filein.IsNull())
1364 return error("%s: OpenUndoFile failed", __func__);
1366 // Read block
1367 uint256 hashChecksum;
1368 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1369 try {
1370 verifier << hashBlock;
1371 verifier >> blockundo;
1372 filein >> hashChecksum;
1374 catch (const std::exception& e) {
1375 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1378 // Verify checksum
1379 if (hashChecksum != verifier.GetHash())
1380 return error("%s: Checksum mismatch", __func__);
1382 return true;
1385 /** Abort with a message */
1386 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1388 SetMiscWarning(strMessage);
1389 LogPrintf("*** %s\n", strMessage);
1390 uiInterface.ThreadSafeMessageBox(
1391 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1392 "", CClientUIInterface::MSG_ERROR);
1393 StartShutdown();
1394 return false;
1397 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1399 AbortNode(strMessage, userMessage);
1400 return state.Error(strMessage);
1403 } // namespace
1405 enum DisconnectResult
1407 DISCONNECT_OK, // All good.
1408 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1409 DISCONNECT_FAILED // Something else went wrong.
1413 * Restore the UTXO in a Coin at a given COutPoint
1414 * @param undo The Coin to be restored.
1415 * @param view The coins view to which to apply the changes.
1416 * @param out The out point that corresponds to the tx input.
1417 * @return A DisconnectResult as an int
1419 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1421 bool fClean = true;
1423 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1425 if (undo.nHeight == 0) {
1426 // Missing undo metadata (height and coinbase). Older versions included this
1427 // information only in undo records for the last spend of a transactions'
1428 // outputs. This implies that it must be present for some other output of the same tx.
1429 const Coin& alternate = AccessByTxid(view, out.hash);
1430 if (!alternate.IsSpent()) {
1431 undo.nHeight = alternate.nHeight;
1432 undo.fCoinBase = alternate.fCoinBase;
1433 } else {
1434 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1437 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1438 // sure that the coin did not already exist in the cache. As we have queried for that above
1439 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1440 // it is an overwrite.
1441 view.AddCoin(out, std::move(undo), !fClean);
1443 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1446 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1447 * When FAILED is returned, view is left in an indeterminate state. */
1448 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1450 bool fClean = true;
1452 CBlockUndo blockUndo;
1453 CDiskBlockPos pos = pindex->GetUndoPos();
1454 if (pos.IsNull()) {
1455 error("DisconnectBlock(): no undo data available");
1456 return DISCONNECT_FAILED;
1458 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1459 error("DisconnectBlock(): failure reading undo data");
1460 return DISCONNECT_FAILED;
1463 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1464 error("DisconnectBlock(): block and undo data inconsistent");
1465 return DISCONNECT_FAILED;
1468 // undo transactions in reverse order
1469 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1470 const CTransaction &tx = *(block.vtx[i]);
1471 uint256 hash = tx.GetHash();
1472 bool is_coinbase = tx.IsCoinBase();
1474 // Check that all outputs are available and match the outputs in the block itself
1475 // exactly.
1476 for (size_t o = 0; o < tx.vout.size(); o++) {
1477 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1478 COutPoint out(hash, o);
1479 Coin coin;
1480 bool is_spent = view.SpendCoin(out, &coin);
1481 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1482 fClean = false; // transaction output mismatch
1487 // restore inputs
1488 if (i > 0) { // not coinbases
1489 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1490 if (txundo.vprevout.size() != tx.vin.size()) {
1491 error("DisconnectBlock(): transaction and undo data inconsistent");
1492 return DISCONNECT_FAILED;
1494 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1495 const COutPoint &out = tx.vin[j].prevout;
1496 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1497 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1498 fClean = fClean && res != DISCONNECT_UNCLEAN;
1500 // At this point, all of txundo.vprevout should have been moved out.
1504 // move best block pointer to prevout block
1505 view.SetBestBlock(pindex->pprev->GetBlockHash());
1507 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1510 void static FlushBlockFile(bool fFinalize = false)
1512 LOCK(cs_LastBlockFile);
1514 CDiskBlockPos posOld(nLastBlockFile, 0);
1516 FILE *fileOld = OpenBlockFile(posOld);
1517 if (fileOld) {
1518 if (fFinalize)
1519 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1520 FileCommit(fileOld);
1521 fclose(fileOld);
1524 fileOld = OpenUndoFile(posOld);
1525 if (fileOld) {
1526 if (fFinalize)
1527 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1528 FileCommit(fileOld);
1529 fclose(fileOld);
1533 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1535 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1537 void ThreadScriptCheck() {
1538 RenameThread("bitcoin-scriptch");
1539 scriptcheckqueue.Thread();
1542 // Protected by cs_main
1543 VersionBitsCache versionbitscache;
1545 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1547 LOCK(cs_main);
1548 int32_t nVersion = VERSIONBITS_TOP_BITS;
1550 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1551 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1552 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1553 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1557 return nVersion;
1561 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1563 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1565 private:
1566 int bit;
1568 public:
1569 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1571 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1572 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1573 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1574 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1576 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1578 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1579 ((pindex->nVersion >> bit) & 1) != 0 &&
1580 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1584 // Protected by cs_main
1585 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1587 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1588 AssertLockHeld(cs_main);
1590 // BIP16 didn't become active until Apr 1 2012
1591 int64_t nBIP16SwitchTime = 1333238400;
1592 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1594 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1596 // Start enforcing the DERSIG (BIP66) rule
1597 if (pindex->nHeight >= consensusparams.BIP66Height) {
1598 flags |= SCRIPT_VERIFY_DERSIG;
1601 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1602 if (pindex->nHeight >= consensusparams.BIP65Height) {
1603 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1606 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1607 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1608 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1611 // Start enforcing WITNESS rules using versionbits logic.
1612 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1613 flags |= SCRIPT_VERIFY_WITNESS;
1614 flags |= SCRIPT_VERIFY_NULLDUMMY;
1617 return flags;
1622 static int64_t nTimeCheck = 0;
1623 static int64_t nTimeForks = 0;
1624 static int64_t nTimeVerify = 0;
1625 static int64_t nTimeConnect = 0;
1626 static int64_t nTimeIndex = 0;
1627 static int64_t nTimeCallbacks = 0;
1628 static int64_t nTimeTotal = 0;
1629 static int64_t nBlocksTotal = 0;
1631 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1632 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1633 * can fail if those validity checks fail (among other reasons). */
1634 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1635 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1637 AssertLockHeld(cs_main);
1638 assert(pindex);
1639 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1640 assert((pindex->phashBlock == nullptr) ||
1641 (*pindex->phashBlock == block.GetHash()));
1642 int64_t nTimeStart = GetTimeMicros();
1644 // Check it again in case a previous version let a bad block in
1645 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1646 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1648 // verify that the view's current state corresponds to the previous block
1649 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1650 assert(hashPrevBlock == view.GetBestBlock());
1652 // Special case for the genesis block, skipping connection of its transactions
1653 // (its coinbase is unspendable)
1654 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1655 if (!fJustCheck)
1656 view.SetBestBlock(pindex->GetBlockHash());
1657 return true;
1660 nBlocksTotal++;
1662 bool fScriptChecks = true;
1663 if (!hashAssumeValid.IsNull()) {
1664 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1665 // A suitable default value is included with the software and updated from time to time. Because validity
1666 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1667 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1668 // effectively caching the result of part of the verification.
1669 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1670 if (it != mapBlockIndex.end()) {
1671 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1672 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1673 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1674 // This block is a member of the assumed verified chain and an ancestor of the best header.
1675 // The equivalent time check discourages hash power from extorting the network via DOS attack
1676 // into accepting an invalid block through telling users they must manually set assumevalid.
1677 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1678 // it hard to hide the implication of the demand. This also avoids having release candidates
1679 // that are hardly doing any signature verification at all in testing without having to
1680 // artificially set the default assumed verified block further back.
1681 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1682 // least as good as the expected chain.
1683 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1688 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1689 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1691 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1692 // unless those are already completely spent.
1693 // If such overwrites are allowed, coinbases and transactions depending upon those
1694 // can be duplicated to remove the ability to spend the first instance -- even after
1695 // being sent to another address.
1696 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1697 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1698 // already refuses previously-known transaction ids entirely.
1699 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1700 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1701 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1702 // initial block download.
1703 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1704 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1705 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1707 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1708 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1709 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1710 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1711 // duplicate transactions descending from the known pairs either.
1712 // 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.
1713 assert(pindex->pprev);
1714 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1715 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1716 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1718 if (fEnforceBIP30) {
1719 for (const auto& tx : block.vtx) {
1720 for (size_t o = 0; o < tx->vout.size(); o++) {
1721 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1722 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1723 REJECT_INVALID, "bad-txns-BIP30");
1729 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1730 int nLockTimeFlags = 0;
1731 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1732 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1735 // Get the script flags for this block
1736 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1738 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1739 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1741 CBlockUndo blockundo;
1743 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1745 std::vector<int> prevheights;
1746 CAmount nFees = 0;
1747 int nInputs = 0;
1748 int64_t nSigOpsCost = 0;
1749 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1750 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1751 vPos.reserve(block.vtx.size());
1752 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1753 std::vector<PrecomputedTransactionData> txdata;
1754 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1755 for (unsigned int i = 0; i < block.vtx.size(); i++)
1757 const CTransaction &tx = *(block.vtx[i]);
1759 nInputs += tx.vin.size();
1761 if (!tx.IsCoinBase())
1763 CAmount txfee = 0;
1764 if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
1765 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
1767 nFees += txfee;
1768 if (!MoneyRange(nFees)) {
1769 return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
1770 REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
1773 // Check that transaction is BIP68 final
1774 // BIP68 lock checks (as opposed to nLockTime checks) must
1775 // be in ConnectBlock because they require the UTXO set
1776 prevheights.resize(tx.vin.size());
1777 for (size_t j = 0; j < tx.vin.size(); j++) {
1778 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1781 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1782 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1783 REJECT_INVALID, "bad-txns-nonfinal");
1787 // GetTransactionSigOpCost counts 3 types of sigops:
1788 // * legacy (always)
1789 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1790 // * witness (when witness enabled in flags and excludes coinbase)
1791 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1792 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1793 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1794 REJECT_INVALID, "bad-blk-sigops");
1796 txdata.emplace_back(tx);
1797 if (!tx.IsCoinBase())
1799 std::vector<CScriptCheck> vChecks;
1800 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1801 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1802 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1803 tx.GetHash().ToString(), FormatStateMessage(state));
1804 control.Add(vChecks);
1807 CTxUndo undoDummy;
1808 if (i > 0) {
1809 blockundo.vtxundo.push_back(CTxUndo());
1811 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1813 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1814 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1816 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1817 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);
1819 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1820 if (block.vtx[0]->GetValueOut() > blockReward)
1821 return state.DoS(100,
1822 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1823 block.vtx[0]->GetValueOut(), blockReward),
1824 REJECT_INVALID, "bad-cb-amount");
1826 if (!control.Wait())
1827 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1828 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1829 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);
1831 if (fJustCheck)
1832 return true;
1834 // Write undo information to disk
1835 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1837 if (pindex->GetUndoPos().IsNull()) {
1838 CDiskBlockPos _pos;
1839 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1840 return error("ConnectBlock(): FindUndoPos failed");
1841 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1842 return AbortNode(state, "Failed to write undo data");
1844 // update nUndoPos in block index
1845 pindex->nUndoPos = _pos.nPos;
1846 pindex->nStatus |= BLOCK_HAVE_UNDO;
1849 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1850 setDirtyBlockIndex.insert(pindex);
1853 if (fTxIndex)
1854 if (!pblocktree->WriteTxIndex(vPos))
1855 return AbortNode(state, "Failed to write transaction index");
1857 assert(pindex->phashBlock);
1858 // add this block to the view's block chain
1859 view.SetBestBlock(pindex->GetBlockHash());
1861 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1862 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1864 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1865 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1867 return true;
1871 * Update the on-disk chain state.
1872 * The caches and indexes are flushed depending on the mode we're called with
1873 * if they're too large, if it's been a while since the last write,
1874 * or always and in all cases if we're in prune mode and are deleting files.
1876 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1877 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1878 LOCK(cs_main);
1879 static int64_t nLastWrite = 0;
1880 static int64_t nLastFlush = 0;
1881 static int64_t nLastSetChain = 0;
1882 std::set<int> setFilesToPrune;
1883 bool fFlushForPrune = false;
1884 bool fDoFullFlush = false;
1885 int64_t nNow = 0;
1886 try {
1888 LOCK(cs_LastBlockFile);
1889 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1890 if (nManualPruneHeight > 0) {
1891 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1892 } else {
1893 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1894 fCheckForPruning = false;
1896 if (!setFilesToPrune.empty()) {
1897 fFlushForPrune = true;
1898 if (!fHavePruned) {
1899 pblocktree->WriteFlag("prunedblockfiles", true);
1900 fHavePruned = true;
1904 nNow = GetTimeMicros();
1905 // Avoid writing/flushing immediately after startup.
1906 if (nLastWrite == 0) {
1907 nLastWrite = nNow;
1909 if (nLastFlush == 0) {
1910 nLastFlush = nNow;
1912 if (nLastSetChain == 0) {
1913 nLastSetChain = nNow;
1915 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1916 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1917 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1918 // 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).
1919 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1920 // The cache is over the limit, we have to write now.
1921 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1922 // 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.
1923 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1924 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1925 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1926 // Combine all conditions that result in a full cache flush.
1927 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1928 // Write blocks and block index to disk.
1929 if (fDoFullFlush || fPeriodicWrite) {
1930 // Depend on nMinDiskSpace to ensure we can write block index
1931 if (!CheckDiskSpace(0))
1932 return state.Error("out of disk space");
1933 // First make sure all block and undo data is flushed to disk.
1934 FlushBlockFile();
1935 // Then update all block file information (which may refer to block and undo files).
1937 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1938 vFiles.reserve(setDirtyFileInfo.size());
1939 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1940 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1941 setDirtyFileInfo.erase(it++);
1943 std::vector<const CBlockIndex*> vBlocks;
1944 vBlocks.reserve(setDirtyBlockIndex.size());
1945 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1946 vBlocks.push_back(*it);
1947 setDirtyBlockIndex.erase(it++);
1949 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1950 return AbortNode(state, "Failed to write to block index database");
1953 // Finally remove any pruned files
1954 if (fFlushForPrune)
1955 UnlinkPrunedFiles(setFilesToPrune);
1956 nLastWrite = nNow;
1958 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1959 if (fDoFullFlush) {
1960 // Typical Coin structures on disk are around 48 bytes in size.
1961 // Pushing a new one to the database can cause it to be written
1962 // twice (once in the log, and once in the tables). This is already
1963 // an overestimation, as most will delete an existing entry or
1964 // overwrite one. Still, use a conservative safety factor of 2.
1965 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1966 return state.Error("out of disk space");
1967 // Flush the chainstate (which may refer to block index entries).
1968 if (!pcoinsTip->Flush())
1969 return AbortNode(state, "Failed to write to coin database");
1970 nLastFlush = nNow;
1973 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1974 // Update best block in wallet (so we can detect restored wallets).
1975 GetMainSignals().SetBestChain(chainActive.GetLocator());
1976 nLastSetChain = nNow;
1978 } catch (const std::runtime_error& e) {
1979 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1981 return true;
1984 void FlushStateToDisk() {
1985 CValidationState state;
1986 const CChainParams& chainparams = Params();
1987 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
1990 void PruneAndFlush() {
1991 CValidationState state;
1992 fCheckForPruning = true;
1993 const CChainParams& chainparams = Params();
1994 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
1997 static void DoWarning(const std::string& strWarning)
1999 static bool fWarned = false;
2000 SetMiscWarning(strWarning);
2001 if (!fWarned) {
2002 AlertNotify(strWarning);
2003 fWarned = true;
2007 /** Update chainActive and related internal data structures. */
2008 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2009 chainActive.SetTip(pindexNew);
2011 // New best block
2012 mempool.AddTransactionsUpdated(1);
2014 cvBlockChange.notify_all();
2016 std::vector<std::string> warningMessages;
2017 if (!IsInitialBlockDownload())
2019 int nUpgraded = 0;
2020 const CBlockIndex* pindex = chainActive.Tip();
2021 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2022 WarningBitsConditionChecker checker(bit);
2023 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2024 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2025 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2026 if (state == THRESHOLD_ACTIVE) {
2027 DoWarning(strWarning);
2028 } else {
2029 warningMessages.push_back(strWarning);
2033 // Check the version of the last 100 blocks to see if we need to upgrade:
2034 for (int i = 0; i < 100 && pindex != nullptr; i++)
2036 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2037 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2038 ++nUpgraded;
2039 pindex = pindex->pprev;
2041 if (nUpgraded > 0)
2042 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2043 if (nUpgraded > 100/2)
2045 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2046 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2047 DoWarning(strWarning);
2050 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2051 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2052 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2053 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2054 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2055 if (!warningMessages.empty())
2056 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2057 LogPrintf("\n");
2061 /** Disconnect chainActive's tip.
2062 * After calling, the mempool will be in an inconsistent state, with
2063 * transactions from disconnected blocks being added to disconnectpool. You
2064 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2065 * with cs_main held.
2067 * If disconnectpool is nullptr, then no disconnected transactions are added to
2068 * disconnectpool (note that the caller is responsible for mempool consistency
2069 * in any case).
2071 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2073 CBlockIndex *pindexDelete = chainActive.Tip();
2074 assert(pindexDelete);
2075 // Read block from disk.
2076 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2077 CBlock& block = *pblock;
2078 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2079 return AbortNode(state, "Failed to read block");
2080 // Apply the block atomically to the chain state.
2081 int64_t nStart = GetTimeMicros();
2083 CCoinsViewCache view(pcoinsTip);
2084 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2085 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2086 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2087 bool flushed = view.Flush();
2088 assert(flushed);
2090 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2091 // Write the chain state to disk, if necessary.
2092 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2093 return false;
2095 if (disconnectpool) {
2096 // Save transactions to re-add to mempool at end of reorg
2097 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2098 disconnectpool->addTransaction(*it);
2100 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2101 // Drop the earliest entry, and remove its children from the mempool.
2102 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2103 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2104 disconnectpool->removeEntry(it);
2108 // Update chainActive and related variables.
2109 UpdateTip(pindexDelete->pprev, chainparams);
2110 // Let wallets know transactions went from 1-confirmed to
2111 // 0-confirmed or conflicted:
2112 GetMainSignals().BlockDisconnected(pblock);
2113 return true;
2116 static int64_t nTimeReadFromDisk = 0;
2117 static int64_t nTimeConnectTotal = 0;
2118 static int64_t nTimeFlush = 0;
2119 static int64_t nTimeChainState = 0;
2120 static int64_t nTimePostConnect = 0;
2122 struct PerBlockConnectTrace {
2123 CBlockIndex* pindex = nullptr;
2124 std::shared_ptr<const CBlock> pblock;
2125 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2126 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2129 * Used to track blocks whose transactions were applied to the UTXO state as a
2130 * part of a single ActivateBestChainStep call.
2132 * This class also tracks transactions that are removed from the mempool as
2133 * conflicts (per block) and can be used to pass all those transactions
2134 * through SyncTransaction.
2136 * This class assumes (and asserts) that the conflicted transactions for a given
2137 * block are added via mempool callbacks prior to the BlockConnected() associated
2138 * with those transactions. If any transactions are marked conflicted, it is
2139 * assumed that an associated block will always be added.
2141 * This class is single-use, once you call GetBlocksConnected() you have to throw
2142 * it away and make a new one.
2144 class ConnectTrace {
2145 private:
2146 std::vector<PerBlockConnectTrace> blocksConnected;
2147 CTxMemPool &pool;
2149 public:
2150 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2151 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2154 ~ConnectTrace() {
2155 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2158 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2159 assert(!blocksConnected.back().pindex);
2160 assert(pindex);
2161 assert(pblock);
2162 blocksConnected.back().pindex = pindex;
2163 blocksConnected.back().pblock = std::move(pblock);
2164 blocksConnected.emplace_back();
2167 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2168 // We always keep one extra block at the end of our list because
2169 // blocks are added after all the conflicted transactions have
2170 // been filled in. Thus, the last entry should always be an empty
2171 // one waiting for the transactions from the next block. We pop
2172 // the last entry here to make sure the list we return is sane.
2173 assert(!blocksConnected.back().pindex);
2174 assert(blocksConnected.back().conflictedTxs->empty());
2175 blocksConnected.pop_back();
2176 return blocksConnected;
2179 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2180 assert(!blocksConnected.back().pindex);
2181 if (reason == MemPoolRemovalReason::CONFLICT) {
2182 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2188 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2189 * corresponding to pindexNew, to bypass loading it again from disk.
2191 * The block is added to connectTrace if connection succeeds.
2193 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2195 assert(pindexNew->pprev == chainActive.Tip());
2196 // Read block from disk.
2197 int64_t nTime1 = GetTimeMicros();
2198 std::shared_ptr<const CBlock> pthisBlock;
2199 if (!pblock) {
2200 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2201 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2202 return AbortNode(state, "Failed to read block");
2203 pthisBlock = pblockNew;
2204 } else {
2205 pthisBlock = pblock;
2207 const CBlock& blockConnecting = *pthisBlock;
2208 // Apply the block atomically to the chain state.
2209 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2210 int64_t nTime3;
2211 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2213 CCoinsViewCache view(pcoinsTip);
2214 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2215 GetMainSignals().BlockChecked(blockConnecting, state);
2216 if (!rv) {
2217 if (state.IsInvalid())
2218 InvalidBlockFound(pindexNew, state);
2219 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2221 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2222 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2223 bool flushed = view.Flush();
2224 assert(flushed);
2226 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2227 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2228 // Write the chain state to disk, if necessary.
2229 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2230 return false;
2231 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2232 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2233 // Remove conflicting transactions from the mempool.;
2234 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2235 disconnectpool.removeForBlock(blockConnecting.vtx);
2236 // Update chainActive & related variables.
2237 UpdateTip(pindexNew, chainparams);
2239 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2240 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2241 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2243 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2244 return true;
2248 * Return the tip of the chain with the most work in it, that isn't
2249 * known to be invalid (it's however far from certain to be valid).
2251 static CBlockIndex* FindMostWorkChain() {
2252 do {
2253 CBlockIndex *pindexNew = nullptr;
2255 // Find the best candidate header.
2257 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2258 if (it == setBlockIndexCandidates.rend())
2259 return nullptr;
2260 pindexNew = *it;
2263 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2264 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2265 CBlockIndex *pindexTest = pindexNew;
2266 bool fInvalidAncestor = false;
2267 while (pindexTest && !chainActive.Contains(pindexTest)) {
2268 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2270 // Pruned nodes may have entries in setBlockIndexCandidates for
2271 // which block files have been deleted. Remove those as candidates
2272 // for the most work chain if we come across them; we can't switch
2273 // to a chain unless we have all the non-active-chain parent blocks.
2274 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2275 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2276 if (fFailedChain || fMissingData) {
2277 // Candidate chain is not usable (either invalid or missing data)
2278 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2279 pindexBestInvalid = pindexNew;
2280 CBlockIndex *pindexFailed = pindexNew;
2281 // Remove the entire chain from the set.
2282 while (pindexTest != pindexFailed) {
2283 if (fFailedChain) {
2284 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2285 } else if (fMissingData) {
2286 // If we're missing data, then add back to mapBlocksUnlinked,
2287 // so that if the block arrives in the future we can try adding
2288 // to setBlockIndexCandidates again.
2289 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2291 setBlockIndexCandidates.erase(pindexFailed);
2292 pindexFailed = pindexFailed->pprev;
2294 setBlockIndexCandidates.erase(pindexTest);
2295 fInvalidAncestor = true;
2296 break;
2298 pindexTest = pindexTest->pprev;
2300 if (!fInvalidAncestor)
2301 return pindexNew;
2302 } while(true);
2305 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2306 static void PruneBlockIndexCandidates() {
2307 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2308 // reorganization to a better block fails.
2309 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2310 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2311 setBlockIndexCandidates.erase(it++);
2313 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2314 assert(!setBlockIndexCandidates.empty());
2318 * Try to make some progress towards making pindexMostWork the active block.
2319 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2321 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2323 AssertLockHeld(cs_main);
2324 const CBlockIndex *pindexOldTip = chainActive.Tip();
2325 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2327 // Disconnect active blocks which are no longer in the best chain.
2328 bool fBlocksDisconnected = false;
2329 DisconnectedBlockTransactions disconnectpool;
2330 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2331 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2332 // This is likely a fatal error, but keep the mempool consistent,
2333 // just in case. Only remove from the mempool in this case.
2334 UpdateMempoolForReorg(disconnectpool, false);
2335 return false;
2337 fBlocksDisconnected = true;
2340 // Build list of new blocks to connect.
2341 std::vector<CBlockIndex*> vpindexToConnect;
2342 bool fContinue = true;
2343 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2344 while (fContinue && nHeight != pindexMostWork->nHeight) {
2345 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2346 // a few blocks along the way.
2347 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2348 vpindexToConnect.clear();
2349 vpindexToConnect.reserve(nTargetHeight - nHeight);
2350 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2351 while (pindexIter && pindexIter->nHeight != nHeight) {
2352 vpindexToConnect.push_back(pindexIter);
2353 pindexIter = pindexIter->pprev;
2355 nHeight = nTargetHeight;
2357 // Connect new blocks.
2358 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2359 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2360 if (state.IsInvalid()) {
2361 // The block violates a consensus rule.
2362 if (!state.CorruptionPossible())
2363 InvalidChainFound(vpindexToConnect.back());
2364 state = CValidationState();
2365 fInvalidFound = true;
2366 fContinue = false;
2367 break;
2368 } else {
2369 // A system error occurred (disk space, database error, ...).
2370 // Make the mempool consistent with the current tip, just in case
2371 // any observers try to use it before shutdown.
2372 UpdateMempoolForReorg(disconnectpool, false);
2373 return false;
2375 } else {
2376 PruneBlockIndexCandidates();
2377 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2378 // We're in a better position than we were. Return temporarily to release the lock.
2379 fContinue = false;
2380 break;
2386 if (fBlocksDisconnected) {
2387 // If any blocks were disconnected, disconnectpool may be non empty. Add
2388 // any disconnected transactions back to the mempool.
2389 UpdateMempoolForReorg(disconnectpool, true);
2391 mempool.check(pcoinsTip);
2393 // Callbacks/notifications for a new best chain.
2394 if (fInvalidFound)
2395 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2396 else
2397 CheckForkWarningConditions();
2399 return true;
2402 static void NotifyHeaderTip() {
2403 bool fNotify = false;
2404 bool fInitialBlockDownload = false;
2405 static CBlockIndex* pindexHeaderOld = nullptr;
2406 CBlockIndex* pindexHeader = nullptr;
2408 LOCK(cs_main);
2409 pindexHeader = pindexBestHeader;
2411 if (pindexHeader != pindexHeaderOld) {
2412 fNotify = true;
2413 fInitialBlockDownload = IsInitialBlockDownload();
2414 pindexHeaderOld = pindexHeader;
2417 // Send block tip changed notifications without cs_main
2418 if (fNotify) {
2419 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2424 * Make the best chain active, in multiple steps. The result is either failure
2425 * or an activated best chain. pblock is either nullptr or a pointer to a block
2426 * that is already loaded (to avoid loading it again from disk).
2428 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2429 // Note that while we're often called here from ProcessNewBlock, this is
2430 // far from a guarantee. Things in the P2P/RPC will often end up calling
2431 // us in the middle of ProcessNewBlock - do not assume pblock is set
2432 // sanely for performance or correctness!
2434 CBlockIndex *pindexMostWork = nullptr;
2435 CBlockIndex *pindexNewTip = nullptr;
2436 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2437 do {
2438 boost::this_thread::interruption_point();
2439 if (ShutdownRequested())
2440 break;
2442 const CBlockIndex *pindexFork;
2443 bool fInitialDownload;
2445 LOCK(cs_main);
2446 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2448 CBlockIndex *pindexOldTip = chainActive.Tip();
2449 if (pindexMostWork == nullptr) {
2450 pindexMostWork = FindMostWorkChain();
2453 // Whether we have anything to do at all.
2454 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2455 return true;
2457 bool fInvalidFound = false;
2458 std::shared_ptr<const CBlock> nullBlockPtr;
2459 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2460 return false;
2462 if (fInvalidFound) {
2463 // Wipe cache, we may need another branch now.
2464 pindexMostWork = nullptr;
2466 pindexNewTip = chainActive.Tip();
2467 pindexFork = chainActive.FindFork(pindexOldTip);
2468 fInitialDownload = IsInitialBlockDownload();
2470 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2471 assert(trace.pblock && trace.pindex);
2472 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2475 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2477 // Notifications/callbacks that can run without cs_main
2479 // Notify external listeners about the new tip.
2480 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2482 // Always notify the UI if a new block tip was connected
2483 if (pindexFork != pindexNewTip) {
2484 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2487 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2488 } while (pindexNewTip != pindexMostWork);
2489 CheckBlockIndex(chainparams.GetConsensus());
2491 // Write changes periodically to disk, after relay.
2492 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2493 return false;
2496 return true;
2500 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2503 LOCK(cs_main);
2504 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2505 // Nothing to do, this block is not at the tip.
2506 return true;
2508 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2509 // The chain has been extended since the last call, reset the counter.
2510 nBlockReverseSequenceId = -1;
2512 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2513 setBlockIndexCandidates.erase(pindex);
2514 pindex->nSequenceId = nBlockReverseSequenceId;
2515 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2516 // We can't keep reducing the counter if somebody really wants to
2517 // call preciousblock 2**31-1 times on the same set of tips...
2518 nBlockReverseSequenceId--;
2520 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2521 setBlockIndexCandidates.insert(pindex);
2522 PruneBlockIndexCandidates();
2526 return ActivateBestChain(state, params);
2529 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2531 AssertLockHeld(cs_main);
2533 // Mark the block itself as invalid.
2534 pindex->nStatus |= BLOCK_FAILED_VALID;
2535 setDirtyBlockIndex.insert(pindex);
2536 setBlockIndexCandidates.erase(pindex);
2538 DisconnectedBlockTransactions disconnectpool;
2539 while (chainActive.Contains(pindex)) {
2540 CBlockIndex *pindexWalk = chainActive.Tip();
2541 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2542 setDirtyBlockIndex.insert(pindexWalk);
2543 setBlockIndexCandidates.erase(pindexWalk);
2544 // ActivateBestChain considers blocks already in chainActive
2545 // unconditionally valid already, so force disconnect away from it.
2546 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2547 // It's probably hopeless to try to make the mempool consistent
2548 // here if DisconnectTip failed, but we can try.
2549 UpdateMempoolForReorg(disconnectpool, false);
2550 return false;
2554 // DisconnectTip will add transactions to disconnectpool; try to add these
2555 // back to the mempool.
2556 UpdateMempoolForReorg(disconnectpool, true);
2558 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2559 // add it again.
2560 BlockMap::iterator it = mapBlockIndex.begin();
2561 while (it != mapBlockIndex.end()) {
2562 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2563 setBlockIndexCandidates.insert(it->second);
2565 it++;
2568 InvalidChainFound(pindex);
2569 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2570 return true;
2573 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2574 AssertLockHeld(cs_main);
2576 int nHeight = pindex->nHeight;
2578 // Remove the invalidity flag from this block and all its descendants.
2579 BlockMap::iterator it = mapBlockIndex.begin();
2580 while (it != mapBlockIndex.end()) {
2581 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2582 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2583 setDirtyBlockIndex.insert(it->second);
2584 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2585 setBlockIndexCandidates.insert(it->second);
2587 if (it->second == pindexBestInvalid) {
2588 // Reset invalid block marker if it was pointing to one of those.
2589 pindexBestInvalid = nullptr;
2592 it++;
2595 // Remove the invalidity flag from all ancestors too.
2596 while (pindex != nullptr) {
2597 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2598 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2599 setDirtyBlockIndex.insert(pindex);
2601 pindex = pindex->pprev;
2603 return true;
2606 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2608 // Check for duplicate
2609 uint256 hash = block.GetHash();
2610 BlockMap::iterator it = mapBlockIndex.find(hash);
2611 if (it != mapBlockIndex.end())
2612 return it->second;
2614 // Construct new block index object
2615 CBlockIndex* pindexNew = new CBlockIndex(block);
2616 // We assign the sequence id to blocks only when the full data is available,
2617 // to avoid miners withholding blocks but broadcasting headers, to get a
2618 // competitive advantage.
2619 pindexNew->nSequenceId = 0;
2620 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2621 pindexNew->phashBlock = &((*mi).first);
2622 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2623 if (miPrev != mapBlockIndex.end())
2625 pindexNew->pprev = (*miPrev).second;
2626 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2627 pindexNew->BuildSkip();
2629 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2630 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2631 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2632 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2633 pindexBestHeader = pindexNew;
2635 setDirtyBlockIndex.insert(pindexNew);
2637 return pindexNew;
2640 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2641 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2643 pindexNew->nTx = block.vtx.size();
2644 pindexNew->nChainTx = 0;
2645 pindexNew->nFile = pos.nFile;
2646 pindexNew->nDataPos = pos.nPos;
2647 pindexNew->nUndoPos = 0;
2648 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2649 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2650 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2652 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2653 setDirtyBlockIndex.insert(pindexNew);
2655 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2656 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2657 std::deque<CBlockIndex*> queue;
2658 queue.push_back(pindexNew);
2660 // Recursively process any descendant blocks that now may be eligible to be connected.
2661 while (!queue.empty()) {
2662 CBlockIndex *pindex = queue.front();
2663 queue.pop_front();
2664 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2666 LOCK(cs_nBlockSequenceId);
2667 pindex->nSequenceId = nBlockSequenceId++;
2669 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2670 setBlockIndexCandidates.insert(pindex);
2672 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2673 while (range.first != range.second) {
2674 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2675 queue.push_back(it->second);
2676 range.first++;
2677 mapBlocksUnlinked.erase(it);
2680 } else {
2681 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2682 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2686 return true;
2689 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2691 LOCK(cs_LastBlockFile);
2693 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2694 if (vinfoBlockFile.size() <= nFile) {
2695 vinfoBlockFile.resize(nFile + 1);
2698 if (!fKnown) {
2699 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2700 nFile++;
2701 if (vinfoBlockFile.size() <= nFile) {
2702 vinfoBlockFile.resize(nFile + 1);
2705 pos.nFile = nFile;
2706 pos.nPos = vinfoBlockFile[nFile].nSize;
2709 if ((int)nFile != nLastBlockFile) {
2710 if (!fKnown) {
2711 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2713 FlushBlockFile(!fKnown);
2714 nLastBlockFile = nFile;
2717 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2718 if (fKnown)
2719 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2720 else
2721 vinfoBlockFile[nFile].nSize += nAddSize;
2723 if (!fKnown) {
2724 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2725 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2726 if (nNewChunks > nOldChunks) {
2727 if (fPruneMode)
2728 fCheckForPruning = true;
2729 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2730 FILE *file = OpenBlockFile(pos);
2731 if (file) {
2732 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2733 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2734 fclose(file);
2737 else
2738 return state.Error("out of disk space");
2742 setDirtyFileInfo.insert(nFile);
2743 return true;
2746 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2748 pos.nFile = nFile;
2750 LOCK(cs_LastBlockFile);
2752 unsigned int nNewSize;
2753 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2754 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2755 setDirtyFileInfo.insert(nFile);
2757 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2758 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2759 if (nNewChunks > nOldChunks) {
2760 if (fPruneMode)
2761 fCheckForPruning = true;
2762 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2763 FILE *file = OpenUndoFile(pos);
2764 if (file) {
2765 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2766 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2767 fclose(file);
2770 else
2771 return state.Error("out of disk space");
2774 return true;
2777 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2779 // Check proof of work matches claimed amount
2780 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2781 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2783 return true;
2786 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2788 // These are checks that are independent of context.
2790 if (block.fChecked)
2791 return true;
2793 // Check that the header is valid (particularly PoW). This is mostly
2794 // redundant with the call in AcceptBlockHeader.
2795 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2796 return false;
2798 // Check the merkle root.
2799 if (fCheckMerkleRoot) {
2800 bool mutated;
2801 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2802 if (block.hashMerkleRoot != hashMerkleRoot2)
2803 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2805 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2806 // of transactions in a block without affecting the merkle root of a block,
2807 // while still invalidating it.
2808 if (mutated)
2809 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2812 // All potential-corruption validation must be done before we do any
2813 // transaction validation, as otherwise we may mark the header as invalid
2814 // because we receive the wrong transactions for it.
2815 // Note that witness malleability is checked in ContextualCheckBlock, so no
2816 // checks that use witness data may be performed here.
2818 // Size limits
2819 if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
2820 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2822 // First transaction must be coinbase, the rest must not be
2823 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2824 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2825 for (unsigned int i = 1; i < block.vtx.size(); i++)
2826 if (block.vtx[i]->IsCoinBase())
2827 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2829 // Check transactions
2830 for (const auto& tx : block.vtx)
2831 if (!CheckTransaction(*tx, state, false))
2832 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2833 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2835 unsigned int nSigOps = 0;
2836 for (const auto& tx : block.vtx)
2838 nSigOps += GetLegacySigOpCount(*tx);
2840 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2841 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2843 if (fCheckPOW && fCheckMerkleRoot)
2844 block.fChecked = true;
2846 return true;
2849 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2851 LOCK(cs_main);
2852 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2855 // Compute at which vout of the block's coinbase transaction the witness
2856 // commitment occurs, or -1 if not found.
2857 static int GetWitnessCommitmentIndex(const CBlock& block)
2859 int commitpos = -1;
2860 if (!block.vtx.empty()) {
2861 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2862 if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
2863 commitpos = o;
2867 return commitpos;
2870 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2872 int commitpos = GetWitnessCommitmentIndex(block);
2873 static const std::vector<unsigned char> nonce(32, 0x00);
2874 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2875 CMutableTransaction tx(*block.vtx[0]);
2876 tx.vin[0].scriptWitness.stack.resize(1);
2877 tx.vin[0].scriptWitness.stack[0] = nonce;
2878 block.vtx[0] = MakeTransactionRef(std::move(tx));
2882 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2884 std::vector<unsigned char> commitment;
2885 int commitpos = GetWitnessCommitmentIndex(block);
2886 std::vector<unsigned char> ret(32, 0x00);
2887 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2888 if (commitpos == -1) {
2889 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2890 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2891 CTxOut out;
2892 out.nValue = 0;
2893 out.scriptPubKey.resize(38);
2894 out.scriptPubKey[0] = OP_RETURN;
2895 out.scriptPubKey[1] = 0x24;
2896 out.scriptPubKey[2] = 0xaa;
2897 out.scriptPubKey[3] = 0x21;
2898 out.scriptPubKey[4] = 0xa9;
2899 out.scriptPubKey[5] = 0xed;
2900 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2901 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2902 CMutableTransaction tx(*block.vtx[0]);
2903 tx.vout.push_back(out);
2904 block.vtx[0] = MakeTransactionRef(std::move(tx));
2907 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2908 return commitment;
2911 /** Context-dependent validity checks.
2912 * By "context", we mean only the previous block headers, but not the UTXO
2913 * set; UTXO-related validity checks are done in ConnectBlock(). */
2914 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2916 assert(pindexPrev != nullptr);
2917 const int nHeight = pindexPrev->nHeight + 1;
2919 // Check proof of work
2920 const Consensus::Params& consensusParams = params.GetConsensus();
2921 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2922 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2924 // Check against checkpoints
2925 if (fCheckpointsEnabled) {
2926 // Don't accept any forks from the main chain prior to last checkpoint.
2927 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2928 // MapBlockIndex.
2929 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2930 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2931 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2934 // Check timestamp against prev
2935 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2936 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2938 // Check timestamp
2939 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2940 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2942 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2943 // check for version 2, 3 and 4 upgrades
2944 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2945 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2946 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2947 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2948 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2950 return true;
2953 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2955 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
2957 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2958 int nLockTimeFlags = 0;
2959 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2960 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2963 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2964 ? pindexPrev->GetMedianTimePast()
2965 : block.GetBlockTime();
2967 // Check that all transactions are finalized
2968 for (const auto& tx : block.vtx) {
2969 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2970 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2974 // Enforce rule that the coinbase starts with serialized block height
2975 if (nHeight >= consensusParams.BIP34Height)
2977 CScript expect = CScript() << nHeight;
2978 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2979 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2980 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2984 // Validation for witness commitments.
2985 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2986 // coinbase (where 0x0000....0000 is used instead).
2987 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2988 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2989 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2990 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2991 // multiple, the last one is used.
2992 bool fHaveWitness = false;
2993 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2994 int commitpos = GetWitnessCommitmentIndex(block);
2995 if (commitpos != -1) {
2996 bool malleated = false;
2997 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2998 // The malleation check is ignored; as the transaction tree itself
2999 // already does not permit it, it is impossible to trigger in the
3000 // witness tree.
3001 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3002 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3004 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3005 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3006 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3008 fHaveWitness = true;
3012 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3013 if (!fHaveWitness) {
3014 for (const auto& tx : block.vtx) {
3015 if (tx->HasWitness()) {
3016 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3021 // After the coinbase witness nonce and commitment are verified,
3022 // we can check if the block weight passes (before we've checked the
3023 // coinbase witness, it would be possible for the weight to be too
3024 // large by filling up the coinbase witness, which doesn't change
3025 // the block hash, so we couldn't mark the block as permanently
3026 // failed).
3027 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3028 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3031 return true;
3034 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3036 AssertLockHeld(cs_main);
3037 // Check for duplicate
3038 uint256 hash = block.GetHash();
3039 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3040 CBlockIndex *pindex = nullptr;
3041 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3043 if (miSelf != mapBlockIndex.end()) {
3044 // Block header is already known.
3045 pindex = miSelf->second;
3046 if (ppindex)
3047 *ppindex = pindex;
3048 if (pindex->nStatus & BLOCK_FAILED_MASK)
3049 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3050 return true;
3053 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3054 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3056 // Get prev block index
3057 CBlockIndex* pindexPrev = nullptr;
3058 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3059 if (mi == mapBlockIndex.end())
3060 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3061 pindexPrev = (*mi).second;
3062 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3063 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3064 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3065 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3067 if (pindex == nullptr)
3068 pindex = AddToBlockIndex(block);
3070 if (ppindex)
3071 *ppindex = pindex;
3073 CheckBlockIndex(chainparams.GetConsensus());
3075 return true;
3078 // Exposed wrapper for AcceptBlockHeader
3079 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3082 LOCK(cs_main);
3083 for (const CBlockHeader& header : headers) {
3084 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3085 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3086 return false;
3088 if (ppindex) {
3089 *ppindex = pindex;
3093 NotifyHeaderTip();
3094 return true;
3097 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3098 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3100 const CBlock& block = *pblock;
3102 if (fNewBlock) *fNewBlock = false;
3103 AssertLockHeld(cs_main);
3105 CBlockIndex *pindexDummy = nullptr;
3106 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3108 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3109 return false;
3111 // Try to process all requested blocks that we don't have, but only
3112 // process an unrequested block if it's new and has enough work to
3113 // advance our tip, and isn't too many blocks ahead.
3114 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3115 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3116 // Blocks that are too out-of-order needlessly limit the effectiveness of
3117 // pruning, because pruning will not delete block files that contain any
3118 // blocks which are too close in height to the tip. Apply this test
3119 // regardless of whether pruning is enabled; it should generally be safe to
3120 // not process unrequested blocks.
3121 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3123 // TODO: Decouple this function from the block download logic by removing fRequested
3124 // This requires some new chain data structure to efficiently look up if a
3125 // block is in a chain leading to a candidate for best tip, despite not
3126 // being such a candidate itself.
3128 // TODO: deal better with return value and error conditions for duplicate
3129 // and unrequested blocks.
3130 if (fAlreadyHave) return true;
3131 if (!fRequested) { // If we didn't ask for it:
3132 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3133 if (!fHasMoreWork) return true; // Don't process less-work chains
3134 if (fTooFarAhead) return true; // Block height is too high
3136 if (fNewBlock) *fNewBlock = true;
3138 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3139 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3140 if (state.IsInvalid() && !state.CorruptionPossible()) {
3141 pindex->nStatus |= BLOCK_FAILED_VALID;
3142 setDirtyBlockIndex.insert(pindex);
3144 return error("%s: %s", __func__, FormatStateMessage(state));
3147 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3148 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3149 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3150 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3152 int nHeight = pindex->nHeight;
3154 // Write block to history file
3155 try {
3156 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3157 CDiskBlockPos blockPos;
3158 if (dbp != nullptr)
3159 blockPos = *dbp;
3160 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3161 return error("AcceptBlock(): FindBlockPos failed");
3162 if (dbp == nullptr)
3163 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3164 AbortNode(state, "Failed to write block");
3165 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3166 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3167 } catch (const std::runtime_error& e) {
3168 return AbortNode(state, std::string("System error: ") + e.what());
3171 if (fCheckForPruning)
3172 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3174 return true;
3177 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3180 CBlockIndex *pindex = nullptr;
3181 if (fNewBlock) *fNewBlock = false;
3182 CValidationState state;
3183 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3184 // belt-and-suspenders.
3185 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3187 LOCK(cs_main);
3189 if (ret) {
3190 // Store to disk
3191 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3193 CheckBlockIndex(chainparams.GetConsensus());
3194 if (!ret) {
3195 GetMainSignals().BlockChecked(*pblock, state);
3196 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3200 NotifyHeaderTip();
3202 CValidationState state; // Only used to report errors, not invalidity - ignore it
3203 if (!ActivateBestChain(state, chainparams, pblock))
3204 return error("%s: ActivateBestChain failed", __func__);
3206 return true;
3209 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3211 AssertLockHeld(cs_main);
3212 assert(pindexPrev && pindexPrev == chainActive.Tip());
3213 CCoinsViewCache viewNew(pcoinsTip);
3214 CBlockIndex indexDummy(block);
3215 indexDummy.pprev = pindexPrev;
3216 indexDummy.nHeight = pindexPrev->nHeight + 1;
3218 // NOTE: CheckBlockHeader is called by CheckBlock
3219 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3220 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3221 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3222 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3223 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3224 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3225 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3226 return false;
3227 assert(state.IsValid());
3229 return true;
3233 * BLOCK PRUNING CODE
3236 /* Calculate the amount of disk space the block & undo files currently use */
3237 uint64_t CalculateCurrentUsage()
3239 LOCK(cs_LastBlockFile);
3241 uint64_t retval = 0;
3242 for (const CBlockFileInfo &file : vinfoBlockFile) {
3243 retval += file.nSize + file.nUndoSize;
3245 return retval;
3248 /* Prune a block file (modify associated database entries)*/
3249 void PruneOneBlockFile(const int fileNumber)
3251 LOCK(cs_LastBlockFile);
3253 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3254 CBlockIndex* pindex = it->second;
3255 if (pindex->nFile == fileNumber) {
3256 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3257 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3258 pindex->nFile = 0;
3259 pindex->nDataPos = 0;
3260 pindex->nUndoPos = 0;
3261 setDirtyBlockIndex.insert(pindex);
3263 // Prune from mapBlocksUnlinked -- any block we prune would have
3264 // to be downloaded again in order to consider its chain, at which
3265 // point it would be considered as a candidate for
3266 // mapBlocksUnlinked or setBlockIndexCandidates.
3267 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3268 while (range.first != range.second) {
3269 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3270 range.first++;
3271 if (_it->second == pindex) {
3272 mapBlocksUnlinked.erase(_it);
3278 vinfoBlockFile[fileNumber].SetNull();
3279 setDirtyFileInfo.insert(fileNumber);
3283 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3285 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3286 CDiskBlockPos pos(*it, 0);
3287 fs::remove(GetBlockPosFilename(pos, "blk"));
3288 fs::remove(GetBlockPosFilename(pos, "rev"));
3289 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3293 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3294 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3296 assert(fPruneMode && nManualPruneHeight > 0);
3298 LOCK2(cs_main, cs_LastBlockFile);
3299 if (chainActive.Tip() == nullptr)
3300 return;
3302 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3303 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3304 int count=0;
3305 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3306 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3307 continue;
3308 PruneOneBlockFile(fileNumber);
3309 setFilesToPrune.insert(fileNumber);
3310 count++;
3312 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3315 /* This function is called from the RPC code for pruneblockchain */
3316 void PruneBlockFilesManual(int nManualPruneHeight)
3318 CValidationState state;
3319 const CChainParams& chainparams = Params();
3320 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3324 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3325 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3326 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3327 * (which in this case means the blockchain must be re-downloaded.)
3329 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3330 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3331 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3332 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3333 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3334 * A db flag records the fact that at least some block files have been pruned.
3336 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3338 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3340 LOCK2(cs_main, cs_LastBlockFile);
3341 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3342 return;
3344 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3345 return;
3348 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3349 uint64_t nCurrentUsage = CalculateCurrentUsage();
3350 // We don't check to prune until after we've allocated new space for files
3351 // So we should leave a buffer under our target to account for another allocation
3352 // before the next pruning.
3353 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3354 uint64_t nBytesToPrune;
3355 int count=0;
3357 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3358 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3359 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3361 if (vinfoBlockFile[fileNumber].nSize == 0)
3362 continue;
3364 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3365 break;
3367 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3368 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3369 continue;
3371 PruneOneBlockFile(fileNumber);
3372 // Queue up the files for removal
3373 setFilesToPrune.insert(fileNumber);
3374 nCurrentUsage -= nBytesToPrune;
3375 count++;
3379 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3380 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3381 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3382 nLastBlockWeCanPrune, count);
3385 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3387 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3389 // Check for nMinDiskSpace bytes (currently 50MB)
3390 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3391 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3393 return true;
3396 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3398 if (pos.IsNull())
3399 return nullptr;
3400 fs::path path = GetBlockPosFilename(pos, prefix);
3401 fs::create_directories(path.parent_path());
3402 FILE* file = fsbridge::fopen(path, "rb+");
3403 if (!file && !fReadOnly)
3404 file = fsbridge::fopen(path, "wb+");
3405 if (!file) {
3406 LogPrintf("Unable to open file %s\n", path.string());
3407 return nullptr;
3409 if (pos.nPos) {
3410 if (fseek(file, pos.nPos, SEEK_SET)) {
3411 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3412 fclose(file);
3413 return nullptr;
3416 return file;
3419 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3420 return OpenDiskFile(pos, "blk", fReadOnly);
3423 /** Open an undo file (rev?????.dat) */
3424 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3425 return OpenDiskFile(pos, "rev", fReadOnly);
3428 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3430 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3433 CBlockIndex * InsertBlockIndex(uint256 hash)
3435 if (hash.IsNull())
3436 return nullptr;
3438 // Return existing
3439 BlockMap::iterator mi = mapBlockIndex.find(hash);
3440 if (mi != mapBlockIndex.end())
3441 return (*mi).second;
3443 // Create new
3444 CBlockIndex* pindexNew = new CBlockIndex();
3445 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3446 pindexNew->phashBlock = &((*mi).first);
3448 return pindexNew;
3451 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3453 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3454 return false;
3456 boost::this_thread::interruption_point();
3458 // Calculate nChainWork
3459 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3460 vSortedByHeight.reserve(mapBlockIndex.size());
3461 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3463 CBlockIndex* pindex = item.second;
3464 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3466 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3467 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3469 CBlockIndex* pindex = item.second;
3470 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3471 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3472 // We can link the chain of blocks for which we've received transactions at some point.
3473 // Pruned nodes may have deleted the block.
3474 if (pindex->nTx > 0) {
3475 if (pindex->pprev) {
3476 if (pindex->pprev->nChainTx) {
3477 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3478 } else {
3479 pindex->nChainTx = 0;
3480 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3482 } else {
3483 pindex->nChainTx = pindex->nTx;
3486 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3487 setBlockIndexCandidates.insert(pindex);
3488 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3489 pindexBestInvalid = pindex;
3490 if (pindex->pprev)
3491 pindex->BuildSkip();
3492 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3493 pindexBestHeader = pindex;
3496 // Load block file info
3497 pblocktree->ReadLastBlockFile(nLastBlockFile);
3498 vinfoBlockFile.resize(nLastBlockFile + 1);
3499 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3500 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3501 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3503 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3504 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3505 CBlockFileInfo info;
3506 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3507 vinfoBlockFile.push_back(info);
3508 } else {
3509 break;
3513 // Check presence of blk files
3514 LogPrintf("Checking all blk files are present...\n");
3515 std::set<int> setBlkDataFiles;
3516 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3518 CBlockIndex* pindex = item.second;
3519 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3520 setBlkDataFiles.insert(pindex->nFile);
3523 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3525 CDiskBlockPos pos(*it, 0);
3526 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3527 return false;
3531 // Check whether we have ever pruned block & undo files
3532 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3533 if (fHavePruned)
3534 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3536 // Check whether we need to continue reindexing
3537 bool fReindexing = false;
3538 pblocktree->ReadReindexing(fReindexing);
3539 if(fReindexing) fReindex = true;
3541 // Check whether we have a transaction index
3542 pblocktree->ReadFlag("txindex", fTxIndex);
3543 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3545 return true;
3548 bool LoadChainTip(const CChainParams& chainparams)
3550 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3552 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3553 // In case we just added the genesis block, connect it now, so
3554 // that we always have a chainActive.Tip() when we return.
3555 LogPrintf("%s: Connecting genesis block...\n", __func__);
3556 CValidationState state;
3557 if (!ActivateBestChain(state, chainparams)) {
3558 return false;
3562 // Load pointer to end of best chain
3563 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3564 if (it == mapBlockIndex.end())
3565 return false;
3566 chainActive.SetTip(it->second);
3568 PruneBlockIndexCandidates();
3570 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3571 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3572 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3573 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3574 return true;
3577 CVerifyDB::CVerifyDB()
3579 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3582 CVerifyDB::~CVerifyDB()
3584 uiInterface.ShowProgress("", 100, false);
3587 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3589 LOCK(cs_main);
3590 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3591 return true;
3593 // Verify blocks in the best chain
3594 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3595 nCheckDepth = chainActive.Height();
3596 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3597 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3598 CCoinsViewCache coins(coinsview);
3599 CBlockIndex* pindexState = chainActive.Tip();
3600 CBlockIndex* pindexFailure = nullptr;
3601 int nGoodTransactions = 0;
3602 CValidationState state;
3603 int reportDone = 0;
3604 LogPrintf("[0%%]...");
3605 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3607 boost::this_thread::interruption_point();
3608 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3609 if (reportDone < percentageDone/10) {
3610 // report every 10% step
3611 LogPrintf("[%d%%]...", percentageDone);
3612 reportDone = percentageDone/10;
3614 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3615 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3616 break;
3617 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3618 // If pruning, only go back as far as we have data.
3619 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3620 break;
3622 CBlock block;
3623 // check level 0: read from disk
3624 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3625 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3626 // check level 1: verify block validity
3627 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3628 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3629 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3630 // check level 2: verify undo validity
3631 if (nCheckLevel >= 2 && pindex) {
3632 CBlockUndo undo;
3633 CDiskBlockPos pos = pindex->GetUndoPos();
3634 if (!pos.IsNull()) {
3635 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3636 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3639 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3640 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3641 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3642 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3643 if (res == DISCONNECT_FAILED) {
3644 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3646 pindexState = pindex->pprev;
3647 if (res == DISCONNECT_UNCLEAN) {
3648 nGoodTransactions = 0;
3649 pindexFailure = pindex;
3650 } else {
3651 nGoodTransactions += block.vtx.size();
3654 if (ShutdownRequested())
3655 return true;
3657 if (pindexFailure)
3658 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3660 // check level 4: try reconnecting blocks
3661 if (nCheckLevel >= 4) {
3662 CBlockIndex *pindex = pindexState;
3663 while (pindex != chainActive.Tip()) {
3664 boost::this_thread::interruption_point();
3665 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3666 pindex = chainActive.Next(pindex);
3667 CBlock block;
3668 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3669 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3670 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3671 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3675 LogPrintf("[DONE].\n");
3676 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3678 return true;
3681 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3682 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3684 // TODO: merge with ConnectBlock
3685 CBlock block;
3686 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3687 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3690 for (const CTransactionRef& tx : block.vtx) {
3691 if (!tx->IsCoinBase()) {
3692 for (const CTxIn &txin : tx->vin) {
3693 inputs.SpendCoin(txin.prevout);
3696 // Pass check = true as every addition may be an overwrite.
3697 AddCoins(inputs, *tx, pindex->nHeight, true);
3699 return true;
3702 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3704 LOCK(cs_main);
3706 CCoinsViewCache cache(view);
3708 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3709 if (hashHeads.empty()) return true; // We're already in a consistent state.
3710 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3712 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3713 LogPrintf("Replaying blocks\n");
3715 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3716 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3717 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3719 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3720 return error("ReplayBlocks(): reorganization to unknown block requested");
3722 pindexNew = mapBlockIndex[hashHeads[0]];
3724 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3725 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3726 return error("ReplayBlocks(): reorganization from unknown block requested");
3728 pindexOld = mapBlockIndex[hashHeads[1]];
3729 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3730 assert(pindexFork != nullptr);
3733 // Rollback along the old branch.
3734 while (pindexOld != pindexFork) {
3735 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3736 CBlock block;
3737 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3738 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3740 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3741 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3742 if (res == DISCONNECT_FAILED) {
3743 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3745 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3746 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3747 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3748 // the result is still a version of the UTXO set with the effects of that block undone.
3750 pindexOld = pindexOld->pprev;
3753 // Roll forward from the forking point to the new tip.
3754 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3755 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3756 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3757 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3758 if (!RollforwardBlock(pindex, cache, params)) return false;
3761 cache.SetBestBlock(pindexNew->GetBlockHash());
3762 cache.Flush();
3763 uiInterface.ShowProgress("", 100, false);
3764 return true;
3767 bool RewindBlockIndex(const CChainParams& params)
3769 LOCK(cs_main);
3771 // Note that during -reindex-chainstate we are called with an empty chainActive!
3773 int nHeight = 1;
3774 while (nHeight <= chainActive.Height()) {
3775 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3776 break;
3778 nHeight++;
3781 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3782 CValidationState state;
3783 CBlockIndex* pindex = chainActive.Tip();
3784 while (chainActive.Height() >= nHeight) {
3785 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3786 // If pruning, don't try rewinding past the HAVE_DATA point;
3787 // since older blocks can't be served anyway, there's
3788 // no need to walk further, and trying to DisconnectTip()
3789 // will fail (and require a needless reindex/redownload
3790 // of the blockchain).
3791 break;
3793 if (!DisconnectTip(state, params, nullptr)) {
3794 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3796 // Occasionally flush state to disk.
3797 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3798 return false;
3801 // Reduce validity flag and have-data flags.
3802 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3803 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3804 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3805 CBlockIndex* pindexIter = it->second;
3807 // Note: If we encounter an insufficiently validated block that
3808 // is on chainActive, it must be because we are a pruning node, and
3809 // this block or some successor doesn't HAVE_DATA, so we were unable to
3810 // rewind all the way. Blocks remaining on chainActive at this point
3811 // must not have their validity reduced.
3812 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3813 // Reduce validity
3814 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3815 // Remove have-data flags.
3816 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3817 // Remove storage location.
3818 pindexIter->nFile = 0;
3819 pindexIter->nDataPos = 0;
3820 pindexIter->nUndoPos = 0;
3821 // Remove various other things
3822 pindexIter->nTx = 0;
3823 pindexIter->nChainTx = 0;
3824 pindexIter->nSequenceId = 0;
3825 // Make sure it gets written.
3826 setDirtyBlockIndex.insert(pindexIter);
3827 // Update indexes
3828 setBlockIndexCandidates.erase(pindexIter);
3829 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3830 while (ret.first != ret.second) {
3831 if (ret.first->second == pindexIter) {
3832 mapBlocksUnlinked.erase(ret.first++);
3833 } else {
3834 ++ret.first;
3837 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3838 setBlockIndexCandidates.insert(pindexIter);
3842 if (chainActive.Tip() != nullptr) {
3843 // We can't prune block index candidates based on our tip if we have
3844 // no tip due to chainActive being empty!
3845 PruneBlockIndexCandidates();
3847 CheckBlockIndex(params.GetConsensus());
3849 // FlushStateToDisk can possibly read chainActive. Be conservative
3850 // and skip it here, we're about to -reindex-chainstate anyway, so
3851 // it'll get called a bunch real soon.
3852 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3853 return false;
3857 return true;
3860 // May NOT be used after any connections are up as much
3861 // of the peer-processing logic assumes a consistent
3862 // block index state
3863 void UnloadBlockIndex()
3865 LOCK(cs_main);
3866 setBlockIndexCandidates.clear();
3867 chainActive.SetTip(nullptr);
3868 pindexBestInvalid = nullptr;
3869 pindexBestHeader = nullptr;
3870 mempool.clear();
3871 mapBlocksUnlinked.clear();
3872 vinfoBlockFile.clear();
3873 nLastBlockFile = 0;
3874 nBlockSequenceId = 1;
3875 setDirtyBlockIndex.clear();
3876 setDirtyFileInfo.clear();
3877 versionbitscache.Clear();
3878 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3879 warningcache[b].clear();
3882 for (BlockMap::value_type& entry : mapBlockIndex) {
3883 delete entry.second;
3885 mapBlockIndex.clear();
3886 fHavePruned = false;
3889 bool LoadBlockIndex(const CChainParams& chainparams)
3891 // Load block index from databases
3892 bool needs_init = fReindex;
3893 if (!fReindex) {
3894 bool ret = LoadBlockIndexDB(chainparams);
3895 if (!ret) return false;
3896 needs_init = mapBlockIndex.empty();
3899 if (needs_init) {
3900 // Everything here is for *new* reindex/DBs. Thus, though
3901 // LoadBlockIndexDB may have set fReindex if we shut down
3902 // mid-reindex previously, we don't check fReindex and
3903 // instead only check it prior to LoadBlockIndexDB to set
3904 // needs_init.
3906 LogPrintf("Initializing databases...\n");
3907 // Use the provided setting for -txindex in the new database
3908 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
3909 pblocktree->WriteFlag("txindex", fTxIndex);
3911 return true;
3914 bool LoadGenesisBlock(const CChainParams& chainparams)
3916 LOCK(cs_main);
3918 // Check whether we're already initialized by checking for genesis in
3919 // mapBlockIndex. Note that we can't use chainActive here, since it is
3920 // set based on the coins db, not the block index db, which is the only
3921 // thing loaded at this point.
3922 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
3923 return true;
3925 try {
3926 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3927 // Start new block file
3928 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3929 CDiskBlockPos blockPos;
3930 CValidationState state;
3931 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3932 return error("%s: FindBlockPos failed", __func__);
3933 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3934 return error("%s: writing genesis block to disk failed", __func__);
3935 CBlockIndex *pindex = AddToBlockIndex(block);
3936 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3937 return error("%s: genesis block not accepted", __func__);
3938 } catch (const std::runtime_error& e) {
3939 return error("%s: failed to write genesis block: %s", __func__, e.what());
3942 return true;
3945 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3947 // Map of disk positions for blocks with unknown parent (only used for reindex)
3948 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3949 int64_t nStart = GetTimeMillis();
3951 int nLoaded = 0;
3952 try {
3953 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3954 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3955 uint64_t nRewind = blkdat.GetPos();
3956 while (!blkdat.eof()) {
3957 boost::this_thread::interruption_point();
3959 blkdat.SetPos(nRewind);
3960 nRewind++; // start one byte further next time, in case of failure
3961 blkdat.SetLimit(); // remove former limit
3962 unsigned int nSize = 0;
3963 try {
3964 // locate a header
3965 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3966 blkdat.FindByte(chainparams.MessageStart()[0]);
3967 nRewind = blkdat.GetPos()+1;
3968 blkdat >> FLATDATA(buf);
3969 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3970 continue;
3971 // read size
3972 blkdat >> nSize;
3973 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3974 continue;
3975 } catch (const std::exception&) {
3976 // no valid block header found; don't complain
3977 break;
3979 try {
3980 // read block
3981 uint64_t nBlockPos = blkdat.GetPos();
3982 if (dbp)
3983 dbp->nPos = nBlockPos;
3984 blkdat.SetLimit(nBlockPos + nSize);
3985 blkdat.SetPos(nBlockPos);
3986 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3987 CBlock& block = *pblock;
3988 blkdat >> block;
3989 nRewind = blkdat.GetPos();
3991 // detect out of order blocks, and store them for later
3992 uint256 hash = block.GetHash();
3993 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3994 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3995 block.hashPrevBlock.ToString());
3996 if (dbp)
3997 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3998 continue;
4001 // process in case the block isn't known yet
4002 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4003 LOCK(cs_main);
4004 CValidationState state;
4005 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4006 nLoaded++;
4007 if (state.IsError())
4008 break;
4009 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4010 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4013 // Activate the genesis block so normal node progress can continue
4014 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4015 CValidationState state;
4016 if (!ActivateBestChain(state, chainparams)) {
4017 break;
4021 NotifyHeaderTip();
4023 // Recursively process earlier encountered successors of this block
4024 std::deque<uint256> queue;
4025 queue.push_back(hash);
4026 while (!queue.empty()) {
4027 uint256 head = queue.front();
4028 queue.pop_front();
4029 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4030 while (range.first != range.second) {
4031 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4032 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4033 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4035 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4036 head.ToString());
4037 LOCK(cs_main);
4038 CValidationState dummy;
4039 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4041 nLoaded++;
4042 queue.push_back(pblockrecursive->GetHash());
4045 range.first++;
4046 mapBlocksUnknownParent.erase(it);
4047 NotifyHeaderTip();
4050 } catch (const std::exception& e) {
4051 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4054 } catch (const std::runtime_error& e) {
4055 AbortNode(std::string("System error: ") + e.what());
4057 if (nLoaded > 0)
4058 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4059 return nLoaded > 0;
4062 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4064 if (!fCheckBlockIndex) {
4065 return;
4068 LOCK(cs_main);
4070 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4071 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4072 // iterating the block tree require that chainActive has been initialized.)
4073 if (chainActive.Height() < 0) {
4074 assert(mapBlockIndex.size() <= 1);
4075 return;
4078 // Build forward-pointing map of the entire block tree.
4079 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4080 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4081 forward.insert(std::make_pair(it->second->pprev, it->second));
4084 assert(forward.size() == mapBlockIndex.size());
4086 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4087 CBlockIndex *pindex = rangeGenesis.first->second;
4088 rangeGenesis.first++;
4089 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4091 // Iterate over the entire block tree, using depth-first search.
4092 // Along the way, remember whether there are blocks on the path from genesis
4093 // block being explored which are the first to have certain properties.
4094 size_t nNodes = 0;
4095 int nHeight = 0;
4096 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4097 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4098 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4099 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4100 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4101 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4102 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4103 while (pindex != nullptr) {
4104 nNodes++;
4105 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4106 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4107 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4108 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4109 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4110 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4111 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4113 // Begin: actual consistency checks.
4114 if (pindex->pprev == nullptr) {
4115 // Genesis block checks.
4116 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4117 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4119 if (pindex->nChainTx == 0) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4120 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4121 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4122 if (!fHavePruned) {
4123 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4124 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4125 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4126 } else {
4127 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4128 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4130 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4131 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4132 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4133 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4134 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4135 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4136 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.
4137 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4138 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4139 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4140 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4141 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4142 if (pindexFirstInvalid == nullptr) {
4143 // Checks for not-invalid blocks.
4144 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4146 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4147 if (pindexFirstInvalid == nullptr) {
4148 // If this block sorts at least as good as the current tip and
4149 // is valid and we have all data for its parents, it must be in
4150 // setBlockIndexCandidates. chainActive.Tip() must also be there
4151 // even if some data has been pruned.
4152 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4153 assert(setBlockIndexCandidates.count(pindex));
4155 // If some parent is missing, then it could be that this block was in
4156 // setBlockIndexCandidates but had to be removed because of the missing data.
4157 // In this case it must be in mapBlocksUnlinked -- see test below.
4159 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4160 assert(setBlockIndexCandidates.count(pindex) == 0);
4162 // Check whether this block is in mapBlocksUnlinked.
4163 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4164 bool foundInUnlinked = false;
4165 while (rangeUnlinked.first != rangeUnlinked.second) {
4166 assert(rangeUnlinked.first->first == pindex->pprev);
4167 if (rangeUnlinked.first->second == pindex) {
4168 foundInUnlinked = true;
4169 break;
4171 rangeUnlinked.first++;
4173 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4174 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4175 assert(foundInUnlinked);
4177 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4178 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4179 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4180 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4181 assert(fHavePruned); // We must have pruned.
4182 // This block may have entered mapBlocksUnlinked if:
4183 // - it has a descendant that at some point had more work than the
4184 // tip, and
4185 // - we tried switching to that descendant but were missing
4186 // data for some intermediate block between chainActive and the
4187 // tip.
4188 // So if this block is itself better than chainActive.Tip() and it wasn't in
4189 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4190 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4191 if (pindexFirstInvalid == nullptr) {
4192 assert(foundInUnlinked);
4196 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4197 // End: actual consistency checks.
4199 // Try descending into the first subnode.
4200 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4201 if (range.first != range.second) {
4202 // A subnode was found.
4203 pindex = range.first->second;
4204 nHeight++;
4205 continue;
4207 // This is a leaf node.
4208 // Move upwards until we reach a node of which we have not yet visited the last child.
4209 while (pindex) {
4210 // We are going to either move to a parent or a sibling of pindex.
4211 // If pindex was the first with a certain property, unset the corresponding variable.
4212 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4213 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4214 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4215 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4216 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4217 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4218 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4219 // Find our parent.
4220 CBlockIndex* pindexPar = pindex->pprev;
4221 // Find which child we just visited.
4222 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4223 while (rangePar.first->second != pindex) {
4224 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4225 rangePar.first++;
4227 // Proceed to the next one.
4228 rangePar.first++;
4229 if (rangePar.first != rangePar.second) {
4230 // Move to the sibling.
4231 pindex = rangePar.first->second;
4232 break;
4233 } else {
4234 // Move up further.
4235 pindex = pindexPar;
4236 nHeight--;
4237 continue;
4242 // Check that we actually traversed the entire map.
4243 assert(nNodes == forward.size());
4246 std::string CBlockFileInfo::ToString() const
4248 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
4251 CBlockFileInfo* GetBlockFileInfo(size_t n)
4253 LOCK(cs_LastBlockFile);
4255 return &vinfoBlockFile.at(n);
4258 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4260 LOCK(cs_main);
4261 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4264 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4266 LOCK(cs_main);
4267 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4270 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4272 LOCK(cs_main);
4273 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4276 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4278 bool LoadMempool(void)
4280 const CChainParams& chainparams = Params();
4281 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4282 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4283 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4284 if (file.IsNull()) {
4285 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4286 return false;
4289 int64_t count = 0;
4290 int64_t expired = 0;
4291 int64_t failed = 0;
4292 int64_t already_there = 0;
4293 int64_t nNow = GetTime();
4295 try {
4296 uint64_t version;
4297 file >> version;
4298 if (version != MEMPOOL_DUMP_VERSION) {
4299 return false;
4301 uint64_t num;
4302 file >> num;
4303 while (num--) {
4304 CTransactionRef tx;
4305 int64_t nTime;
4306 int64_t nFeeDelta;
4307 file >> tx;
4308 file >> nTime;
4309 file >> nFeeDelta;
4311 CAmount amountdelta = nFeeDelta;
4312 if (amountdelta) {
4313 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4315 CValidationState state;
4316 if (nTime + nExpiryTimeout > nNow) {
4317 LOCK(cs_main);
4318 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4319 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4320 if (state.IsValid()) {
4321 ++count;
4322 } else {
4323 // mempool may contain the transaction already, e.g. from
4324 // wallet(s) having loaded it while we were processing
4325 // mempool transactions; consider these as valid, instead of
4326 // failed, but mark them as 'already there'
4327 if (mempool.exists(tx->GetHash())) {
4328 ++already_there;
4329 } else {
4330 ++failed;
4333 } else {
4334 ++expired;
4336 if (ShutdownRequested())
4337 return false;
4339 std::map<uint256, CAmount> mapDeltas;
4340 file >> mapDeltas;
4342 for (const auto& i : mapDeltas) {
4343 mempool.PrioritiseTransaction(i.first, i.second);
4345 } catch (const std::exception& e) {
4346 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4347 return false;
4350 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4351 return true;
4354 bool DumpMempool(void)
4356 int64_t start = GetTimeMicros();
4358 std::map<uint256, CAmount> mapDeltas;
4359 std::vector<TxMempoolInfo> vinfo;
4362 LOCK(mempool.cs);
4363 for (const auto &i : mempool.mapDeltas) {
4364 mapDeltas[i.first] = i.second;
4366 vinfo = mempool.infoAll();
4369 int64_t mid = GetTimeMicros();
4371 try {
4372 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4373 if (!filestr) {
4374 return false;
4377 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4379 uint64_t version = MEMPOOL_DUMP_VERSION;
4380 file << version;
4382 file << (uint64_t)vinfo.size();
4383 for (const auto& i : vinfo) {
4384 file << *(i.tx);
4385 file << (int64_t)i.nTime;
4386 file << (int64_t)i.nFeeDelta;
4387 mapDeltas.erase(i.tx->GetHash());
4390 file << mapDeltas;
4391 FileCommit(file.Get());
4392 file.fclose();
4393 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4394 int64_t last = GetTimeMicros();
4395 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4396 } catch (const std::exception& e) {
4397 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4398 return false;
4400 return true;
4403 //! Guess how far we are in the verification process at the given block index
4404 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4405 if (pindex == nullptr)
4406 return 0.0;
4408 int64_t nNow = time(nullptr);
4410 double fTxTotal;
4412 if (pindex->nChainTx <= data.nTxCount) {
4413 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4414 } else {
4415 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4418 return pindex->nChainTx / fTxTotal;
4421 class CMainCleanup
4423 public:
4424 CMainCleanup() {}
4425 ~CMainCleanup() {
4426 // block headers
4427 BlockMap::iterator it1 = mapBlockIndex.begin();
4428 for (; it1 != mapBlockIndex.end(); it1++)
4429 delete (*it1).second;
4430 mapBlockIndex.clear();
4432 } instance_of_cmaincleanup;