Add CConnmanTest to mutate g_connman in tests
[bitcoinplatinum.git] / src / validation.cpp
blob78eb6d7302409aba715bb81567d36dddcd34a5e7
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;
943 // transaction not found in index, nothing more can be done
944 return false;
947 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
948 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
949 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
952 if (pindexSlow) {
953 CBlock block;
954 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
955 for (const auto& tx : block.vtx) {
956 if (tx->GetHash() == hash) {
957 txOut = tx;
958 hashBlock = pindexSlow->GetBlockHash();
959 return true;
965 return false;
973 //////////////////////////////////////////////////////////////////////////////
975 // CBlock and CBlockIndex
978 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
980 // Open history file to append
981 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
982 if (fileout.IsNull())
983 return error("WriteBlockToDisk: OpenBlockFile failed");
985 // Write index header
986 unsigned int nSize = GetSerializeSize(fileout, block);
987 fileout << FLATDATA(messageStart) << nSize;
989 // Write block
990 long fileOutPos = ftell(fileout.Get());
991 if (fileOutPos < 0)
992 return error("WriteBlockToDisk: ftell failed");
993 pos.nPos = (unsigned int)fileOutPos;
994 fileout << block;
996 return true;
999 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1001 block.SetNull();
1003 // Open history file to read
1004 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1005 if (filein.IsNull())
1006 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1008 // Read block
1009 try {
1010 filein >> block;
1012 catch (const std::exception& e) {
1013 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1016 // Check the header
1017 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1018 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1020 return true;
1023 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1025 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1026 return false;
1027 if (block.GetHash() != pindex->GetBlockHash())
1028 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1029 pindex->ToString(), pindex->GetBlockPos().ToString());
1030 return true;
1033 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1035 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1036 // Force block reward to zero when right shift is undefined.
1037 if (halvings >= 64)
1038 return 0;
1040 CAmount nSubsidy = 50 * COIN;
1041 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1042 nSubsidy >>= halvings;
1043 return nSubsidy;
1046 bool IsInitialBlockDownload()
1048 // Once this function has returned false, it must remain false.
1049 static std::atomic<bool> latchToFalse{false};
1050 // Optimization: pre-test latch before taking the lock.
1051 if (latchToFalse.load(std::memory_order_relaxed))
1052 return false;
1054 LOCK(cs_main);
1055 if (latchToFalse.load(std::memory_order_relaxed))
1056 return false;
1057 if (fImporting || fReindex)
1058 return true;
1059 if (chainActive.Tip() == nullptr)
1060 return true;
1061 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1062 return true;
1063 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1064 return true;
1065 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1066 latchToFalse.store(true, std::memory_order_relaxed);
1067 return false;
1070 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1072 static void AlertNotify(const std::string& strMessage)
1074 uiInterface.NotifyAlertChanged();
1075 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1076 if (strCmd.empty()) return;
1078 // Alert text should be plain ascii coming from a trusted source, but to
1079 // be safe we first strip anything not in safeChars, then add single quotes around
1080 // the whole string before passing it to the shell:
1081 std::string singleQuote("'");
1082 std::string safeStatus = SanitizeString(strMessage);
1083 safeStatus = singleQuote+safeStatus+singleQuote;
1084 boost::replace_all(strCmd, "%s", safeStatus);
1086 boost::thread t(runCommand, strCmd); // thread runs free
1089 static void CheckForkWarningConditions()
1091 AssertLockHeld(cs_main);
1092 // Before we get past initial download, we cannot reliably alert about forks
1093 // (we assume we don't get stuck on a fork before finishing our initial sync)
1094 if (IsInitialBlockDownload())
1095 return;
1097 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1098 // of our head, drop it
1099 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1100 pindexBestForkTip = nullptr;
1102 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1104 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1106 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1107 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1108 AlertNotify(warning);
1110 if (pindexBestForkTip && pindexBestForkBase)
1112 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__,
1113 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1114 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1115 SetfLargeWorkForkFound(true);
1117 else
1119 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1120 SetfLargeWorkInvalidChainFound(true);
1123 else
1125 SetfLargeWorkForkFound(false);
1126 SetfLargeWorkInvalidChainFound(false);
1130 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1132 AssertLockHeld(cs_main);
1133 // If we are on a fork that is sufficiently large, set a warning flag
1134 CBlockIndex* pfork = pindexNewForkTip;
1135 CBlockIndex* plonger = chainActive.Tip();
1136 while (pfork && pfork != plonger)
1138 while (plonger && plonger->nHeight > pfork->nHeight)
1139 plonger = plonger->pprev;
1140 if (pfork == plonger)
1141 break;
1142 pfork = pfork->pprev;
1145 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1146 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1147 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1148 // hash rate operating on the fork.
1149 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1150 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1151 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1152 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1153 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1154 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1156 pindexBestForkTip = pindexNewForkTip;
1157 pindexBestForkBase = pfork;
1160 CheckForkWarningConditions();
1163 void static InvalidChainFound(CBlockIndex* pindexNew)
1165 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1166 pindexBestInvalid = pindexNew;
1168 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1169 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1170 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1171 pindexNew->GetBlockTime()));
1172 CBlockIndex *tip = chainActive.Tip();
1173 assert (tip);
1174 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1175 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1176 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1177 CheckForkWarningConditions();
1180 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1181 if (!state.CorruptionPossible()) {
1182 pindex->nStatus |= BLOCK_FAILED_VALID;
1183 setDirtyBlockIndex.insert(pindex);
1184 setBlockIndexCandidates.erase(pindex);
1185 InvalidChainFound(pindex);
1189 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1191 // mark inputs spent
1192 if (!tx.IsCoinBase()) {
1193 txundo.vprevout.reserve(tx.vin.size());
1194 for (const CTxIn &txin : tx.vin) {
1195 txundo.vprevout.emplace_back();
1196 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1197 assert(is_spent);
1200 // add outputs
1201 AddCoins(inputs, tx, nHeight);
1204 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1206 CTxUndo txundo;
1207 UpdateCoins(tx, inputs, txundo, nHeight);
1210 bool CScriptCheck::operator()() {
1211 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1212 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1213 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1216 int GetSpendHeight(const CCoinsViewCache& inputs)
1218 LOCK(cs_main);
1219 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1220 return pindexPrev->nHeight + 1;
1224 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1225 static uint256 scriptExecutionCacheNonce(GetRandHash());
1227 void InitScriptExecutionCache() {
1228 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1229 // setup_bytes creates the minimum possible cache (2 elements).
1230 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);
1231 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1232 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1233 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1237 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1238 * This does not modify the UTXO set.
1240 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1241 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1242 * not pushed onto pvChecks/run.
1244 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1245 * which are matched. This is useful for checking blocks where we will likely never need the cache
1246 * entry again.
1248 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1250 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)
1252 if (!tx.IsCoinBase())
1254 if (pvChecks)
1255 pvChecks->reserve(tx.vin.size());
1257 // The first loop above does all the inexpensive checks.
1258 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1259 // Helps prevent CPU exhaustion attacks.
1261 // Skip script verification when connecting blocks under the
1262 // assumevalid block. Assuming the assumevalid block is valid this
1263 // is safe because block merkle hashes are still computed and checked,
1264 // Of course, if an assumed valid block is invalid due to false scriptSigs
1265 // this optimization would allow an invalid chain to be accepted.
1266 if (fScriptChecks) {
1267 // First check if script executions have been cached with the same
1268 // flags. Note that this assumes that the inputs provided are
1269 // correct (ie that the transaction hash which is in tx's prevouts
1270 // properly commits to the scriptPubKey in the inputs view of that
1271 // transaction).
1272 uint256 hashCacheEntry;
1273 // We only use the first 19 bytes of nonce to avoid a second SHA
1274 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1275 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1276 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1277 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1278 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1279 return true;
1282 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1283 const COutPoint &prevout = tx.vin[i].prevout;
1284 const Coin& coin = inputs.AccessCoin(prevout);
1285 assert(!coin.IsSpent());
1287 // We very carefully only pass in things to CScriptCheck which
1288 // are clearly committed to by tx' witness hash. This provides
1289 // a sanity check that our caching is not introducing consensus
1290 // failures through additional data in, eg, the coins being
1291 // spent being checked as a part of CScriptCheck.
1293 // Verify signature
1294 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1295 if (pvChecks) {
1296 pvChecks->push_back(CScriptCheck());
1297 check.swap(pvChecks->back());
1298 } else if (!check()) {
1299 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1300 // Check whether the failure was caused by a
1301 // non-mandatory script verification check, such as
1302 // non-standard DER encodings or non-null dummy
1303 // arguments; if so, don't trigger DoS protection to
1304 // avoid splitting the network between upgraded and
1305 // non-upgraded nodes.
1306 CScriptCheck check2(coin.out, tx, i,
1307 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1308 if (check2())
1309 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1311 // Failures of other flags indicate a transaction that is
1312 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1313 // such nodes as they are not following the protocol. That
1314 // said during an upgrade careful thought should be taken
1315 // as to the correct behavior - we may want to continue
1316 // peering with non-upgraded nodes even after soft-fork
1317 // super-majority signaling has occurred.
1318 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1322 if (cacheFullScriptStore && !pvChecks) {
1323 // We executed all of the provided scripts, and were told to
1324 // cache the result. Do so now.
1325 scriptExecutionCache.insert(hashCacheEntry);
1330 return true;
1333 namespace {
1335 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1337 // Open history file to append
1338 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1339 if (fileout.IsNull())
1340 return error("%s: OpenUndoFile failed", __func__);
1342 // Write index header
1343 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1344 fileout << FLATDATA(messageStart) << nSize;
1346 // Write undo data
1347 long fileOutPos = ftell(fileout.Get());
1348 if (fileOutPos < 0)
1349 return error("%s: ftell failed", __func__);
1350 pos.nPos = (unsigned int)fileOutPos;
1351 fileout << blockundo;
1353 // calculate & write checksum
1354 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1355 hasher << hashBlock;
1356 hasher << blockundo;
1357 fileout << hasher.GetHash();
1359 return true;
1362 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1364 // Open history file to read
1365 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1366 if (filein.IsNull())
1367 return error("%s: OpenUndoFile failed", __func__);
1369 // Read block
1370 uint256 hashChecksum;
1371 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1372 try {
1373 verifier << hashBlock;
1374 verifier >> blockundo;
1375 filein >> hashChecksum;
1377 catch (const std::exception& e) {
1378 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1381 // Verify checksum
1382 if (hashChecksum != verifier.GetHash())
1383 return error("%s: Checksum mismatch", __func__);
1385 return true;
1388 /** Abort with a message */
1389 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1391 SetMiscWarning(strMessage);
1392 LogPrintf("*** %s\n", strMessage);
1393 uiInterface.ThreadSafeMessageBox(
1394 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1395 "", CClientUIInterface::MSG_ERROR);
1396 StartShutdown();
1397 return false;
1400 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1402 AbortNode(strMessage, userMessage);
1403 return state.Error(strMessage);
1406 } // namespace
1408 enum DisconnectResult
1410 DISCONNECT_OK, // All good.
1411 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1412 DISCONNECT_FAILED // Something else went wrong.
1416 * Restore the UTXO in a Coin at a given COutPoint
1417 * @param undo The Coin to be restored.
1418 * @param view The coins view to which to apply the changes.
1419 * @param out The out point that corresponds to the tx input.
1420 * @return A DisconnectResult as an int
1422 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1424 bool fClean = true;
1426 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1428 if (undo.nHeight == 0) {
1429 // Missing undo metadata (height and coinbase). Older versions included this
1430 // information only in undo records for the last spend of a transactions'
1431 // outputs. This implies that it must be present for some other output of the same tx.
1432 const Coin& alternate = AccessByTxid(view, out.hash);
1433 if (!alternate.IsSpent()) {
1434 undo.nHeight = alternate.nHeight;
1435 undo.fCoinBase = alternate.fCoinBase;
1436 } else {
1437 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1440 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1441 // sure that the coin did not already exist in the cache. As we have queried for that above
1442 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1443 // it is an overwrite.
1444 view.AddCoin(out, std::move(undo), !fClean);
1446 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1449 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1450 * When FAILED is returned, view is left in an indeterminate state. */
1451 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1453 bool fClean = true;
1455 CBlockUndo blockUndo;
1456 CDiskBlockPos pos = pindex->GetUndoPos();
1457 if (pos.IsNull()) {
1458 error("DisconnectBlock(): no undo data available");
1459 return DISCONNECT_FAILED;
1461 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1462 error("DisconnectBlock(): failure reading undo data");
1463 return DISCONNECT_FAILED;
1466 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1467 error("DisconnectBlock(): block and undo data inconsistent");
1468 return DISCONNECT_FAILED;
1471 // undo transactions in reverse order
1472 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1473 const CTransaction &tx = *(block.vtx[i]);
1474 uint256 hash = tx.GetHash();
1475 bool is_coinbase = tx.IsCoinBase();
1477 // Check that all outputs are available and match the outputs in the block itself
1478 // exactly.
1479 for (size_t o = 0; o < tx.vout.size(); o++) {
1480 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1481 COutPoint out(hash, o);
1482 Coin coin;
1483 bool is_spent = view.SpendCoin(out, &coin);
1484 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1485 fClean = false; // transaction output mismatch
1490 // restore inputs
1491 if (i > 0) { // not coinbases
1492 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1493 if (txundo.vprevout.size() != tx.vin.size()) {
1494 error("DisconnectBlock(): transaction and undo data inconsistent");
1495 return DISCONNECT_FAILED;
1497 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1498 const COutPoint &out = tx.vin[j].prevout;
1499 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1500 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1501 fClean = fClean && res != DISCONNECT_UNCLEAN;
1503 // At this point, all of txundo.vprevout should have been moved out.
1507 // move best block pointer to prevout block
1508 view.SetBestBlock(pindex->pprev->GetBlockHash());
1510 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1513 void static FlushBlockFile(bool fFinalize = false)
1515 LOCK(cs_LastBlockFile);
1517 CDiskBlockPos posOld(nLastBlockFile, 0);
1519 FILE *fileOld = OpenBlockFile(posOld);
1520 if (fileOld) {
1521 if (fFinalize)
1522 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1523 FileCommit(fileOld);
1524 fclose(fileOld);
1527 fileOld = OpenUndoFile(posOld);
1528 if (fileOld) {
1529 if (fFinalize)
1530 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1531 FileCommit(fileOld);
1532 fclose(fileOld);
1536 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1538 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1540 void ThreadScriptCheck() {
1541 RenameThread("bitcoin-scriptch");
1542 scriptcheckqueue.Thread();
1545 // Protected by cs_main
1546 VersionBitsCache versionbitscache;
1548 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1550 LOCK(cs_main);
1551 int32_t nVersion = VERSIONBITS_TOP_BITS;
1553 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1554 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1555 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1556 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1560 return nVersion;
1564 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1566 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1568 private:
1569 int bit;
1571 public:
1572 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1574 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1575 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1576 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1577 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1579 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1581 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1582 ((pindex->nVersion >> bit) & 1) != 0 &&
1583 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1587 // Protected by cs_main
1588 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1590 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1591 AssertLockHeld(cs_main);
1593 // BIP16 didn't become active until Apr 1 2012
1594 int64_t nBIP16SwitchTime = 1333238400;
1595 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1597 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1599 // Start enforcing the DERSIG (BIP66) rule
1600 if (pindex->nHeight >= consensusparams.BIP66Height) {
1601 flags |= SCRIPT_VERIFY_DERSIG;
1604 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1605 if (pindex->nHeight >= consensusparams.BIP65Height) {
1606 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1609 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1610 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1611 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1614 // Start enforcing WITNESS rules using versionbits logic.
1615 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1616 flags |= SCRIPT_VERIFY_WITNESS;
1617 flags |= SCRIPT_VERIFY_NULLDUMMY;
1620 return flags;
1625 static int64_t nTimeCheck = 0;
1626 static int64_t nTimeForks = 0;
1627 static int64_t nTimeVerify = 0;
1628 static int64_t nTimeConnect = 0;
1629 static int64_t nTimeIndex = 0;
1630 static int64_t nTimeCallbacks = 0;
1631 static int64_t nTimeTotal = 0;
1632 static int64_t nBlocksTotal = 0;
1634 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1635 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1636 * can fail if those validity checks fail (among other reasons). */
1637 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1638 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1640 AssertLockHeld(cs_main);
1641 assert(pindex);
1642 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1643 assert((pindex->phashBlock == nullptr) ||
1644 (*pindex->phashBlock == block.GetHash()));
1645 int64_t nTimeStart = GetTimeMicros();
1647 // Check it again in case a previous version let a bad block in
1648 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1649 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1651 // verify that the view's current state corresponds to the previous block
1652 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1653 assert(hashPrevBlock == view.GetBestBlock());
1655 // Special case for the genesis block, skipping connection of its transactions
1656 // (its coinbase is unspendable)
1657 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1658 if (!fJustCheck)
1659 view.SetBestBlock(pindex->GetBlockHash());
1660 return true;
1663 nBlocksTotal++;
1665 bool fScriptChecks = true;
1666 if (!hashAssumeValid.IsNull()) {
1667 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1668 // A suitable default value is included with the software and updated from time to time. Because validity
1669 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1670 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1671 // effectively caching the result of part of the verification.
1672 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1673 if (it != mapBlockIndex.end()) {
1674 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1675 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1676 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1677 // This block is a member of the assumed verified chain and an ancestor of the best header.
1678 // The equivalent time check discourages hash power from extorting the network via DOS attack
1679 // into accepting an invalid block through telling users they must manually set assumevalid.
1680 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1681 // it hard to hide the implication of the demand. This also avoids having release candidates
1682 // that are hardly doing any signature verification at all in testing without having to
1683 // artificially set the default assumed verified block further back.
1684 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1685 // least as good as the expected chain.
1686 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1691 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1692 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1694 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1695 // unless those are already completely spent.
1696 // If such overwrites are allowed, coinbases and transactions depending upon those
1697 // can be duplicated to remove the ability to spend the first instance -- even after
1698 // being sent to another address.
1699 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1700 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1701 // already refuses previously-known transaction ids entirely.
1702 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1703 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1704 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1705 // initial block download.
1706 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1707 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1708 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1710 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1711 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1712 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1713 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1714 // duplicate transactions descending from the known pairs either.
1715 // 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.
1716 assert(pindex->pprev);
1717 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1718 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1719 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1721 if (fEnforceBIP30) {
1722 for (const auto& tx : block.vtx) {
1723 for (size_t o = 0; o < tx->vout.size(); o++) {
1724 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1725 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1726 REJECT_INVALID, "bad-txns-BIP30");
1732 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1733 int nLockTimeFlags = 0;
1734 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1735 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1738 // Get the script flags for this block
1739 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1741 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1742 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1744 CBlockUndo blockundo;
1746 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1748 std::vector<int> prevheights;
1749 CAmount nFees = 0;
1750 int nInputs = 0;
1751 int64_t nSigOpsCost = 0;
1752 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1753 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1754 vPos.reserve(block.vtx.size());
1755 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1756 std::vector<PrecomputedTransactionData> txdata;
1757 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1758 for (unsigned int i = 0; i < block.vtx.size(); i++)
1760 const CTransaction &tx = *(block.vtx[i]);
1762 nInputs += tx.vin.size();
1764 if (!tx.IsCoinBase())
1766 CAmount txfee = 0;
1767 if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
1768 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
1770 nFees += txfee;
1771 if (!MoneyRange(nFees)) {
1772 return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
1773 REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
1776 // Check that transaction is BIP68 final
1777 // BIP68 lock checks (as opposed to nLockTime checks) must
1778 // be in ConnectBlock because they require the UTXO set
1779 prevheights.resize(tx.vin.size());
1780 for (size_t j = 0; j < tx.vin.size(); j++) {
1781 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1784 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1785 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1786 REJECT_INVALID, "bad-txns-nonfinal");
1790 // GetTransactionSigOpCost counts 3 types of sigops:
1791 // * legacy (always)
1792 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1793 // * witness (when witness enabled in flags and excludes coinbase)
1794 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1795 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1796 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1797 REJECT_INVALID, "bad-blk-sigops");
1799 txdata.emplace_back(tx);
1800 if (!tx.IsCoinBase())
1802 std::vector<CScriptCheck> vChecks;
1803 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1804 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1805 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1806 tx.GetHash().ToString(), FormatStateMessage(state));
1807 control.Add(vChecks);
1810 CTxUndo undoDummy;
1811 if (i > 0) {
1812 blockundo.vtxundo.push_back(CTxUndo());
1814 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1816 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1817 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1819 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1820 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);
1822 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1823 if (block.vtx[0]->GetValueOut() > blockReward)
1824 return state.DoS(100,
1825 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1826 block.vtx[0]->GetValueOut(), blockReward),
1827 REJECT_INVALID, "bad-cb-amount");
1829 if (!control.Wait())
1830 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1831 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1832 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);
1834 if (fJustCheck)
1835 return true;
1837 // Write undo information to disk
1838 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1840 if (pindex->GetUndoPos().IsNull()) {
1841 CDiskBlockPos _pos;
1842 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1843 return error("ConnectBlock(): FindUndoPos failed");
1844 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1845 return AbortNode(state, "Failed to write undo data");
1847 // update nUndoPos in block index
1848 pindex->nUndoPos = _pos.nPos;
1849 pindex->nStatus |= BLOCK_HAVE_UNDO;
1852 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1853 setDirtyBlockIndex.insert(pindex);
1856 if (fTxIndex)
1857 if (!pblocktree->WriteTxIndex(vPos))
1858 return AbortNode(state, "Failed to write transaction index");
1860 assert(pindex->phashBlock);
1861 // add this block to the view's block chain
1862 view.SetBestBlock(pindex->GetBlockHash());
1864 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1865 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1867 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1868 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1870 return true;
1874 * Update the on-disk chain state.
1875 * The caches and indexes are flushed depending on the mode we're called with
1876 * if they're too large, if it's been a while since the last write,
1877 * or always and in all cases if we're in prune mode and are deleting files.
1879 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1880 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1881 LOCK(cs_main);
1882 static int64_t nLastWrite = 0;
1883 static int64_t nLastFlush = 0;
1884 static int64_t nLastSetChain = 0;
1885 std::set<int> setFilesToPrune;
1886 bool fFlushForPrune = false;
1887 bool fDoFullFlush = false;
1888 int64_t nNow = 0;
1889 try {
1891 LOCK(cs_LastBlockFile);
1892 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1893 if (nManualPruneHeight > 0) {
1894 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1895 } else {
1896 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1897 fCheckForPruning = false;
1899 if (!setFilesToPrune.empty()) {
1900 fFlushForPrune = true;
1901 if (!fHavePruned) {
1902 pblocktree->WriteFlag("prunedblockfiles", true);
1903 fHavePruned = true;
1907 nNow = GetTimeMicros();
1908 // Avoid writing/flushing immediately after startup.
1909 if (nLastWrite == 0) {
1910 nLastWrite = nNow;
1912 if (nLastFlush == 0) {
1913 nLastFlush = nNow;
1915 if (nLastSetChain == 0) {
1916 nLastSetChain = nNow;
1918 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1919 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1920 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1921 // 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).
1922 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1923 // The cache is over the limit, we have to write now.
1924 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1925 // 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.
1926 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1927 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1928 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1929 // Combine all conditions that result in a full cache flush.
1930 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1931 // Write blocks and block index to disk.
1932 if (fDoFullFlush || fPeriodicWrite) {
1933 // Depend on nMinDiskSpace to ensure we can write block index
1934 if (!CheckDiskSpace(0))
1935 return state.Error("out of disk space");
1936 // First make sure all block and undo data is flushed to disk.
1937 FlushBlockFile();
1938 // Then update all block file information (which may refer to block and undo files).
1940 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1941 vFiles.reserve(setDirtyFileInfo.size());
1942 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1943 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1944 setDirtyFileInfo.erase(it++);
1946 std::vector<const CBlockIndex*> vBlocks;
1947 vBlocks.reserve(setDirtyBlockIndex.size());
1948 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1949 vBlocks.push_back(*it);
1950 setDirtyBlockIndex.erase(it++);
1952 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1953 return AbortNode(state, "Failed to write to block index database");
1956 // Finally remove any pruned files
1957 if (fFlushForPrune)
1958 UnlinkPrunedFiles(setFilesToPrune);
1959 nLastWrite = nNow;
1961 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1962 if (fDoFullFlush) {
1963 // Typical Coin structures on disk are around 48 bytes in size.
1964 // Pushing a new one to the database can cause it to be written
1965 // twice (once in the log, and once in the tables). This is already
1966 // an overestimation, as most will delete an existing entry or
1967 // overwrite one. Still, use a conservative safety factor of 2.
1968 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1969 return state.Error("out of disk space");
1970 // Flush the chainstate (which may refer to block index entries).
1971 if (!pcoinsTip->Flush())
1972 return AbortNode(state, "Failed to write to coin database");
1973 nLastFlush = nNow;
1976 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1977 // Update best block in wallet (so we can detect restored wallets).
1978 GetMainSignals().SetBestChain(chainActive.GetLocator());
1979 nLastSetChain = nNow;
1981 } catch (const std::runtime_error& e) {
1982 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1984 return true;
1987 void FlushStateToDisk() {
1988 CValidationState state;
1989 const CChainParams& chainparams = Params();
1990 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
1993 void PruneAndFlush() {
1994 CValidationState state;
1995 fCheckForPruning = true;
1996 const CChainParams& chainparams = Params();
1997 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2000 static void DoWarning(const std::string& strWarning)
2002 static bool fWarned = false;
2003 SetMiscWarning(strWarning);
2004 if (!fWarned) {
2005 AlertNotify(strWarning);
2006 fWarned = true;
2010 /** Update chainActive and related internal data structures. */
2011 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2012 chainActive.SetTip(pindexNew);
2014 // New best block
2015 mempool.AddTransactionsUpdated(1);
2017 cvBlockChange.notify_all();
2019 std::vector<std::string> warningMessages;
2020 if (!IsInitialBlockDownload())
2022 int nUpgraded = 0;
2023 const CBlockIndex* pindex = chainActive.Tip();
2024 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2025 WarningBitsConditionChecker checker(bit);
2026 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2027 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2028 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2029 if (state == THRESHOLD_ACTIVE) {
2030 DoWarning(strWarning);
2031 } else {
2032 warningMessages.push_back(strWarning);
2036 // Check the version of the last 100 blocks to see if we need to upgrade:
2037 for (int i = 0; i < 100 && pindex != nullptr; i++)
2039 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2040 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2041 ++nUpgraded;
2042 pindex = pindex->pprev;
2044 if (nUpgraded > 0)
2045 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2046 if (nUpgraded > 100/2)
2048 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2049 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2050 DoWarning(strWarning);
2053 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2054 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2055 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2056 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2057 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2058 if (!warningMessages.empty())
2059 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2060 LogPrintf("\n");
2064 /** Disconnect chainActive's tip.
2065 * After calling, the mempool will be in an inconsistent state, with
2066 * transactions from disconnected blocks being added to disconnectpool. You
2067 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2068 * with cs_main held.
2070 * If disconnectpool is nullptr, then no disconnected transactions are added to
2071 * disconnectpool (note that the caller is responsible for mempool consistency
2072 * in any case).
2074 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2076 CBlockIndex *pindexDelete = chainActive.Tip();
2077 assert(pindexDelete);
2078 // Read block from disk.
2079 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2080 CBlock& block = *pblock;
2081 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2082 return AbortNode(state, "Failed to read block");
2083 // Apply the block atomically to the chain state.
2084 int64_t nStart = GetTimeMicros();
2086 CCoinsViewCache view(pcoinsTip);
2087 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2088 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2089 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2090 bool flushed = view.Flush();
2091 assert(flushed);
2093 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2094 // Write the chain state to disk, if necessary.
2095 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2096 return false;
2098 if (disconnectpool) {
2099 // Save transactions to re-add to mempool at end of reorg
2100 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2101 disconnectpool->addTransaction(*it);
2103 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2104 // Drop the earliest entry, and remove its children from the mempool.
2105 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2106 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2107 disconnectpool->removeEntry(it);
2111 // Update chainActive and related variables.
2112 UpdateTip(pindexDelete->pprev, chainparams);
2113 // Let wallets know transactions went from 1-confirmed to
2114 // 0-confirmed or conflicted:
2115 GetMainSignals().BlockDisconnected(pblock);
2116 return true;
2119 static int64_t nTimeReadFromDisk = 0;
2120 static int64_t nTimeConnectTotal = 0;
2121 static int64_t nTimeFlush = 0;
2122 static int64_t nTimeChainState = 0;
2123 static int64_t nTimePostConnect = 0;
2125 struct PerBlockConnectTrace {
2126 CBlockIndex* pindex = nullptr;
2127 std::shared_ptr<const CBlock> pblock;
2128 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2129 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2132 * Used to track blocks whose transactions were applied to the UTXO state as a
2133 * part of a single ActivateBestChainStep call.
2135 * This class also tracks transactions that are removed from the mempool as
2136 * conflicts (per block) and can be used to pass all those transactions
2137 * through SyncTransaction.
2139 * This class assumes (and asserts) that the conflicted transactions for a given
2140 * block are added via mempool callbacks prior to the BlockConnected() associated
2141 * with those transactions. If any transactions are marked conflicted, it is
2142 * assumed that an associated block will always be added.
2144 * This class is single-use, once you call GetBlocksConnected() you have to throw
2145 * it away and make a new one.
2147 class ConnectTrace {
2148 private:
2149 std::vector<PerBlockConnectTrace> blocksConnected;
2150 CTxMemPool &pool;
2152 public:
2153 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2154 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2157 ~ConnectTrace() {
2158 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2161 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2162 assert(!blocksConnected.back().pindex);
2163 assert(pindex);
2164 assert(pblock);
2165 blocksConnected.back().pindex = pindex;
2166 blocksConnected.back().pblock = std::move(pblock);
2167 blocksConnected.emplace_back();
2170 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2171 // We always keep one extra block at the end of our list because
2172 // blocks are added after all the conflicted transactions have
2173 // been filled in. Thus, the last entry should always be an empty
2174 // one waiting for the transactions from the next block. We pop
2175 // the last entry here to make sure the list we return is sane.
2176 assert(!blocksConnected.back().pindex);
2177 assert(blocksConnected.back().conflictedTxs->empty());
2178 blocksConnected.pop_back();
2179 return blocksConnected;
2182 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2183 assert(!blocksConnected.back().pindex);
2184 if (reason == MemPoolRemovalReason::CONFLICT) {
2185 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2191 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2192 * corresponding to pindexNew, to bypass loading it again from disk.
2194 * The block is added to connectTrace if connection succeeds.
2196 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2198 assert(pindexNew->pprev == chainActive.Tip());
2199 // Read block from disk.
2200 int64_t nTime1 = GetTimeMicros();
2201 std::shared_ptr<const CBlock> pthisBlock;
2202 if (!pblock) {
2203 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2204 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2205 return AbortNode(state, "Failed to read block");
2206 pthisBlock = pblockNew;
2207 } else {
2208 pthisBlock = pblock;
2210 const CBlock& blockConnecting = *pthisBlock;
2211 // Apply the block atomically to the chain state.
2212 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2213 int64_t nTime3;
2214 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2216 CCoinsViewCache view(pcoinsTip);
2217 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2218 GetMainSignals().BlockChecked(blockConnecting, state);
2219 if (!rv) {
2220 if (state.IsInvalid())
2221 InvalidBlockFound(pindexNew, state);
2222 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2224 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2225 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2226 bool flushed = view.Flush();
2227 assert(flushed);
2229 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2230 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2231 // Write the chain state to disk, if necessary.
2232 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2233 return false;
2234 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2235 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2236 // Remove conflicting transactions from the mempool.;
2237 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2238 disconnectpool.removeForBlock(blockConnecting.vtx);
2239 // Update chainActive & related variables.
2240 UpdateTip(pindexNew, chainparams);
2242 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2243 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2244 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2246 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2247 return true;
2251 * Return the tip of the chain with the most work in it, that isn't
2252 * known to be invalid (it's however far from certain to be valid).
2254 static CBlockIndex* FindMostWorkChain() {
2255 do {
2256 CBlockIndex *pindexNew = nullptr;
2258 // Find the best candidate header.
2260 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2261 if (it == setBlockIndexCandidates.rend())
2262 return nullptr;
2263 pindexNew = *it;
2266 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2267 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2268 CBlockIndex *pindexTest = pindexNew;
2269 bool fInvalidAncestor = false;
2270 while (pindexTest && !chainActive.Contains(pindexTest)) {
2271 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2273 // Pruned nodes may have entries in setBlockIndexCandidates for
2274 // which block files have been deleted. Remove those as candidates
2275 // for the most work chain if we come across them; we can't switch
2276 // to a chain unless we have all the non-active-chain parent blocks.
2277 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2278 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2279 if (fFailedChain || fMissingData) {
2280 // Candidate chain is not usable (either invalid or missing data)
2281 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2282 pindexBestInvalid = pindexNew;
2283 CBlockIndex *pindexFailed = pindexNew;
2284 // Remove the entire chain from the set.
2285 while (pindexTest != pindexFailed) {
2286 if (fFailedChain) {
2287 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2288 } else if (fMissingData) {
2289 // If we're missing data, then add back to mapBlocksUnlinked,
2290 // so that if the block arrives in the future we can try adding
2291 // to setBlockIndexCandidates again.
2292 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2294 setBlockIndexCandidates.erase(pindexFailed);
2295 pindexFailed = pindexFailed->pprev;
2297 setBlockIndexCandidates.erase(pindexTest);
2298 fInvalidAncestor = true;
2299 break;
2301 pindexTest = pindexTest->pprev;
2303 if (!fInvalidAncestor)
2304 return pindexNew;
2305 } while(true);
2308 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2309 static void PruneBlockIndexCandidates() {
2310 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2311 // reorganization to a better block fails.
2312 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2313 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2314 setBlockIndexCandidates.erase(it++);
2316 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2317 assert(!setBlockIndexCandidates.empty());
2321 * Try to make some progress towards making pindexMostWork the active block.
2322 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2324 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2326 AssertLockHeld(cs_main);
2327 const CBlockIndex *pindexOldTip = chainActive.Tip();
2328 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2330 // Disconnect active blocks which are no longer in the best chain.
2331 bool fBlocksDisconnected = false;
2332 DisconnectedBlockTransactions disconnectpool;
2333 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2334 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2335 // This is likely a fatal error, but keep the mempool consistent,
2336 // just in case. Only remove from the mempool in this case.
2337 UpdateMempoolForReorg(disconnectpool, false);
2338 return false;
2340 fBlocksDisconnected = true;
2343 // Build list of new blocks to connect.
2344 std::vector<CBlockIndex*> vpindexToConnect;
2345 bool fContinue = true;
2346 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2347 while (fContinue && nHeight != pindexMostWork->nHeight) {
2348 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2349 // a few blocks along the way.
2350 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2351 vpindexToConnect.clear();
2352 vpindexToConnect.reserve(nTargetHeight - nHeight);
2353 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2354 while (pindexIter && pindexIter->nHeight != nHeight) {
2355 vpindexToConnect.push_back(pindexIter);
2356 pindexIter = pindexIter->pprev;
2358 nHeight = nTargetHeight;
2360 // Connect new blocks.
2361 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2362 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2363 if (state.IsInvalid()) {
2364 // The block violates a consensus rule.
2365 if (!state.CorruptionPossible())
2366 InvalidChainFound(vpindexToConnect.back());
2367 state = CValidationState();
2368 fInvalidFound = true;
2369 fContinue = false;
2370 break;
2371 } else {
2372 // A system error occurred (disk space, database error, ...).
2373 // Make the mempool consistent with the current tip, just in case
2374 // any observers try to use it before shutdown.
2375 UpdateMempoolForReorg(disconnectpool, false);
2376 return false;
2378 } else {
2379 PruneBlockIndexCandidates();
2380 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2381 // We're in a better position than we were. Return temporarily to release the lock.
2382 fContinue = false;
2383 break;
2389 if (fBlocksDisconnected) {
2390 // If any blocks were disconnected, disconnectpool may be non empty. Add
2391 // any disconnected transactions back to the mempool.
2392 UpdateMempoolForReorg(disconnectpool, true);
2394 mempool.check(pcoinsTip);
2396 // Callbacks/notifications for a new best chain.
2397 if (fInvalidFound)
2398 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2399 else
2400 CheckForkWarningConditions();
2402 return true;
2405 static void NotifyHeaderTip() {
2406 bool fNotify = false;
2407 bool fInitialBlockDownload = false;
2408 static CBlockIndex* pindexHeaderOld = nullptr;
2409 CBlockIndex* pindexHeader = nullptr;
2411 LOCK(cs_main);
2412 pindexHeader = pindexBestHeader;
2414 if (pindexHeader != pindexHeaderOld) {
2415 fNotify = true;
2416 fInitialBlockDownload = IsInitialBlockDownload();
2417 pindexHeaderOld = pindexHeader;
2420 // Send block tip changed notifications without cs_main
2421 if (fNotify) {
2422 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2427 * Make the best chain active, in multiple steps. The result is either failure
2428 * or an activated best chain. pblock is either nullptr or a pointer to a block
2429 * that is already loaded (to avoid loading it again from disk).
2431 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2432 // Note that while we're often called here from ProcessNewBlock, this is
2433 // far from a guarantee. Things in the P2P/RPC will often end up calling
2434 // us in the middle of ProcessNewBlock - do not assume pblock is set
2435 // sanely for performance or correctness!
2437 CBlockIndex *pindexMostWork = nullptr;
2438 CBlockIndex *pindexNewTip = nullptr;
2439 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2440 do {
2441 boost::this_thread::interruption_point();
2442 if (ShutdownRequested())
2443 break;
2445 const CBlockIndex *pindexFork;
2446 bool fInitialDownload;
2448 LOCK(cs_main);
2449 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2451 CBlockIndex *pindexOldTip = chainActive.Tip();
2452 if (pindexMostWork == nullptr) {
2453 pindexMostWork = FindMostWorkChain();
2456 // Whether we have anything to do at all.
2457 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2458 return true;
2460 bool fInvalidFound = false;
2461 std::shared_ptr<const CBlock> nullBlockPtr;
2462 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2463 return false;
2465 if (fInvalidFound) {
2466 // Wipe cache, we may need another branch now.
2467 pindexMostWork = nullptr;
2469 pindexNewTip = chainActive.Tip();
2470 pindexFork = chainActive.FindFork(pindexOldTip);
2471 fInitialDownload = IsInitialBlockDownload();
2473 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2474 assert(trace.pblock && trace.pindex);
2475 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2478 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2480 // Notifications/callbacks that can run without cs_main
2482 // Notify external listeners about the new tip.
2483 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2485 // Always notify the UI if a new block tip was connected
2486 if (pindexFork != pindexNewTip) {
2487 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2490 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2491 } while (pindexNewTip != pindexMostWork);
2492 CheckBlockIndex(chainparams.GetConsensus());
2494 // Write changes periodically to disk, after relay.
2495 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2496 return false;
2499 return true;
2503 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2506 LOCK(cs_main);
2507 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2508 // Nothing to do, this block is not at the tip.
2509 return true;
2511 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2512 // The chain has been extended since the last call, reset the counter.
2513 nBlockReverseSequenceId = -1;
2515 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2516 setBlockIndexCandidates.erase(pindex);
2517 pindex->nSequenceId = nBlockReverseSequenceId;
2518 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2519 // We can't keep reducing the counter if somebody really wants to
2520 // call preciousblock 2**31-1 times on the same set of tips...
2521 nBlockReverseSequenceId--;
2523 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2524 setBlockIndexCandidates.insert(pindex);
2525 PruneBlockIndexCandidates();
2529 return ActivateBestChain(state, params);
2532 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2534 AssertLockHeld(cs_main);
2536 // Mark the block itself as invalid.
2537 pindex->nStatus |= BLOCK_FAILED_VALID;
2538 setDirtyBlockIndex.insert(pindex);
2539 setBlockIndexCandidates.erase(pindex);
2541 DisconnectedBlockTransactions disconnectpool;
2542 while (chainActive.Contains(pindex)) {
2543 CBlockIndex *pindexWalk = chainActive.Tip();
2544 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2545 setDirtyBlockIndex.insert(pindexWalk);
2546 setBlockIndexCandidates.erase(pindexWalk);
2547 // ActivateBestChain considers blocks already in chainActive
2548 // unconditionally valid already, so force disconnect away from it.
2549 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2550 // It's probably hopeless to try to make the mempool consistent
2551 // here if DisconnectTip failed, but we can try.
2552 UpdateMempoolForReorg(disconnectpool, false);
2553 return false;
2557 // DisconnectTip will add transactions to disconnectpool; try to add these
2558 // back to the mempool.
2559 UpdateMempoolForReorg(disconnectpool, true);
2561 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2562 // add it again.
2563 BlockMap::iterator it = mapBlockIndex.begin();
2564 while (it != mapBlockIndex.end()) {
2565 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2566 setBlockIndexCandidates.insert(it->second);
2568 it++;
2571 InvalidChainFound(pindex);
2572 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2573 return true;
2576 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2577 AssertLockHeld(cs_main);
2579 int nHeight = pindex->nHeight;
2581 // Remove the invalidity flag from this block and all its descendants.
2582 BlockMap::iterator it = mapBlockIndex.begin();
2583 while (it != mapBlockIndex.end()) {
2584 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2585 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2586 setDirtyBlockIndex.insert(it->second);
2587 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2588 setBlockIndexCandidates.insert(it->second);
2590 if (it->second == pindexBestInvalid) {
2591 // Reset invalid block marker if it was pointing to one of those.
2592 pindexBestInvalid = nullptr;
2595 it++;
2598 // Remove the invalidity flag from all ancestors too.
2599 while (pindex != nullptr) {
2600 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2601 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2602 setDirtyBlockIndex.insert(pindex);
2604 pindex = pindex->pprev;
2606 return true;
2609 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2611 // Check for duplicate
2612 uint256 hash = block.GetHash();
2613 BlockMap::iterator it = mapBlockIndex.find(hash);
2614 if (it != mapBlockIndex.end())
2615 return it->second;
2617 // Construct new block index object
2618 CBlockIndex* pindexNew = new CBlockIndex(block);
2619 // We assign the sequence id to blocks only when the full data is available,
2620 // to avoid miners withholding blocks but broadcasting headers, to get a
2621 // competitive advantage.
2622 pindexNew->nSequenceId = 0;
2623 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2624 pindexNew->phashBlock = &((*mi).first);
2625 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2626 if (miPrev != mapBlockIndex.end())
2628 pindexNew->pprev = (*miPrev).second;
2629 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2630 pindexNew->BuildSkip();
2632 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2633 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2634 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2635 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2636 pindexBestHeader = pindexNew;
2638 setDirtyBlockIndex.insert(pindexNew);
2640 return pindexNew;
2643 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2644 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2646 pindexNew->nTx = block.vtx.size();
2647 pindexNew->nChainTx = 0;
2648 pindexNew->nFile = pos.nFile;
2649 pindexNew->nDataPos = pos.nPos;
2650 pindexNew->nUndoPos = 0;
2651 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2652 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2653 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2655 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2656 setDirtyBlockIndex.insert(pindexNew);
2658 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2659 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2660 std::deque<CBlockIndex*> queue;
2661 queue.push_back(pindexNew);
2663 // Recursively process any descendant blocks that now may be eligible to be connected.
2664 while (!queue.empty()) {
2665 CBlockIndex *pindex = queue.front();
2666 queue.pop_front();
2667 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2669 LOCK(cs_nBlockSequenceId);
2670 pindex->nSequenceId = nBlockSequenceId++;
2672 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2673 setBlockIndexCandidates.insert(pindex);
2675 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2676 while (range.first != range.second) {
2677 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2678 queue.push_back(it->second);
2679 range.first++;
2680 mapBlocksUnlinked.erase(it);
2683 } else {
2684 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2685 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2689 return true;
2692 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2694 LOCK(cs_LastBlockFile);
2696 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2697 if (vinfoBlockFile.size() <= nFile) {
2698 vinfoBlockFile.resize(nFile + 1);
2701 if (!fKnown) {
2702 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2703 nFile++;
2704 if (vinfoBlockFile.size() <= nFile) {
2705 vinfoBlockFile.resize(nFile + 1);
2708 pos.nFile = nFile;
2709 pos.nPos = vinfoBlockFile[nFile].nSize;
2712 if ((int)nFile != nLastBlockFile) {
2713 if (!fKnown) {
2714 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2716 FlushBlockFile(!fKnown);
2717 nLastBlockFile = nFile;
2720 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2721 if (fKnown)
2722 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2723 else
2724 vinfoBlockFile[nFile].nSize += nAddSize;
2726 if (!fKnown) {
2727 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2728 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2729 if (nNewChunks > nOldChunks) {
2730 if (fPruneMode)
2731 fCheckForPruning = true;
2732 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2733 FILE *file = OpenBlockFile(pos);
2734 if (file) {
2735 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2736 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2737 fclose(file);
2740 else
2741 return state.Error("out of disk space");
2745 setDirtyFileInfo.insert(nFile);
2746 return true;
2749 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2751 pos.nFile = nFile;
2753 LOCK(cs_LastBlockFile);
2755 unsigned int nNewSize;
2756 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2757 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2758 setDirtyFileInfo.insert(nFile);
2760 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2761 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2762 if (nNewChunks > nOldChunks) {
2763 if (fPruneMode)
2764 fCheckForPruning = true;
2765 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2766 FILE *file = OpenUndoFile(pos);
2767 if (file) {
2768 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2769 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2770 fclose(file);
2773 else
2774 return state.Error("out of disk space");
2777 return true;
2780 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2782 // Check proof of work matches claimed amount
2783 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2784 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2786 return true;
2789 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2791 // These are checks that are independent of context.
2793 if (block.fChecked)
2794 return true;
2796 // Check that the header is valid (particularly PoW). This is mostly
2797 // redundant with the call in AcceptBlockHeader.
2798 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2799 return false;
2801 // Check the merkle root.
2802 if (fCheckMerkleRoot) {
2803 bool mutated;
2804 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2805 if (block.hashMerkleRoot != hashMerkleRoot2)
2806 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2808 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2809 // of transactions in a block without affecting the merkle root of a block,
2810 // while still invalidating it.
2811 if (mutated)
2812 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2815 // All potential-corruption validation must be done before we do any
2816 // transaction validation, as otherwise we may mark the header as invalid
2817 // because we receive the wrong transactions for it.
2818 // Note that witness malleability is checked in ContextualCheckBlock, so no
2819 // checks that use witness data may be performed here.
2821 // Size limits
2822 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)
2823 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2825 // First transaction must be coinbase, the rest must not be
2826 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2827 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2828 for (unsigned int i = 1; i < block.vtx.size(); i++)
2829 if (block.vtx[i]->IsCoinBase())
2830 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2832 // Check transactions
2833 for (const auto& tx : block.vtx)
2834 if (!CheckTransaction(*tx, state, false))
2835 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2836 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2838 unsigned int nSigOps = 0;
2839 for (const auto& tx : block.vtx)
2841 nSigOps += GetLegacySigOpCount(*tx);
2843 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2844 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2846 if (fCheckPOW && fCheckMerkleRoot)
2847 block.fChecked = true;
2849 return true;
2852 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2854 LOCK(cs_main);
2855 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2858 // Compute at which vout of the block's coinbase transaction the witness
2859 // commitment occurs, or -1 if not found.
2860 static int GetWitnessCommitmentIndex(const CBlock& block)
2862 int commitpos = -1;
2863 if (!block.vtx.empty()) {
2864 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2865 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) {
2866 commitpos = o;
2870 return commitpos;
2873 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2875 int commitpos = GetWitnessCommitmentIndex(block);
2876 static const std::vector<unsigned char> nonce(32, 0x00);
2877 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2878 CMutableTransaction tx(*block.vtx[0]);
2879 tx.vin[0].scriptWitness.stack.resize(1);
2880 tx.vin[0].scriptWitness.stack[0] = nonce;
2881 block.vtx[0] = MakeTransactionRef(std::move(tx));
2885 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2887 std::vector<unsigned char> commitment;
2888 int commitpos = GetWitnessCommitmentIndex(block);
2889 std::vector<unsigned char> ret(32, 0x00);
2890 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2891 if (commitpos == -1) {
2892 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
2893 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
2894 CTxOut out;
2895 out.nValue = 0;
2896 out.scriptPubKey.resize(38);
2897 out.scriptPubKey[0] = OP_RETURN;
2898 out.scriptPubKey[1] = 0x24;
2899 out.scriptPubKey[2] = 0xaa;
2900 out.scriptPubKey[3] = 0x21;
2901 out.scriptPubKey[4] = 0xa9;
2902 out.scriptPubKey[5] = 0xed;
2903 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2904 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2905 CMutableTransaction tx(*block.vtx[0]);
2906 tx.vout.push_back(out);
2907 block.vtx[0] = MakeTransactionRef(std::move(tx));
2910 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2911 return commitment;
2914 /** Context-dependent validity checks.
2915 * By "context", we mean only the previous block headers, but not the UTXO
2916 * set; UTXO-related validity checks are done in ConnectBlock(). */
2917 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2919 assert(pindexPrev != nullptr);
2920 const int nHeight = pindexPrev->nHeight + 1;
2922 // Check proof of work
2923 const Consensus::Params& consensusParams = params.GetConsensus();
2924 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2925 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2927 // Check against checkpoints
2928 if (fCheckpointsEnabled) {
2929 // Don't accept any forks from the main chain prior to last checkpoint.
2930 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2931 // MapBlockIndex.
2932 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
2933 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2934 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2937 // Check timestamp against prev
2938 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2939 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2941 // Check timestamp
2942 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2943 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2945 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2946 // check for version 2, 3 and 4 upgrades
2947 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2948 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2949 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2950 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2951 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2953 return true;
2956 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2958 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
2960 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2961 int nLockTimeFlags = 0;
2962 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2963 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2966 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2967 ? pindexPrev->GetMedianTimePast()
2968 : block.GetBlockTime();
2970 // Check that all transactions are finalized
2971 for (const auto& tx : block.vtx) {
2972 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2973 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2977 // Enforce rule that the coinbase starts with serialized block height
2978 if (nHeight >= consensusParams.BIP34Height)
2980 CScript expect = CScript() << nHeight;
2981 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2982 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2983 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2987 // Validation for witness commitments.
2988 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2989 // coinbase (where 0x0000....0000 is used instead).
2990 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2991 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2992 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2993 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2994 // multiple, the last one is used.
2995 bool fHaveWitness = false;
2996 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2997 int commitpos = GetWitnessCommitmentIndex(block);
2998 if (commitpos != -1) {
2999 bool malleated = false;
3000 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3001 // The malleation check is ignored; as the transaction tree itself
3002 // already does not permit it, it is impossible to trigger in the
3003 // witness tree.
3004 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3005 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3007 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3008 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3009 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3011 fHaveWitness = true;
3015 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3016 if (!fHaveWitness) {
3017 for (const auto& tx : block.vtx) {
3018 if (tx->HasWitness()) {
3019 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3024 // After the coinbase witness nonce and commitment are verified,
3025 // we can check if the block weight passes (before we've checked the
3026 // coinbase witness, it would be possible for the weight to be too
3027 // large by filling up the coinbase witness, which doesn't change
3028 // the block hash, so we couldn't mark the block as permanently
3029 // failed).
3030 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3031 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3034 return true;
3037 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3039 AssertLockHeld(cs_main);
3040 // Check for duplicate
3041 uint256 hash = block.GetHash();
3042 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3043 CBlockIndex *pindex = nullptr;
3044 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3046 if (miSelf != mapBlockIndex.end()) {
3047 // Block header is already known.
3048 pindex = miSelf->second;
3049 if (ppindex)
3050 *ppindex = pindex;
3051 if (pindex->nStatus & BLOCK_FAILED_MASK)
3052 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3053 return true;
3056 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3057 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3059 // Get prev block index
3060 CBlockIndex* pindexPrev = nullptr;
3061 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3062 if (mi == mapBlockIndex.end())
3063 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3064 pindexPrev = (*mi).second;
3065 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3066 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3067 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3068 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3070 if (pindex == nullptr)
3071 pindex = AddToBlockIndex(block);
3073 if (ppindex)
3074 *ppindex = pindex;
3076 CheckBlockIndex(chainparams.GetConsensus());
3078 return true;
3081 // Exposed wrapper for AcceptBlockHeader
3082 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
3084 if (first_invalid != nullptr) first_invalid->SetNull();
3086 LOCK(cs_main);
3087 for (const CBlockHeader& header : headers) {
3088 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3089 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3090 if (first_invalid) *first_invalid = header;
3091 return false;
3093 if (ppindex) {
3094 *ppindex = pindex;
3098 NotifyHeaderTip();
3099 return true;
3102 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3103 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3105 const CBlock& block = *pblock;
3107 if (fNewBlock) *fNewBlock = false;
3108 AssertLockHeld(cs_main);
3110 CBlockIndex *pindexDummy = nullptr;
3111 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3113 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3114 return false;
3116 // Try to process all requested blocks that we don't have, but only
3117 // process an unrequested block if it's new and has enough work to
3118 // advance our tip, and isn't too many blocks ahead.
3119 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3120 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3121 // Blocks that are too out-of-order needlessly limit the effectiveness of
3122 // pruning, because pruning will not delete block files that contain any
3123 // blocks which are too close in height to the tip. Apply this test
3124 // regardless of whether pruning is enabled; it should generally be safe to
3125 // not process unrequested blocks.
3126 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3128 // TODO: Decouple this function from the block download logic by removing fRequested
3129 // This requires some new chain data structure to efficiently look up if a
3130 // block is in a chain leading to a candidate for best tip, despite not
3131 // being such a candidate itself.
3133 // TODO: deal better with return value and error conditions for duplicate
3134 // and unrequested blocks.
3135 if (fAlreadyHave) return true;
3136 if (!fRequested) { // If we didn't ask for it:
3137 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3138 if (!fHasMoreWork) return true; // Don't process less-work chains
3139 if (fTooFarAhead) return true; // Block height is too high
3141 // Protect against DoS attacks from low-work chains.
3142 // If our tip is behind, a peer could try to send us
3143 // low-work blocks on a fake chain that we would never
3144 // request; don't process these.
3145 if (pindex->nChainWork < nMinimumChainWork) return true;
3147 if (fNewBlock) *fNewBlock = true;
3149 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3150 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3151 if (state.IsInvalid() && !state.CorruptionPossible()) {
3152 pindex->nStatus |= BLOCK_FAILED_VALID;
3153 setDirtyBlockIndex.insert(pindex);
3155 return error("%s: %s", __func__, FormatStateMessage(state));
3158 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3159 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3160 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3161 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3163 int nHeight = pindex->nHeight;
3165 // Write block to history file
3166 try {
3167 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3168 CDiskBlockPos blockPos;
3169 if (dbp != nullptr)
3170 blockPos = *dbp;
3171 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
3172 return error("AcceptBlock(): FindBlockPos failed");
3173 if (dbp == nullptr)
3174 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3175 AbortNode(state, "Failed to write block");
3176 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3177 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3178 } catch (const std::runtime_error& e) {
3179 return AbortNode(state, std::string("System error: ") + e.what());
3182 if (fCheckForPruning)
3183 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3185 return true;
3188 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3191 CBlockIndex *pindex = nullptr;
3192 if (fNewBlock) *fNewBlock = false;
3193 CValidationState state;
3194 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3195 // belt-and-suspenders.
3196 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3198 LOCK(cs_main);
3200 if (ret) {
3201 // Store to disk
3202 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3204 CheckBlockIndex(chainparams.GetConsensus());
3205 if (!ret) {
3206 GetMainSignals().BlockChecked(*pblock, state);
3207 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3211 NotifyHeaderTip();
3213 CValidationState state; // Only used to report errors, not invalidity - ignore it
3214 if (!ActivateBestChain(state, chainparams, pblock))
3215 return error("%s: ActivateBestChain failed", __func__);
3217 return true;
3220 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3222 AssertLockHeld(cs_main);
3223 assert(pindexPrev && pindexPrev == chainActive.Tip());
3224 CCoinsViewCache viewNew(pcoinsTip);
3225 CBlockIndex indexDummy(block);
3226 indexDummy.pprev = pindexPrev;
3227 indexDummy.nHeight = pindexPrev->nHeight + 1;
3229 // NOTE: CheckBlockHeader is called by CheckBlock
3230 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3231 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3232 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3233 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3234 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3235 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3236 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3237 return false;
3238 assert(state.IsValid());
3240 return true;
3244 * BLOCK PRUNING CODE
3247 /* Calculate the amount of disk space the block & undo files currently use */
3248 uint64_t CalculateCurrentUsage()
3250 LOCK(cs_LastBlockFile);
3252 uint64_t retval = 0;
3253 for (const CBlockFileInfo &file : vinfoBlockFile) {
3254 retval += file.nSize + file.nUndoSize;
3256 return retval;
3259 /* Prune a block file (modify associated database entries)*/
3260 void PruneOneBlockFile(const int fileNumber)
3262 LOCK(cs_LastBlockFile);
3264 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3265 CBlockIndex* pindex = it->second;
3266 if (pindex->nFile == fileNumber) {
3267 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3268 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3269 pindex->nFile = 0;
3270 pindex->nDataPos = 0;
3271 pindex->nUndoPos = 0;
3272 setDirtyBlockIndex.insert(pindex);
3274 // Prune from mapBlocksUnlinked -- any block we prune would have
3275 // to be downloaded again in order to consider its chain, at which
3276 // point it would be considered as a candidate for
3277 // mapBlocksUnlinked or setBlockIndexCandidates.
3278 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3279 while (range.first != range.second) {
3280 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3281 range.first++;
3282 if (_it->second == pindex) {
3283 mapBlocksUnlinked.erase(_it);
3289 vinfoBlockFile[fileNumber].SetNull();
3290 setDirtyFileInfo.insert(fileNumber);
3294 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3296 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3297 CDiskBlockPos pos(*it, 0);
3298 fs::remove(GetBlockPosFilename(pos, "blk"));
3299 fs::remove(GetBlockPosFilename(pos, "rev"));
3300 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3304 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3305 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3307 assert(fPruneMode && nManualPruneHeight > 0);
3309 LOCK2(cs_main, cs_LastBlockFile);
3310 if (chainActive.Tip() == nullptr)
3311 return;
3313 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3314 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3315 int count=0;
3316 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3317 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3318 continue;
3319 PruneOneBlockFile(fileNumber);
3320 setFilesToPrune.insert(fileNumber);
3321 count++;
3323 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3326 /* This function is called from the RPC code for pruneblockchain */
3327 void PruneBlockFilesManual(int nManualPruneHeight)
3329 CValidationState state;
3330 const CChainParams& chainparams = Params();
3331 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3335 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3336 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3337 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3338 * (which in this case means the blockchain must be re-downloaded.)
3340 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3341 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3342 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3343 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3344 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3345 * A db flag records the fact that at least some block files have been pruned.
3347 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3349 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3351 LOCK2(cs_main, cs_LastBlockFile);
3352 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3353 return;
3355 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3356 return;
3359 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3360 uint64_t nCurrentUsage = CalculateCurrentUsage();
3361 // We don't check to prune until after we've allocated new space for files
3362 // So we should leave a buffer under our target to account for another allocation
3363 // before the next pruning.
3364 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3365 uint64_t nBytesToPrune;
3366 int count=0;
3368 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3369 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3370 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3372 if (vinfoBlockFile[fileNumber].nSize == 0)
3373 continue;
3375 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3376 break;
3378 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3379 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3380 continue;
3382 PruneOneBlockFile(fileNumber);
3383 // Queue up the files for removal
3384 setFilesToPrune.insert(fileNumber);
3385 nCurrentUsage -= nBytesToPrune;
3386 count++;
3390 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3391 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3392 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3393 nLastBlockWeCanPrune, count);
3396 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3398 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3400 // Check for nMinDiskSpace bytes (currently 50MB)
3401 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3402 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3404 return true;
3407 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3409 if (pos.IsNull())
3410 return nullptr;
3411 fs::path path = GetBlockPosFilename(pos, prefix);
3412 fs::create_directories(path.parent_path());
3413 FILE* file = fsbridge::fopen(path, "rb+");
3414 if (!file && !fReadOnly)
3415 file = fsbridge::fopen(path, "wb+");
3416 if (!file) {
3417 LogPrintf("Unable to open file %s\n", path.string());
3418 return nullptr;
3420 if (pos.nPos) {
3421 if (fseek(file, pos.nPos, SEEK_SET)) {
3422 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3423 fclose(file);
3424 return nullptr;
3427 return file;
3430 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3431 return OpenDiskFile(pos, "blk", fReadOnly);
3434 /** Open an undo file (rev?????.dat) */
3435 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3436 return OpenDiskFile(pos, "rev", fReadOnly);
3439 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3441 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3444 CBlockIndex * InsertBlockIndex(uint256 hash)
3446 if (hash.IsNull())
3447 return nullptr;
3449 // Return existing
3450 BlockMap::iterator mi = mapBlockIndex.find(hash);
3451 if (mi != mapBlockIndex.end())
3452 return (*mi).second;
3454 // Create new
3455 CBlockIndex* pindexNew = new CBlockIndex();
3456 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3457 pindexNew->phashBlock = &((*mi).first);
3459 return pindexNew;
3462 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3464 if (!pblocktree->LoadBlockIndexGuts(chainparams.GetConsensus(), InsertBlockIndex))
3465 return false;
3467 boost::this_thread::interruption_point();
3469 // Calculate nChainWork
3470 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3471 vSortedByHeight.reserve(mapBlockIndex.size());
3472 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3474 CBlockIndex* pindex = item.second;
3475 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3477 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3478 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3480 CBlockIndex* pindex = item.second;
3481 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3482 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3483 // We can link the chain of blocks for which we've received transactions at some point.
3484 // Pruned nodes may have deleted the block.
3485 if (pindex->nTx > 0) {
3486 if (pindex->pprev) {
3487 if (pindex->pprev->nChainTx) {
3488 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3489 } else {
3490 pindex->nChainTx = 0;
3491 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3493 } else {
3494 pindex->nChainTx = pindex->nTx;
3497 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3498 setBlockIndexCandidates.insert(pindex);
3499 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3500 pindexBestInvalid = pindex;
3501 if (pindex->pprev)
3502 pindex->BuildSkip();
3503 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3504 pindexBestHeader = pindex;
3507 // Load block file info
3508 pblocktree->ReadLastBlockFile(nLastBlockFile);
3509 vinfoBlockFile.resize(nLastBlockFile + 1);
3510 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3511 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3512 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3514 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3515 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3516 CBlockFileInfo info;
3517 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3518 vinfoBlockFile.push_back(info);
3519 } else {
3520 break;
3524 // Check presence of blk files
3525 LogPrintf("Checking all blk files are present...\n");
3526 std::set<int> setBlkDataFiles;
3527 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3529 CBlockIndex* pindex = item.second;
3530 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3531 setBlkDataFiles.insert(pindex->nFile);
3534 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3536 CDiskBlockPos pos(*it, 0);
3537 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3538 return false;
3542 // Check whether we have ever pruned block & undo files
3543 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3544 if (fHavePruned)
3545 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3547 // Check whether we need to continue reindexing
3548 bool fReindexing = false;
3549 pblocktree->ReadReindexing(fReindexing);
3550 if(fReindexing) fReindex = true;
3552 // Check whether we have a transaction index
3553 pblocktree->ReadFlag("txindex", fTxIndex);
3554 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3556 return true;
3559 bool LoadChainTip(const CChainParams& chainparams)
3561 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3563 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3564 // In case we just added the genesis block, connect it now, so
3565 // that we always have a chainActive.Tip() when we return.
3566 LogPrintf("%s: Connecting genesis block...\n", __func__);
3567 CValidationState state;
3568 if (!ActivateBestChain(state, chainparams)) {
3569 return false;
3573 // Load pointer to end of best chain
3574 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3575 if (it == mapBlockIndex.end())
3576 return false;
3577 chainActive.SetTip(it->second);
3579 PruneBlockIndexCandidates();
3581 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3582 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3583 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3584 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3585 return true;
3588 CVerifyDB::CVerifyDB()
3590 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3593 CVerifyDB::~CVerifyDB()
3595 uiInterface.ShowProgress("", 100, false);
3598 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3600 LOCK(cs_main);
3601 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3602 return true;
3604 // Verify blocks in the best chain
3605 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3606 nCheckDepth = chainActive.Height();
3607 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3608 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3609 CCoinsViewCache coins(coinsview);
3610 CBlockIndex* pindexState = chainActive.Tip();
3611 CBlockIndex* pindexFailure = nullptr;
3612 int nGoodTransactions = 0;
3613 CValidationState state;
3614 int reportDone = 0;
3615 LogPrintf("[0%%]...");
3616 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3618 boost::this_thread::interruption_point();
3619 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3620 if (reportDone < percentageDone/10) {
3621 // report every 10% step
3622 LogPrintf("[%d%%]...", percentageDone);
3623 reportDone = percentageDone/10;
3625 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3626 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3627 break;
3628 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3629 // If pruning, only go back as far as we have data.
3630 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3631 break;
3633 CBlock block;
3634 // check level 0: read from disk
3635 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3636 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3637 // check level 1: verify block validity
3638 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3639 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3640 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3641 // check level 2: verify undo validity
3642 if (nCheckLevel >= 2 && pindex) {
3643 CBlockUndo undo;
3644 CDiskBlockPos pos = pindex->GetUndoPos();
3645 if (!pos.IsNull()) {
3646 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3647 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3650 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3651 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3652 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3653 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3654 if (res == DISCONNECT_FAILED) {
3655 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3657 pindexState = pindex->pprev;
3658 if (res == DISCONNECT_UNCLEAN) {
3659 nGoodTransactions = 0;
3660 pindexFailure = pindex;
3661 } else {
3662 nGoodTransactions += block.vtx.size();
3665 if (ShutdownRequested())
3666 return true;
3668 if (pindexFailure)
3669 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3671 // check level 4: try reconnecting blocks
3672 if (nCheckLevel >= 4) {
3673 CBlockIndex *pindex = pindexState;
3674 while (pindex != chainActive.Tip()) {
3675 boost::this_thread::interruption_point();
3676 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3677 pindex = chainActive.Next(pindex);
3678 CBlock block;
3679 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3680 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3681 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3682 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3686 LogPrintf("[DONE].\n");
3687 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3689 return true;
3692 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3693 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3695 // TODO: merge with ConnectBlock
3696 CBlock block;
3697 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3698 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3701 for (const CTransactionRef& tx : block.vtx) {
3702 if (!tx->IsCoinBase()) {
3703 for (const CTxIn &txin : tx->vin) {
3704 inputs.SpendCoin(txin.prevout);
3707 // Pass check = true as every addition may be an overwrite.
3708 AddCoins(inputs, *tx, pindex->nHeight, true);
3710 return true;
3713 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
3715 LOCK(cs_main);
3717 CCoinsViewCache cache(view);
3719 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3720 if (hashHeads.empty()) return true; // We're already in a consistent state.
3721 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3723 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3724 LogPrintf("Replaying blocks\n");
3726 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3727 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3728 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3730 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3731 return error("ReplayBlocks(): reorganization to unknown block requested");
3733 pindexNew = mapBlockIndex[hashHeads[0]];
3735 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3736 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3737 return error("ReplayBlocks(): reorganization from unknown block requested");
3739 pindexOld = mapBlockIndex[hashHeads[1]];
3740 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3741 assert(pindexFork != nullptr);
3744 // Rollback along the old branch.
3745 while (pindexOld != pindexFork) {
3746 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3747 CBlock block;
3748 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3749 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3751 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3752 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3753 if (res == DISCONNECT_FAILED) {
3754 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3756 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3757 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3758 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3759 // the result is still a version of the UTXO set with the effects of that block undone.
3761 pindexOld = pindexOld->pprev;
3764 // Roll forward from the forking point to the new tip.
3765 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3766 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3767 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3768 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3769 if (!RollforwardBlock(pindex, cache, params)) return false;
3772 cache.SetBestBlock(pindexNew->GetBlockHash());
3773 cache.Flush();
3774 uiInterface.ShowProgress("", 100, false);
3775 return true;
3778 bool RewindBlockIndex(const CChainParams& params)
3780 LOCK(cs_main);
3782 // Note that during -reindex-chainstate we are called with an empty chainActive!
3784 int nHeight = 1;
3785 while (nHeight <= chainActive.Height()) {
3786 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3787 break;
3789 nHeight++;
3792 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3793 CValidationState state;
3794 CBlockIndex* pindex = chainActive.Tip();
3795 while (chainActive.Height() >= nHeight) {
3796 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3797 // If pruning, don't try rewinding past the HAVE_DATA point;
3798 // since older blocks can't be served anyway, there's
3799 // no need to walk further, and trying to DisconnectTip()
3800 // will fail (and require a needless reindex/redownload
3801 // of the blockchain).
3802 break;
3804 if (!DisconnectTip(state, params, nullptr)) {
3805 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3807 // Occasionally flush state to disk.
3808 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
3809 return false;
3812 // Reduce validity flag and have-data flags.
3813 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3814 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3815 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3816 CBlockIndex* pindexIter = it->second;
3818 // Note: If we encounter an insufficiently validated block that
3819 // is on chainActive, it must be because we are a pruning node, and
3820 // this block or some successor doesn't HAVE_DATA, so we were unable to
3821 // rewind all the way. Blocks remaining on chainActive at this point
3822 // must not have their validity reduced.
3823 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3824 // Reduce validity
3825 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3826 // Remove have-data flags.
3827 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3828 // Remove storage location.
3829 pindexIter->nFile = 0;
3830 pindexIter->nDataPos = 0;
3831 pindexIter->nUndoPos = 0;
3832 // Remove various other things
3833 pindexIter->nTx = 0;
3834 pindexIter->nChainTx = 0;
3835 pindexIter->nSequenceId = 0;
3836 // Make sure it gets written.
3837 setDirtyBlockIndex.insert(pindexIter);
3838 // Update indexes
3839 setBlockIndexCandidates.erase(pindexIter);
3840 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3841 while (ret.first != ret.second) {
3842 if (ret.first->second == pindexIter) {
3843 mapBlocksUnlinked.erase(ret.first++);
3844 } else {
3845 ++ret.first;
3848 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3849 setBlockIndexCandidates.insert(pindexIter);
3853 if (chainActive.Tip() != nullptr) {
3854 // We can't prune block index candidates based on our tip if we have
3855 // no tip due to chainActive being empty!
3856 PruneBlockIndexCandidates();
3858 CheckBlockIndex(params.GetConsensus());
3860 // FlushStateToDisk can possibly read chainActive. Be conservative
3861 // and skip it here, we're about to -reindex-chainstate anyway, so
3862 // it'll get called a bunch real soon.
3863 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
3864 return false;
3868 return true;
3871 // May NOT be used after any connections are up as much
3872 // of the peer-processing logic assumes a consistent
3873 // block index state
3874 void UnloadBlockIndex()
3876 LOCK(cs_main);
3877 setBlockIndexCandidates.clear();
3878 chainActive.SetTip(nullptr);
3879 pindexBestInvalid = nullptr;
3880 pindexBestHeader = nullptr;
3881 mempool.clear();
3882 mapBlocksUnlinked.clear();
3883 vinfoBlockFile.clear();
3884 nLastBlockFile = 0;
3885 nBlockSequenceId = 1;
3886 setDirtyBlockIndex.clear();
3887 setDirtyFileInfo.clear();
3888 versionbitscache.Clear();
3889 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3890 warningcache[b].clear();
3893 for (BlockMap::value_type& entry : mapBlockIndex) {
3894 delete entry.second;
3896 mapBlockIndex.clear();
3897 fHavePruned = false;
3900 bool LoadBlockIndex(const CChainParams& chainparams)
3902 // Load block index from databases
3903 bool needs_init = fReindex;
3904 if (!fReindex) {
3905 bool ret = LoadBlockIndexDB(chainparams);
3906 if (!ret) return false;
3907 needs_init = mapBlockIndex.empty();
3910 if (needs_init) {
3911 // Everything here is for *new* reindex/DBs. Thus, though
3912 // LoadBlockIndexDB may have set fReindex if we shut down
3913 // mid-reindex previously, we don't check fReindex and
3914 // instead only check it prior to LoadBlockIndexDB to set
3915 // needs_init.
3917 LogPrintf("Initializing databases...\n");
3918 // Use the provided setting for -txindex in the new database
3919 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
3920 pblocktree->WriteFlag("txindex", fTxIndex);
3922 return true;
3925 bool LoadGenesisBlock(const CChainParams& chainparams)
3927 LOCK(cs_main);
3929 // Check whether we're already initialized by checking for genesis in
3930 // mapBlockIndex. Note that we can't use chainActive here, since it is
3931 // set based on the coins db, not the block index db, which is the only
3932 // thing loaded at this point.
3933 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
3934 return true;
3936 try {
3937 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3938 // Start new block file
3939 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3940 CDiskBlockPos blockPos;
3941 CValidationState state;
3942 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3943 return error("%s: FindBlockPos failed", __func__);
3944 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3945 return error("%s: writing genesis block to disk failed", __func__);
3946 CBlockIndex *pindex = AddToBlockIndex(block);
3947 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3948 return error("%s: genesis block not accepted", __func__);
3949 } catch (const std::runtime_error& e) {
3950 return error("%s: failed to write genesis block: %s", __func__, e.what());
3953 return true;
3956 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3958 // Map of disk positions for blocks with unknown parent (only used for reindex)
3959 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3960 int64_t nStart = GetTimeMillis();
3962 int nLoaded = 0;
3963 try {
3964 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3965 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3966 uint64_t nRewind = blkdat.GetPos();
3967 while (!blkdat.eof()) {
3968 boost::this_thread::interruption_point();
3970 blkdat.SetPos(nRewind);
3971 nRewind++; // start one byte further next time, in case of failure
3972 blkdat.SetLimit(); // remove former limit
3973 unsigned int nSize = 0;
3974 try {
3975 // locate a header
3976 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3977 blkdat.FindByte(chainparams.MessageStart()[0]);
3978 nRewind = blkdat.GetPos()+1;
3979 blkdat >> FLATDATA(buf);
3980 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3981 continue;
3982 // read size
3983 blkdat >> nSize;
3984 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3985 continue;
3986 } catch (const std::exception&) {
3987 // no valid block header found; don't complain
3988 break;
3990 try {
3991 // read block
3992 uint64_t nBlockPos = blkdat.GetPos();
3993 if (dbp)
3994 dbp->nPos = nBlockPos;
3995 blkdat.SetLimit(nBlockPos + nSize);
3996 blkdat.SetPos(nBlockPos);
3997 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3998 CBlock& block = *pblock;
3999 blkdat >> block;
4000 nRewind = blkdat.GetPos();
4002 // detect out of order blocks, and store them for later
4003 uint256 hash = block.GetHash();
4004 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4005 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4006 block.hashPrevBlock.ToString());
4007 if (dbp)
4008 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4009 continue;
4012 // process in case the block isn't known yet
4013 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4014 LOCK(cs_main);
4015 CValidationState state;
4016 if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4017 nLoaded++;
4018 if (state.IsError())
4019 break;
4020 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4021 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4024 // Activate the genesis block so normal node progress can continue
4025 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4026 CValidationState state;
4027 if (!ActivateBestChain(state, chainparams)) {
4028 break;
4032 NotifyHeaderTip();
4034 // Recursively process earlier encountered successors of this block
4035 std::deque<uint256> queue;
4036 queue.push_back(hash);
4037 while (!queue.empty()) {
4038 uint256 head = queue.front();
4039 queue.pop_front();
4040 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4041 while (range.first != range.second) {
4042 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4043 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4044 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4046 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4047 head.ToString());
4048 LOCK(cs_main);
4049 CValidationState dummy;
4050 if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4052 nLoaded++;
4053 queue.push_back(pblockrecursive->GetHash());
4056 range.first++;
4057 mapBlocksUnknownParent.erase(it);
4058 NotifyHeaderTip();
4061 } catch (const std::exception& e) {
4062 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4065 } catch (const std::runtime_error& e) {
4066 AbortNode(std::string("System error: ") + e.what());
4068 if (nLoaded > 0)
4069 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4070 return nLoaded > 0;
4073 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4075 if (!fCheckBlockIndex) {
4076 return;
4079 LOCK(cs_main);
4081 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4082 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4083 // iterating the block tree require that chainActive has been initialized.)
4084 if (chainActive.Height() < 0) {
4085 assert(mapBlockIndex.size() <= 1);
4086 return;
4089 // Build forward-pointing map of the entire block tree.
4090 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4091 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4092 forward.insert(std::make_pair(it->second->pprev, it->second));
4095 assert(forward.size() == mapBlockIndex.size());
4097 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4098 CBlockIndex *pindex = rangeGenesis.first->second;
4099 rangeGenesis.first++;
4100 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4102 // Iterate over the entire block tree, using depth-first search.
4103 // Along the way, remember whether there are blocks on the path from genesis
4104 // block being explored which are the first to have certain properties.
4105 size_t nNodes = 0;
4106 int nHeight = 0;
4107 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4108 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4109 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4110 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4111 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4112 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4113 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4114 while (pindex != nullptr) {
4115 nNodes++;
4116 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4117 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4118 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4119 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4120 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4121 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4122 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4124 // Begin: actual consistency checks.
4125 if (pindex->pprev == nullptr) {
4126 // Genesis block checks.
4127 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4128 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4130 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)
4131 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4132 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4133 if (!fHavePruned) {
4134 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4135 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4136 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4137 } else {
4138 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4139 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4141 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4142 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4143 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4144 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4145 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4146 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4147 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.
4148 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4149 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4150 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4151 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4152 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4153 if (pindexFirstInvalid == nullptr) {
4154 // Checks for not-invalid blocks.
4155 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4157 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4158 if (pindexFirstInvalid == nullptr) {
4159 // If this block sorts at least as good as the current tip and
4160 // is valid and we have all data for its parents, it must be in
4161 // setBlockIndexCandidates. chainActive.Tip() must also be there
4162 // even if some data has been pruned.
4163 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4164 assert(setBlockIndexCandidates.count(pindex));
4166 // If some parent is missing, then it could be that this block was in
4167 // setBlockIndexCandidates but had to be removed because of the missing data.
4168 // In this case it must be in mapBlocksUnlinked -- see test below.
4170 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4171 assert(setBlockIndexCandidates.count(pindex) == 0);
4173 // Check whether this block is in mapBlocksUnlinked.
4174 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4175 bool foundInUnlinked = false;
4176 while (rangeUnlinked.first != rangeUnlinked.second) {
4177 assert(rangeUnlinked.first->first == pindex->pprev);
4178 if (rangeUnlinked.first->second == pindex) {
4179 foundInUnlinked = true;
4180 break;
4182 rangeUnlinked.first++;
4184 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4185 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4186 assert(foundInUnlinked);
4188 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4189 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4190 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4191 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4192 assert(fHavePruned); // We must have pruned.
4193 // This block may have entered mapBlocksUnlinked if:
4194 // - it has a descendant that at some point had more work than the
4195 // tip, and
4196 // - we tried switching to that descendant but were missing
4197 // data for some intermediate block between chainActive and the
4198 // tip.
4199 // So if this block is itself better than chainActive.Tip() and it wasn't in
4200 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4201 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4202 if (pindexFirstInvalid == nullptr) {
4203 assert(foundInUnlinked);
4207 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4208 // End: actual consistency checks.
4210 // Try descending into the first subnode.
4211 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4212 if (range.first != range.second) {
4213 // A subnode was found.
4214 pindex = range.first->second;
4215 nHeight++;
4216 continue;
4218 // This is a leaf node.
4219 // Move upwards until we reach a node of which we have not yet visited the last child.
4220 while (pindex) {
4221 // We are going to either move to a parent or a sibling of pindex.
4222 // If pindex was the first with a certain property, unset the corresponding variable.
4223 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4224 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4225 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4226 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4227 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4228 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4229 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4230 // Find our parent.
4231 CBlockIndex* pindexPar = pindex->pprev;
4232 // Find which child we just visited.
4233 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4234 while (rangePar.first->second != pindex) {
4235 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4236 rangePar.first++;
4238 // Proceed to the next one.
4239 rangePar.first++;
4240 if (rangePar.first != rangePar.second) {
4241 // Move to the sibling.
4242 pindex = rangePar.first->second;
4243 break;
4244 } else {
4245 // Move up further.
4246 pindex = pindexPar;
4247 nHeight--;
4248 continue;
4253 // Check that we actually traversed the entire map.
4254 assert(nNodes == forward.size());
4257 std::string CBlockFileInfo::ToString() const
4259 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));
4262 CBlockFileInfo* GetBlockFileInfo(size_t n)
4264 LOCK(cs_LastBlockFile);
4266 return &vinfoBlockFile.at(n);
4269 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4271 LOCK(cs_main);
4272 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4275 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4277 LOCK(cs_main);
4278 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4281 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4283 LOCK(cs_main);
4284 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4287 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4289 bool LoadMempool(void)
4291 const CChainParams& chainparams = Params();
4292 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4293 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4294 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4295 if (file.IsNull()) {
4296 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4297 return false;
4300 int64_t count = 0;
4301 int64_t expired = 0;
4302 int64_t failed = 0;
4303 int64_t already_there = 0;
4304 int64_t nNow = GetTime();
4306 try {
4307 uint64_t version;
4308 file >> version;
4309 if (version != MEMPOOL_DUMP_VERSION) {
4310 return false;
4312 uint64_t num;
4313 file >> num;
4314 while (num--) {
4315 CTransactionRef tx;
4316 int64_t nTime;
4317 int64_t nFeeDelta;
4318 file >> tx;
4319 file >> nTime;
4320 file >> nFeeDelta;
4322 CAmount amountdelta = nFeeDelta;
4323 if (amountdelta) {
4324 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4326 CValidationState state;
4327 if (nTime + nExpiryTimeout > nNow) {
4328 LOCK(cs_main);
4329 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4330 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4331 if (state.IsValid()) {
4332 ++count;
4333 } else {
4334 // mempool may contain the transaction already, e.g. from
4335 // wallet(s) having loaded it while we were processing
4336 // mempool transactions; consider these as valid, instead of
4337 // failed, but mark them as 'already there'
4338 if (mempool.exists(tx->GetHash())) {
4339 ++already_there;
4340 } else {
4341 ++failed;
4344 } else {
4345 ++expired;
4347 if (ShutdownRequested())
4348 return false;
4350 std::map<uint256, CAmount> mapDeltas;
4351 file >> mapDeltas;
4353 for (const auto& i : mapDeltas) {
4354 mempool.PrioritiseTransaction(i.first, i.second);
4356 } catch (const std::exception& e) {
4357 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4358 return false;
4361 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4362 return true;
4365 bool DumpMempool(void)
4367 int64_t start = GetTimeMicros();
4369 std::map<uint256, CAmount> mapDeltas;
4370 std::vector<TxMempoolInfo> vinfo;
4373 LOCK(mempool.cs);
4374 for (const auto &i : mempool.mapDeltas) {
4375 mapDeltas[i.first] = i.second;
4377 vinfo = mempool.infoAll();
4380 int64_t mid = GetTimeMicros();
4382 try {
4383 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4384 if (!filestr) {
4385 return false;
4388 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4390 uint64_t version = MEMPOOL_DUMP_VERSION;
4391 file << version;
4393 file << (uint64_t)vinfo.size();
4394 for (const auto& i : vinfo) {
4395 file << *(i.tx);
4396 file << (int64_t)i.nTime;
4397 file << (int64_t)i.nFeeDelta;
4398 mapDeltas.erase(i.tx->GetHash());
4401 file << mapDeltas;
4402 FileCommit(file.Get());
4403 file.fclose();
4404 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4405 int64_t last = GetTimeMicros();
4406 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4407 } catch (const std::exception& e) {
4408 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4409 return false;
4411 return true;
4414 //! Guess how far we are in the verification process at the given block index
4415 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4416 if (pindex == nullptr)
4417 return 0.0;
4419 int64_t nNow = time(nullptr);
4421 double fTxTotal;
4423 if (pindex->nChainTx <= data.nTxCount) {
4424 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4425 } else {
4426 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4429 return pindex->nChainTx / fTxTotal;
4432 class CMainCleanup
4434 public:
4435 CMainCleanup() {}
4436 ~CMainCleanup() {
4437 // block headers
4438 BlockMap::iterator it1 = mapBlockIndex.begin();
4439 for (; it1 != mapBlockIndex.end(); it1++)
4440 delete (*it1).second;
4441 mapBlockIndex.clear();
4443 } instance_of_cmaincleanup;