[tests] Add libFuzzer support.
[bitcoinplatinum.git] / src / validation.cpp
blob73466b9df7d17c030c9d548901e77a1414c42e9a
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 "fs.h"
18 #include "hash.h"
19 #include "init.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "pow.h"
23 #include "primitives/block.h"
24 #include "primitives/transaction.h"
25 #include "random.h"
26 #include "script/script.h"
27 #include "script/sigcache.h"
28 #include "script/standard.h"
29 #include "timedata.h"
30 #include "tinyformat.h"
31 #include "txdb.h"
32 #include "txmempool.h"
33 #include "ui_interface.h"
34 #include "undo.h"
35 #include "util.h"
36 #include "utilmoneystr.h"
37 #include "utilstrencodings.h"
38 #include "validationinterface.h"
39 #include "versionbits.h"
40 #include "warnings.h"
42 #include <atomic>
43 #include <sstream>
45 #include <boost/algorithm/string/replace.hpp>
46 #include <boost/algorithm/string/join.hpp>
47 #include <boost/math/distributions/poisson.hpp>
48 #include <boost/thread.hpp>
50 #if defined(NDEBUG)
51 # error "Bitcoin cannot be compiled without assertions."
52 #endif
54 /**
55 * Global state
58 CCriticalSection cs_main;
60 BlockMap mapBlockIndex;
61 CChain chainActive;
62 CBlockIndex *pindexBestHeader = NULL;
63 CWaitableCriticalSection csBestBlock;
64 CConditionVariable cvBlockChange;
65 int nScriptCheckThreads = 0;
66 std::atomic_bool fImporting(false);
67 bool fReindex = false;
68 bool fTxIndex = false;
69 bool fHavePruned = false;
70 bool fPruneMode = false;
71 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
72 bool fRequireStandard = true;
73 bool fCheckBlockIndex = false;
74 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
75 size_t nCoinCacheUsage = 5000 * 300;
76 uint64_t nPruneTarget = 0;
77 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
78 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
80 uint256 hashAssumeValid;
82 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
83 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
85 CBlockPolicyEstimator feeEstimator;
86 CTxMemPool mempool(&feeEstimator);
88 static void CheckBlockIndex(const Consensus::Params& consensusParams);
90 /** Constant stuff for coinbase transactions we create: */
91 CScript COINBASE_FLAGS;
93 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
95 // Internal stuff
96 namespace {
98 struct CBlockIndexWorkComparator
100 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
101 // First sort by most total work, ...
102 if (pa->nChainWork > pb->nChainWork) return false;
103 if (pa->nChainWork < pb->nChainWork) return true;
105 // ... then by earliest time received, ...
106 if (pa->nSequenceId < pb->nSequenceId) return false;
107 if (pa->nSequenceId > pb->nSequenceId) return true;
109 // Use pointer address as tie breaker (should only happen with blocks
110 // loaded from disk, as those all have id 0).
111 if (pa < pb) return false;
112 if (pa > pb) return true;
114 // Identical blocks.
115 return false;
119 CBlockIndex *pindexBestInvalid;
122 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
123 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
124 * missing the data for the block.
126 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
127 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
128 * Pruned nodes may have entries where B is missing data.
130 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
132 CCriticalSection cs_LastBlockFile;
133 std::vector<CBlockFileInfo> vinfoBlockFile;
134 int nLastBlockFile = 0;
135 /** Global flag to indicate we should check to see if there are
136 * block/undo files that should be deleted. Set on startup
137 * or if we allocate more file space when we're in prune mode
139 bool fCheckForPruning = false;
142 * Every received block is assigned a unique and increasing identifier, so we
143 * know which one to give priority in case of a fork.
145 CCriticalSection cs_nBlockSequenceId;
146 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
147 int32_t nBlockSequenceId = 1;
148 /** Decreasing counter (used by subsequent preciousblock calls). */
149 int32_t nBlockReverseSequenceId = -1;
150 /** chainwork for the last block that preciousblock has been applied to. */
151 arith_uint256 nLastPreciousChainwork = 0;
153 /** Dirty block index entries. */
154 std::set<CBlockIndex*> setDirtyBlockIndex;
156 /** Dirty block file entries. */
157 std::set<int> setDirtyFileInfo;
158 } // anon namespace
160 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
162 // Find the first block the caller has in the main chain
163 BOOST_FOREACH(const uint256& hash, locator.vHave) {
164 BlockMap::iterator mi = mapBlockIndex.find(hash);
165 if (mi != mapBlockIndex.end())
167 CBlockIndex* pindex = (*mi).second;
168 if (chain.Contains(pindex))
169 return pindex;
170 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
171 return chain.Tip();
175 return chain.Genesis();
178 CCoinsViewCache *pcoinsTip = NULL;
179 CBlockTreeDB *pblocktree = NULL;
181 enum FlushStateMode {
182 FLUSH_STATE_NONE,
183 FLUSH_STATE_IF_NEEDED,
184 FLUSH_STATE_PERIODIC,
185 FLUSH_STATE_ALWAYS
188 // See definition for documentation
189 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
190 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
192 bool CheckFinalTx(const CTransaction &tx, int flags)
194 AssertLockHeld(cs_main);
196 // By convention a negative value for flags indicates that the
197 // current network-enforced consensus rules should be used. In
198 // a future soft-fork scenario that would mean checking which
199 // rules would be enforced for the next block and setting the
200 // appropriate flags. At the present time no soft-forks are
201 // scheduled, so no flags are set.
202 flags = std::max(flags, 0);
204 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
205 // nLockTime because when IsFinalTx() is called within
206 // CBlock::AcceptBlock(), the height of the block *being*
207 // evaluated is what is used. Thus if we want to know if a
208 // transaction can be part of the *next* block, we need to call
209 // IsFinalTx() with one more than chainActive.Height().
210 const int nBlockHeight = chainActive.Height() + 1;
212 // BIP113 will require that time-locked transactions have nLockTime set to
213 // less than the median time of the previous block they're contained in.
214 // When the next block is created its previous block will be the current
215 // chain tip, so we use that to calculate the median time passed to
216 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
217 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
218 ? chainActive.Tip()->GetMedianTimePast()
219 : GetAdjustedTime();
221 return IsFinalTx(tx, nBlockHeight, nBlockTime);
224 bool TestLockPointValidity(const LockPoints* lp)
226 AssertLockHeld(cs_main);
227 assert(lp);
228 // If there are relative lock times then the maxInputBlock will be set
229 // If there are no relative lock times, the LockPoints don't depend on the chain
230 if (lp->maxInputBlock) {
231 // Check whether chainActive is an extension of the block at which the LockPoints
232 // calculation was valid. If not LockPoints are no longer valid
233 if (!chainActive.Contains(lp->maxInputBlock)) {
234 return false;
238 // LockPoints still valid
239 return true;
242 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
244 AssertLockHeld(cs_main);
245 AssertLockHeld(mempool.cs);
247 CBlockIndex* tip = chainActive.Tip();
248 CBlockIndex index;
249 index.pprev = tip;
250 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
251 // height based locks because when SequenceLocks() is called within
252 // ConnectBlock(), the height of the block *being*
253 // evaluated is what is used.
254 // Thus if we want to know if a transaction can be part of the
255 // *next* block, we need to use one more than chainActive.Height()
256 index.nHeight = tip->nHeight + 1;
258 std::pair<int, int64_t> lockPair;
259 if (useExistingLockPoints) {
260 assert(lp);
261 lockPair.first = lp->height;
262 lockPair.second = lp->time;
264 else {
265 // pcoinsTip contains the UTXO set for chainActive.Tip()
266 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
267 std::vector<int> prevheights;
268 prevheights.resize(tx.vin.size());
269 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
270 const CTxIn& txin = tx.vin[txinIndex];
271 CCoins coins;
272 if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
273 return error("%s: Missing input", __func__);
275 if (coins.nHeight == MEMPOOL_HEIGHT) {
276 // Assume all mempool transaction confirm in the next block
277 prevheights[txinIndex] = tip->nHeight + 1;
278 } else {
279 prevheights[txinIndex] = coins.nHeight;
282 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
283 if (lp) {
284 lp->height = lockPair.first;
285 lp->time = lockPair.second;
286 // Also store the hash of the block with the highest height of
287 // all the blocks which have sequence locked prevouts.
288 // This hash needs to still be on the chain
289 // for these LockPoint calculations to be valid
290 // Note: It is impossible to correctly calculate a maxInputBlock
291 // if any of the sequence locked inputs depend on unconfirmed txs,
292 // except in the special case where the relative lock time/height
293 // is 0, which is equivalent to no sequence lock. Since we assume
294 // input height of tip+1 for mempool txs and test the resulting
295 // lockPair from CalculateSequenceLocks against tip+1. We know
296 // EvaluateSequenceLocks will fail if there was a non-zero sequence
297 // lock on a mempool input, so we can use the return value of
298 // CheckSequenceLocks to indicate the LockPoints validity
299 int maxInputHeight = 0;
300 BOOST_FOREACH(int height, prevheights) {
301 // Can ignore mempool inputs since we'll fail if they had non-zero locks
302 if (height != tip->nHeight+1) {
303 maxInputHeight = std::max(maxInputHeight, height);
306 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
309 return EvaluateSequenceLocks(index, lockPair);
313 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
314 int expired = pool.Expire(GetTime() - age);
315 if (expired != 0) {
316 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
319 std::vector<uint256> vNoSpendsRemaining;
320 pool.TrimToSize(limit, &vNoSpendsRemaining);
321 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
322 pcoinsTip->Uncache(removed);
325 /** Convert CValidationState to a human-readable message for logging */
326 std::string FormatStateMessage(const CValidationState &state)
328 return strprintf("%s%s (code %i)",
329 state.GetRejectReason(),
330 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
331 state.GetRejectCode());
334 static bool IsCurrentForFeeEstimation()
336 AssertLockHeld(cs_main);
337 if (IsInitialBlockDownload())
338 return false;
339 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
340 return false;
341 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
342 return false;
343 return true;
346 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
347 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
348 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
350 const CTransaction& tx = *ptx;
351 const uint256 hash = tx.GetHash();
352 AssertLockHeld(cs_main);
353 if (pfMissingInputs)
354 *pfMissingInputs = false;
356 if (!CheckTransaction(tx, state))
357 return false; // state filled in by CheckTransaction
359 // Coinbase is only valid in a block, not as a loose transaction
360 if (tx.IsCoinBase())
361 return state.DoS(100, false, REJECT_INVALID, "coinbase");
363 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
364 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus());
365 if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
366 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
369 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
370 std::string reason;
371 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
372 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
374 // Only accept nLockTime-using transactions that can be mined in the next
375 // block; we don't want our mempool filled up with transactions that can't
376 // be mined yet.
377 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
378 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
380 // is it already in the memory pool?
381 if (pool.exists(hash))
382 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
384 // Check for conflicts with in-memory transactions
385 std::set<uint256> setConflicts;
387 LOCK(pool.cs); // protect pool.mapNextTx
388 BOOST_FOREACH(const CTxIn &txin, tx.vin)
390 auto itConflicting = pool.mapNextTx.find(txin.prevout);
391 if (itConflicting != pool.mapNextTx.end())
393 const CTransaction *ptxConflicting = itConflicting->second;
394 if (!setConflicts.count(ptxConflicting->GetHash()))
396 // Allow opt-out of transaction replacement by setting
397 // nSequence >= maxint-1 on all inputs.
399 // maxint-1 is picked to still allow use of nLockTime by
400 // non-replaceable transactions. All inputs rather than just one
401 // is for the sake of multi-party protocols, where we don't
402 // want a single party to be able to disable replacement.
404 // The opt-out ignores descendants as anyone relying on
405 // first-seen mempool behavior should be checking all
406 // unconfirmed ancestors anyway; doing otherwise is hopelessly
407 // insecure.
408 bool fReplacementOptOut = true;
409 if (fEnableReplacement)
411 BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
413 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
415 fReplacementOptOut = false;
416 break;
420 if (fReplacementOptOut)
421 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
423 setConflicts.insert(ptxConflicting->GetHash());
430 CCoinsView dummy;
431 CCoinsViewCache view(&dummy);
433 CAmount nValueIn = 0;
434 LockPoints lp;
436 LOCK(pool.cs);
437 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
438 view.SetBackend(viewMemPool);
440 // do we already have it?
441 bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
442 if (view.HaveCoins(hash)) {
443 if (!fHadTxInCache)
444 vHashTxnToUncache.push_back(hash);
445 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
448 // do all inputs exist?
449 // Note that this does not check for the presence of actual outputs (see the next check for that),
450 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
451 BOOST_FOREACH(const CTxIn txin, tx.vin) {
452 if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
453 vHashTxnToUncache.push_back(txin.prevout.hash);
454 if (!view.HaveCoins(txin.prevout.hash)) {
455 if (pfMissingInputs)
456 *pfMissingInputs = true;
457 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
461 // are the actual inputs available?
462 if (!view.HaveInputs(tx))
463 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
465 // Bring the best block into scope
466 view.GetBestBlock();
468 nValueIn = view.GetValueIn(tx);
470 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
471 view.SetBackend(dummy);
473 // Only accept BIP68 sequence locked transactions that can be mined in the next
474 // block; we don't want our mempool filled up with transactions that can't
475 // be mined yet.
476 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
477 // CoinsViewCache instead of create its own
478 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
479 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
482 // Check for non-standard pay-to-script-hash in inputs
483 if (fRequireStandard && !AreInputsStandard(tx, view))
484 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
486 // Check for non-standard witness in P2WSH
487 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
488 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
490 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
492 CAmount nValueOut = tx.GetValueOut();
493 CAmount nFees = nValueIn-nValueOut;
494 // nModifiedFees includes any fee deltas from PrioritiseTransaction
495 CAmount nModifiedFees = nFees;
496 pool.ApplyDelta(hash, nModifiedFees);
498 // Keep track of transactions that spend a coinbase, which we re-scan
499 // during reorgs to ensure COINBASE_MATURITY is still met.
500 bool fSpendsCoinbase = false;
501 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
502 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
503 if (coins->IsCoinBase()) {
504 fSpendsCoinbase = true;
505 break;
509 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
510 fSpendsCoinbase, nSigOpsCost, lp);
511 unsigned int nSize = entry.GetTxSize();
513 // Check that the transaction doesn't have an excessive number of
514 // sigops, making it impossible to mine. Since the coinbase transaction
515 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
516 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
517 // merely non-standard transaction.
518 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
519 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
520 strprintf("%d", nSigOpsCost));
522 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
523 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
524 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
527 // No transactions are allowed below minRelayTxFee except from disconnected blocks
528 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
529 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
532 if (nAbsurdFee && nFees > nAbsurdFee)
533 return state.Invalid(false,
534 REJECT_HIGHFEE, "absurdly-high-fee",
535 strprintf("%d > %d", nFees, nAbsurdFee));
537 // Calculate in-mempool ancestors, up to a limit.
538 CTxMemPool::setEntries setAncestors;
539 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
540 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
541 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
542 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
543 std::string errString;
544 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
545 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
548 // A transaction that spends outputs that would be replaced by it is invalid. Now
549 // that we have the set of all ancestors we can detect this
550 // pathological case by making sure setConflicts and setAncestors don't
551 // intersect.
552 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
554 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
555 if (setConflicts.count(hashAncestor))
557 return state.DoS(10, false,
558 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
559 strprintf("%s spends conflicting transaction %s",
560 hash.ToString(),
561 hashAncestor.ToString()));
565 // Check if it's economically rational to mine this transaction rather
566 // than the ones it replaces.
567 CAmount nConflictingFees = 0;
568 size_t nConflictingSize = 0;
569 uint64_t nConflictingCount = 0;
570 CTxMemPool::setEntries allConflicting;
572 // If we don't hold the lock allConflicting might be incomplete; the
573 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
574 // mempool consistency for us.
575 LOCK(pool.cs);
576 const bool fReplacementTransaction = setConflicts.size();
577 if (fReplacementTransaction)
579 CFeeRate newFeeRate(nModifiedFees, nSize);
580 std::set<uint256> setConflictsParents;
581 const int maxDescendantsToVisit = 100;
582 CTxMemPool::setEntries setIterConflicting;
583 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
585 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
586 if (mi == pool.mapTx.end())
587 continue;
589 // Save these to avoid repeated lookups
590 setIterConflicting.insert(mi);
592 // Don't allow the replacement to reduce the feerate of the
593 // mempool.
595 // We usually don't want to accept replacements with lower
596 // feerates than what they replaced as that would lower the
597 // feerate of the next block. Requiring that the feerate always
598 // be increased is also an easy-to-reason about way to prevent
599 // DoS attacks via replacements.
601 // The mining code doesn't (currently) take children into
602 // account (CPFP) so we only consider the feerates of
603 // transactions being directly replaced, not their indirect
604 // descendants. While that does mean high feerate children are
605 // ignored when deciding whether or not to replace, we do
606 // require the replacement to pay more overall fees too,
607 // mitigating most cases.
608 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
609 if (newFeeRate <= oldFeeRate)
611 return state.DoS(0, false,
612 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
613 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
614 hash.ToString(),
615 newFeeRate.ToString(),
616 oldFeeRate.ToString()));
619 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
621 setConflictsParents.insert(txin.prevout.hash);
624 nConflictingCount += mi->GetCountWithDescendants();
626 // This potentially overestimates the number of actual descendants
627 // but we just want to be conservative to avoid doing too much
628 // work.
629 if (nConflictingCount <= maxDescendantsToVisit) {
630 // If not too many to replace, then calculate the set of
631 // transactions that would have to be evicted
632 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
633 pool.CalculateDescendants(it, allConflicting);
635 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
636 nConflictingFees += it->GetModifiedFee();
637 nConflictingSize += it->GetTxSize();
639 } else {
640 return state.DoS(0, false,
641 REJECT_NONSTANDARD, "too many potential replacements", false,
642 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
643 hash.ToString(),
644 nConflictingCount,
645 maxDescendantsToVisit));
648 for (unsigned int j = 0; j < tx.vin.size(); j++)
650 // We don't want to accept replacements that require low
651 // feerate junk to be mined first. Ideally we'd keep track of
652 // the ancestor feerates and make the decision based on that,
653 // but for now requiring all new inputs to be confirmed works.
654 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
656 // Rather than check the UTXO set - potentially expensive -
657 // it's cheaper to just check if the new input refers to a
658 // tx that's in the mempool.
659 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
660 return state.DoS(0, false,
661 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
662 strprintf("replacement %s adds unconfirmed input, idx %d",
663 hash.ToString(), j));
667 // The replacement must pay greater fees than the transactions it
668 // replaces - if we did the bandwidth used by those conflicting
669 // transactions would not be paid for.
670 if (nModifiedFees < nConflictingFees)
672 return state.DoS(0, false,
673 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
674 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
675 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
678 // Finally in addition to paying more fees than the conflicts the
679 // new transaction must pay for its own bandwidth.
680 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
681 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
683 return state.DoS(0, false,
684 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
685 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
686 hash.ToString(),
687 FormatMoney(nDeltaFees),
688 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
692 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
693 if (!Params().RequireStandard()) {
694 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
697 // Check against previous transactions
698 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
699 PrecomputedTransactionData txdata(tx);
700 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
701 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
702 // need to turn both off, and compare against just turning off CLEANSTACK
703 // to see if the failure is specifically due to witness validation.
704 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
705 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
706 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
707 // Only the witness is missing, so the transaction itself may be fine.
708 state.SetCorruptionPossible();
710 return false; // state filled in by CheckInputs
713 // Check again against just the consensus-critical mandatory script
714 // verification flags, in case of bugs in the standard flags that cause
715 // transactions to pass as valid when they're actually invalid. For
716 // instance the STRICTENC flag was incorrectly allowing certain
717 // CHECKSIG NOT scripts to pass, even though they were invalid.
719 // There is a similar check in CreateNewBlock() to prevent creating
720 // invalid blocks, however allowing such transactions into the mempool
721 // can be exploited as a DoS attack.
722 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
724 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
725 __func__, hash.ToString(), FormatStateMessage(state));
728 // Remove conflicting transactions from the mempool
729 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
731 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
732 it->GetTx().GetHash().ToString(),
733 hash.ToString(),
734 FormatMoney(nModifiedFees - nConflictingFees),
735 (int)nSize - (int)nConflictingSize);
736 if (plTxnReplaced)
737 plTxnReplaced->push_back(it->GetSharedTx());
739 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
741 // This transaction should only count for fee estimation if it isn't a
742 // BIP 125 replacement transaction (may not be widely supported), the
743 // node is not behind, and the transaction is not dependent on any other
744 // transactions in the mempool.
745 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
747 // Store transaction in memory
748 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
750 // trim mempool and check if tx was trimmed
751 if (!fOverrideMempoolLimit) {
752 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
753 if (!pool.exists(hash))
754 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
758 GetMainSignals().TransactionAddedToMempool(ptx);
760 return true;
763 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
764 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
765 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
767 std::vector<uint256> vHashTxToUncache;
768 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
769 if (!res) {
770 BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
771 pcoinsTip->Uncache(hashTx);
773 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
774 CValidationState stateDummy;
775 FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
776 return res;
779 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
780 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
781 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
783 return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
786 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
787 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
789 CBlockIndex *pindexSlow = NULL;
791 LOCK(cs_main);
793 CTransactionRef ptx = mempool.get(hash);
794 if (ptx)
796 txOut = ptx;
797 return true;
800 if (fTxIndex) {
801 CDiskTxPos postx;
802 if (pblocktree->ReadTxIndex(hash, postx)) {
803 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
804 if (file.IsNull())
805 return error("%s: OpenBlockFile failed", __func__);
806 CBlockHeader header;
807 try {
808 file >> header;
809 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
810 file >> txOut;
811 } catch (const std::exception& e) {
812 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
814 hashBlock = header.GetHash();
815 if (txOut->GetHash() != hash)
816 return error("%s: txid mismatch", __func__);
817 return true;
821 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
822 int nHeight = -1;
824 const CCoinsViewCache& view = *pcoinsTip;
825 const CCoins* coins = view.AccessCoins(hash);
826 if (coins)
827 nHeight = coins->nHeight;
829 if (nHeight > 0)
830 pindexSlow = chainActive[nHeight];
833 if (pindexSlow) {
834 CBlock block;
835 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
836 for (const auto& tx : block.vtx) {
837 if (tx->GetHash() == hash) {
838 txOut = tx;
839 hashBlock = pindexSlow->GetBlockHash();
840 return true;
846 return false;
854 //////////////////////////////////////////////////////////////////////////////
856 // CBlock and CBlockIndex
859 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
861 // Open history file to append
862 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
863 if (fileout.IsNull())
864 return error("WriteBlockToDisk: OpenBlockFile failed");
866 // Write index header
867 unsigned int nSize = GetSerializeSize(fileout, block);
868 fileout << FLATDATA(messageStart) << nSize;
870 // Write block
871 long fileOutPos = ftell(fileout.Get());
872 if (fileOutPos < 0)
873 return error("WriteBlockToDisk: ftell failed");
874 pos.nPos = (unsigned int)fileOutPos;
875 fileout << block;
877 return true;
880 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
882 block.SetNull();
884 // Open history file to read
885 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
886 if (filein.IsNull())
887 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
889 // Read block
890 try {
891 filein >> block;
893 catch (const std::exception& e) {
894 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
897 // Check the header
898 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
899 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
901 return true;
904 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
906 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
907 return false;
908 if (block.GetHash() != pindex->GetBlockHash())
909 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
910 pindex->ToString(), pindex->GetBlockPos().ToString());
911 return true;
914 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
916 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
917 // Force block reward to zero when right shift is undefined.
918 if (halvings >= 64)
919 return 0;
921 CAmount nSubsidy = 50 * COIN;
922 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
923 nSubsidy >>= halvings;
924 return nSubsidy;
927 bool IsInitialBlockDownload()
929 const CChainParams& chainParams = Params();
931 // Once this function has returned false, it must remain false.
932 static std::atomic<bool> latchToFalse{false};
933 // Optimization: pre-test latch before taking the lock.
934 if (latchToFalse.load(std::memory_order_relaxed))
935 return false;
937 LOCK(cs_main);
938 if (latchToFalse.load(std::memory_order_relaxed))
939 return false;
940 if (fImporting || fReindex)
941 return true;
942 if (chainActive.Tip() == NULL)
943 return true;
944 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
945 return true;
946 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
947 return true;
948 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
949 latchToFalse.store(true, std::memory_order_relaxed);
950 return false;
953 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
955 static void AlertNotify(const std::string& strMessage)
957 uiInterface.NotifyAlertChanged();
958 std::string strCmd = GetArg("-alertnotify", "");
959 if (strCmd.empty()) return;
961 // Alert text should be plain ascii coming from a trusted source, but to
962 // be safe we first strip anything not in safeChars, then add single quotes around
963 // the whole string before passing it to the shell:
964 std::string singleQuote("'");
965 std::string safeStatus = SanitizeString(strMessage);
966 safeStatus = singleQuote+safeStatus+singleQuote;
967 boost::replace_all(strCmd, "%s", safeStatus);
969 boost::thread t(runCommand, strCmd); // thread runs free
972 void CheckForkWarningConditions()
974 AssertLockHeld(cs_main);
975 // Before we get past initial download, we cannot reliably alert about forks
976 // (we assume we don't get stuck on a fork before finishing our initial sync)
977 if (IsInitialBlockDownload())
978 return;
980 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
981 // of our head, drop it
982 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
983 pindexBestForkTip = NULL;
985 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
987 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
989 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
990 pindexBestForkBase->phashBlock->ToString() + std::string("'");
991 AlertNotify(warning);
993 if (pindexBestForkTip && pindexBestForkBase)
995 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__,
996 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
997 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
998 SetfLargeWorkForkFound(true);
1000 else
1002 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1003 SetfLargeWorkInvalidChainFound(true);
1006 else
1008 SetfLargeWorkForkFound(false);
1009 SetfLargeWorkInvalidChainFound(false);
1013 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1015 AssertLockHeld(cs_main);
1016 // If we are on a fork that is sufficiently large, set a warning flag
1017 CBlockIndex* pfork = pindexNewForkTip;
1018 CBlockIndex* plonger = chainActive.Tip();
1019 while (pfork && pfork != plonger)
1021 while (plonger && plonger->nHeight > pfork->nHeight)
1022 plonger = plonger->pprev;
1023 if (pfork == plonger)
1024 break;
1025 pfork = pfork->pprev;
1028 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1029 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1030 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1031 // hash rate operating on the fork.
1032 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1033 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1034 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1035 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1036 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1037 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1039 pindexBestForkTip = pindexNewForkTip;
1040 pindexBestForkBase = pfork;
1043 CheckForkWarningConditions();
1046 void static InvalidChainFound(CBlockIndex* pindexNew)
1048 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1049 pindexBestInvalid = pindexNew;
1051 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1052 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1053 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1054 pindexNew->GetBlockTime()));
1055 CBlockIndex *tip = chainActive.Tip();
1056 assert (tip);
1057 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1058 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1059 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1060 CheckForkWarningConditions();
1063 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1064 if (!state.CorruptionPossible()) {
1065 pindex->nStatus |= BLOCK_FAILED_VALID;
1066 setDirtyBlockIndex.insert(pindex);
1067 setBlockIndexCandidates.erase(pindex);
1068 InvalidChainFound(pindex);
1072 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1074 // mark inputs spent
1075 if (!tx.IsCoinBase()) {
1076 txundo.vprevout.reserve(tx.vin.size());
1077 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1078 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1079 unsigned nPos = txin.prevout.n;
1081 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1082 assert(false);
1083 // mark an outpoint spent, and construct undo information
1084 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1085 coins->Spend(nPos);
1086 if (coins->vout.size() == 0) {
1087 CTxInUndo& undo = txundo.vprevout.back();
1088 undo.nHeight = coins->nHeight;
1089 undo.fCoinBase = coins->fCoinBase;
1090 undo.nVersion = coins->nVersion;
1094 // add outputs
1095 inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1098 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1100 CTxUndo txundo;
1101 UpdateCoins(tx, inputs, txundo, nHeight);
1104 bool CScriptCheck::operator()() {
1105 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1106 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1107 return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1110 int GetSpendHeight(const CCoinsViewCache& inputs)
1112 LOCK(cs_main);
1113 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1114 return pindexPrev->nHeight + 1;
1117 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1119 if (!tx.IsCoinBase())
1121 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1122 return false;
1124 if (pvChecks)
1125 pvChecks->reserve(tx.vin.size());
1127 // The first loop above does all the inexpensive checks.
1128 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1129 // Helps prevent CPU exhaustion attacks.
1131 // Skip script verification when connecting blocks under the
1132 // assumevalid block. Assuming the assumevalid block is valid this
1133 // is safe because block merkle hashes are still computed and checked,
1134 // Of course, if an assumed valid block is invalid due to false scriptSigs
1135 // this optimization would allow an invalid chain to be accepted.
1136 if (fScriptChecks) {
1137 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1138 const COutPoint &prevout = tx.vin[i].prevout;
1139 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1140 assert(coins);
1142 // Verify signature
1143 CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1144 if (pvChecks) {
1145 pvChecks->push_back(CScriptCheck());
1146 check.swap(pvChecks->back());
1147 } else if (!check()) {
1148 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1149 // Check whether the failure was caused by a
1150 // non-mandatory script verification check, such as
1151 // non-standard DER encodings or non-null dummy
1152 // arguments; if so, don't trigger DoS protection to
1153 // avoid splitting the network between upgraded and
1154 // non-upgraded nodes.
1155 CScriptCheck check2(*coins, tx, i,
1156 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1157 if (check2())
1158 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1160 // Failures of other flags indicate a transaction that is
1161 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1162 // such nodes as they are not following the protocol. That
1163 // said during an upgrade careful thought should be taken
1164 // as to the correct behavior - we may want to continue
1165 // peering with non-upgraded nodes even after soft-fork
1166 // super-majority signaling has occurred.
1167 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1173 return true;
1176 namespace {
1178 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1180 // Open history file to append
1181 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1182 if (fileout.IsNull())
1183 return error("%s: OpenUndoFile failed", __func__);
1185 // Write index header
1186 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1187 fileout << FLATDATA(messageStart) << nSize;
1189 // Write undo data
1190 long fileOutPos = ftell(fileout.Get());
1191 if (fileOutPos < 0)
1192 return error("%s: ftell failed", __func__);
1193 pos.nPos = (unsigned int)fileOutPos;
1194 fileout << blockundo;
1196 // calculate & write checksum
1197 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1198 hasher << hashBlock;
1199 hasher << blockundo;
1200 fileout << hasher.GetHash();
1202 return true;
1205 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1207 // Open history file to read
1208 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1209 if (filein.IsNull())
1210 return error("%s: OpenUndoFile failed", __func__);
1212 // Read block
1213 uint256 hashChecksum;
1214 try {
1215 filein >> blockundo;
1216 filein >> hashChecksum;
1218 catch (const std::exception& e) {
1219 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1222 // Verify checksum
1223 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1224 hasher << hashBlock;
1225 hasher << blockundo;
1226 if (hashChecksum != hasher.GetHash())
1227 return error("%s: Checksum mismatch", __func__);
1229 return true;
1232 /** Abort with a message */
1233 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1235 SetMiscWarning(strMessage);
1236 LogPrintf("*** %s\n", strMessage);
1237 uiInterface.ThreadSafeMessageBox(
1238 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1239 "", CClientUIInterface::MSG_ERROR);
1240 StartShutdown();
1241 return false;
1244 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1246 AbortNode(strMessage, userMessage);
1247 return state.Error(strMessage);
1250 } // anon namespace
1253 * Apply the undo operation of a CTxInUndo to the given chain state.
1254 * @param undo The undo object.
1255 * @param view The coins view to which to apply the changes.
1256 * @param out The out point that corresponds to the tx input.
1257 * @return True on success.
1259 bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1261 bool fClean = true;
1263 CCoinsModifier coins = view.ModifyCoins(out.hash);
1264 if (undo.nHeight != 0) {
1265 // undo data contains height: this is the last output of the prevout tx being spent
1266 if (!coins->IsPruned())
1267 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1268 coins->Clear();
1269 coins->fCoinBase = undo.fCoinBase;
1270 coins->nHeight = undo.nHeight;
1271 coins->nVersion = undo.nVersion;
1272 } else {
1273 if (coins->IsPruned())
1274 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1276 if (coins->IsAvailable(out.n))
1277 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1278 if (coins->vout.size() < out.n+1)
1279 coins->vout.resize(out.n+1);
1280 coins->vout[out.n] = undo.txout;
1282 return fClean;
1285 enum DisconnectResult
1287 DISCONNECT_OK, // All good.
1288 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1289 DISCONNECT_FAILED // Something else went wrong.
1292 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1293 * When UNCLEAN or FAILED is returned, view is left in an indeterminate state. */
1294 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1296 assert(pindex->GetBlockHash() == view.GetBestBlock());
1298 bool fClean = true;
1300 CBlockUndo blockUndo;
1301 CDiskBlockPos pos = pindex->GetUndoPos();
1302 if (pos.IsNull()) {
1303 error("DisconnectBlock(): no undo data available");
1304 return DISCONNECT_FAILED;
1306 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1307 error("DisconnectBlock(): failure reading undo data");
1308 return DISCONNECT_FAILED;
1311 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1312 error("DisconnectBlock(): block and undo data inconsistent");
1313 return DISCONNECT_FAILED;
1316 // undo transactions in reverse order
1317 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1318 const CTransaction &tx = *(block.vtx[i]);
1319 uint256 hash = tx.GetHash();
1321 // Check that all outputs are available and match the outputs in the block itself
1322 // exactly.
1324 CCoinsModifier outs = view.ModifyCoins(hash);
1325 outs->ClearUnspendable();
1327 CCoins outsBlock(tx, pindex->nHeight);
1328 // The CCoins serialization does not serialize negative numbers.
1329 // No network rules currently depend on the version here, so an inconsistency is harmless
1330 // but it must be corrected before txout nversion ever influences a network rule.
1331 if (outsBlock.nVersion < 0)
1332 outs->nVersion = outsBlock.nVersion;
1333 if (*outs != outsBlock)
1334 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1336 // remove outputs
1337 outs->Clear();
1340 // restore inputs
1341 if (i > 0) { // not coinbases
1342 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1343 if (txundo.vprevout.size() != tx.vin.size()) {
1344 error("DisconnectBlock(): transaction and undo data inconsistent");
1345 return DISCONNECT_FAILED;
1347 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1348 const COutPoint &out = tx.vin[j].prevout;
1349 const CTxInUndo &undo = txundo.vprevout[j];
1350 if (!ApplyTxInUndo(undo, view, out))
1351 fClean = false;
1356 // move best block pointer to prevout block
1357 view.SetBestBlock(pindex->pprev->GetBlockHash());
1359 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1362 void static FlushBlockFile(bool fFinalize = false)
1364 LOCK(cs_LastBlockFile);
1366 CDiskBlockPos posOld(nLastBlockFile, 0);
1368 FILE *fileOld = OpenBlockFile(posOld);
1369 if (fileOld) {
1370 if (fFinalize)
1371 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1372 FileCommit(fileOld);
1373 fclose(fileOld);
1376 fileOld = OpenUndoFile(posOld);
1377 if (fileOld) {
1378 if (fFinalize)
1379 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1380 FileCommit(fileOld);
1381 fclose(fileOld);
1385 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1387 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1389 void ThreadScriptCheck() {
1390 RenameThread("bitcoin-scriptch");
1391 scriptcheckqueue.Thread();
1394 // Protected by cs_main
1395 VersionBitsCache versionbitscache;
1397 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1399 LOCK(cs_main);
1400 int32_t nVersion = VERSIONBITS_TOP_BITS;
1402 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1403 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1404 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1405 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1409 return nVersion;
1413 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1415 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1417 private:
1418 int bit;
1420 public:
1421 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1423 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1424 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1425 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1426 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1428 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1430 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1431 ((pindex->nVersion >> bit) & 1) != 0 &&
1432 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1436 // Protected by cs_main
1437 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1439 static int64_t nTimeCheck = 0;
1440 static int64_t nTimeForks = 0;
1441 static int64_t nTimeVerify = 0;
1442 static int64_t nTimeConnect = 0;
1443 static int64_t nTimeIndex = 0;
1444 static int64_t nTimeCallbacks = 0;
1445 static int64_t nTimeTotal = 0;
1447 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1448 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1449 * can fail if those validity checks fail (among other reasons). */
1450 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1451 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1453 AssertLockHeld(cs_main);
1454 assert(pindex);
1455 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1456 assert((pindex->phashBlock == NULL) ||
1457 (*pindex->phashBlock == block.GetHash()));
1458 int64_t nTimeStart = GetTimeMicros();
1460 // Check it again in case a previous version let a bad block in
1461 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1462 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1464 // verify that the view's current state corresponds to the previous block
1465 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1466 assert(hashPrevBlock == view.GetBestBlock());
1468 // Special case for the genesis block, skipping connection of its transactions
1469 // (its coinbase is unspendable)
1470 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1471 if (!fJustCheck)
1472 view.SetBestBlock(pindex->GetBlockHash());
1473 return true;
1476 bool fScriptChecks = true;
1477 if (!hashAssumeValid.IsNull()) {
1478 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1479 // A suitable default value is included with the software and updated from time to time. Because validity
1480 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1481 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1482 // effectively caching the result of part of the verification.
1483 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1484 if (it != mapBlockIndex.end()) {
1485 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1486 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1487 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1488 // This block is a member of the assumed verified chain and an ancestor of the best header.
1489 // The equivalent time check discourages hash power from extorting the network via DOS attack
1490 // into accepting an invalid block through telling users they must manually set assumevalid.
1491 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1492 // it hard to hide the implication of the demand. This also avoids having release candidates
1493 // that are hardly doing any signature verification at all in testing without having to
1494 // artificially set the default assumed verified block further back.
1495 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1496 // least as good as the expected chain.
1497 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1502 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1503 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1505 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1506 // unless those are already completely spent.
1507 // If such overwrites are allowed, coinbases and transactions depending upon those
1508 // can be duplicated to remove the ability to spend the first instance -- even after
1509 // being sent to another address.
1510 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1511 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1512 // already refuses previously-known transaction ids entirely.
1513 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1514 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1515 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1516 // initial block download.
1517 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1518 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1519 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1521 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1522 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1523 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1524 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1525 // duplicate transactions descending from the known pairs either.
1526 // 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.
1527 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1528 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1529 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1531 if (fEnforceBIP30) {
1532 for (const auto& tx : block.vtx) {
1533 const CCoins* coins = view.AccessCoins(tx->GetHash());
1534 if (coins && !coins->IsPruned())
1535 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1536 REJECT_INVALID, "bad-txns-BIP30");
1540 // BIP16 didn't become active until Apr 1 2012
1541 int64_t nBIP16SwitchTime = 1333238400;
1542 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1544 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1546 // Start enforcing the DERSIG (BIP66) rule
1547 if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
1548 flags |= SCRIPT_VERIFY_DERSIG;
1551 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1552 if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
1553 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1556 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1557 int nLockTimeFlags = 0;
1558 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1559 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1560 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1563 // Start enforcing WITNESS rules using versionbits logic.
1564 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) {
1565 flags |= SCRIPT_VERIFY_WITNESS;
1566 flags |= SCRIPT_VERIFY_NULLDUMMY;
1569 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1570 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1572 CBlockUndo blockundo;
1574 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1576 std::vector<int> prevheights;
1577 CAmount nFees = 0;
1578 int nInputs = 0;
1579 int64_t nSigOpsCost = 0;
1580 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1581 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1582 vPos.reserve(block.vtx.size());
1583 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1584 std::vector<PrecomputedTransactionData> txdata;
1585 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1586 for (unsigned int i = 0; i < block.vtx.size(); i++)
1588 const CTransaction &tx = *(block.vtx[i]);
1590 nInputs += tx.vin.size();
1592 if (!tx.IsCoinBase())
1594 if (!view.HaveInputs(tx))
1595 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1596 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1598 // Check that transaction is BIP68 final
1599 // BIP68 lock checks (as opposed to nLockTime checks) must
1600 // be in ConnectBlock because they require the UTXO set
1601 prevheights.resize(tx.vin.size());
1602 for (size_t j = 0; j < tx.vin.size(); j++) {
1603 prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
1606 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1607 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1608 REJECT_INVALID, "bad-txns-nonfinal");
1612 // GetTransactionSigOpCost counts 3 types of sigops:
1613 // * legacy (always)
1614 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1615 // * witness (when witness enabled in flags and excludes coinbase)
1616 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1617 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1618 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1619 REJECT_INVALID, "bad-blk-sigops");
1621 txdata.emplace_back(tx);
1622 if (!tx.IsCoinBase())
1624 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1626 std::vector<CScriptCheck> vChecks;
1627 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1628 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1629 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1630 tx.GetHash().ToString(), FormatStateMessage(state));
1631 control.Add(vChecks);
1634 CTxUndo undoDummy;
1635 if (i > 0) {
1636 blockundo.vtxundo.push_back(CTxUndo());
1638 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1640 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1641 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1643 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1644 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
1646 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1647 if (block.vtx[0]->GetValueOut() > blockReward)
1648 return state.DoS(100,
1649 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1650 block.vtx[0]->GetValueOut(), blockReward),
1651 REJECT_INVALID, "bad-cb-amount");
1653 if (!control.Wait())
1654 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1655 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1656 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
1658 if (fJustCheck)
1659 return true;
1661 // Write undo information to disk
1662 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1664 if (pindex->GetUndoPos().IsNull()) {
1665 CDiskBlockPos _pos;
1666 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1667 return error("ConnectBlock(): FindUndoPos failed");
1668 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1669 return AbortNode(state, "Failed to write undo data");
1671 // update nUndoPos in block index
1672 pindex->nUndoPos = _pos.nPos;
1673 pindex->nStatus |= BLOCK_HAVE_UNDO;
1676 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1677 setDirtyBlockIndex.insert(pindex);
1680 if (fTxIndex)
1681 if (!pblocktree->WriteTxIndex(vPos))
1682 return AbortNode(state, "Failed to write transaction index");
1684 // add this block to the view's block chain
1685 view.SetBestBlock(pindex->GetBlockHash());
1687 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1688 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1690 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1691 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1693 return true;
1697 * Update the on-disk chain state.
1698 * The caches and indexes are flushed depending on the mode we're called with
1699 * if they're too large, if it's been a while since the last write,
1700 * or always and in all cases if we're in prune mode and are deleting files.
1702 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1703 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1704 const CChainParams& chainparams = Params();
1705 LOCK2(cs_main, cs_LastBlockFile);
1706 static int64_t nLastWrite = 0;
1707 static int64_t nLastFlush = 0;
1708 static int64_t nLastSetChain = 0;
1709 std::set<int> setFilesToPrune;
1710 bool fFlushForPrune = false;
1711 try {
1712 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1713 if (nManualPruneHeight > 0) {
1714 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1715 } else {
1716 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1717 fCheckForPruning = false;
1719 if (!setFilesToPrune.empty()) {
1720 fFlushForPrune = true;
1721 if (!fHavePruned) {
1722 pblocktree->WriteFlag("prunedblockfiles", true);
1723 fHavePruned = true;
1727 int64_t nNow = GetTimeMicros();
1728 // Avoid writing/flushing immediately after startup.
1729 if (nLastWrite == 0) {
1730 nLastWrite = nNow;
1732 if (nLastFlush == 0) {
1733 nLastFlush = nNow;
1735 if (nLastSetChain == 0) {
1736 nLastSetChain = nNow;
1738 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1739 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
1740 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1741 // The cache is large and we're within 10% and 200 MiB or 50% and 50MiB of the limit, but we have time now (not in the middle of a block processing).
1742 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::min(std::max(nTotalSpace / 2, nTotalSpace - MIN_BLOCK_COINSDB_USAGE * 1024 * 1024),
1743 std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024));
1744 // The cache is over the limit, we have to write now.
1745 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1746 // 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.
1747 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1748 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1749 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1750 // Combine all conditions that result in a full cache flush.
1751 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1752 // Write blocks and block index to disk.
1753 if (fDoFullFlush || fPeriodicWrite) {
1754 // Depend on nMinDiskSpace to ensure we can write block index
1755 if (!CheckDiskSpace(0))
1756 return state.Error("out of disk space");
1757 // First make sure all block and undo data is flushed to disk.
1758 FlushBlockFile();
1759 // Then update all block file information (which may refer to block and undo files).
1761 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1762 vFiles.reserve(setDirtyFileInfo.size());
1763 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1764 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1765 setDirtyFileInfo.erase(it++);
1767 std::vector<const CBlockIndex*> vBlocks;
1768 vBlocks.reserve(setDirtyBlockIndex.size());
1769 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1770 vBlocks.push_back(*it);
1771 setDirtyBlockIndex.erase(it++);
1773 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1774 return AbortNode(state, "Failed to write to block index database");
1777 // Finally remove any pruned files
1778 if (fFlushForPrune)
1779 UnlinkPrunedFiles(setFilesToPrune);
1780 nLastWrite = nNow;
1782 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1783 if (fDoFullFlush) {
1784 // Typical CCoins structures on disk are around 128 bytes in size.
1785 // Pushing a new one to the database can cause it to be written
1786 // twice (once in the log, and once in the tables). This is already
1787 // an overestimation, as most will delete an existing entry or
1788 // overwrite one. Still, use a conservative safety factor of 2.
1789 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
1790 return state.Error("out of disk space");
1791 // Flush the chainstate (which may refer to block index entries).
1792 if (!pcoinsTip->Flush())
1793 return AbortNode(state, "Failed to write to coin database");
1794 nLastFlush = nNow;
1796 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1797 // Update best block in wallet (so we can detect restored wallets).
1798 GetMainSignals().SetBestChain(chainActive.GetLocator());
1799 nLastSetChain = nNow;
1801 } catch (const std::runtime_error& e) {
1802 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1804 return true;
1807 void FlushStateToDisk() {
1808 CValidationState state;
1809 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1812 void PruneAndFlush() {
1813 CValidationState state;
1814 fCheckForPruning = true;
1815 FlushStateToDisk(state, FLUSH_STATE_NONE);
1818 /** Update chainActive and related internal data structures. */
1819 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
1820 chainActive.SetTip(pindexNew);
1822 // New best block
1823 mempool.AddTransactionsUpdated(1);
1825 cvBlockChange.notify_all();
1827 static bool fWarned = false;
1828 std::vector<std::string> warningMessages;
1829 if (!IsInitialBlockDownload())
1831 int nUpgraded = 0;
1832 const CBlockIndex* pindex = chainActive.Tip();
1833 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
1834 WarningBitsConditionChecker checker(bit);
1835 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
1836 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
1837 if (state == THRESHOLD_ACTIVE) {
1838 std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
1839 SetMiscWarning(strWarning);
1840 if (!fWarned) {
1841 AlertNotify(strWarning);
1842 fWarned = true;
1844 } else {
1845 warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
1849 // Check the version of the last 100 blocks to see if we need to upgrade:
1850 for (int i = 0; i < 100 && pindex != NULL; i++)
1852 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
1853 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
1854 ++nUpgraded;
1855 pindex = pindex->pprev;
1857 if (nUpgraded > 0)
1858 warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
1859 if (nUpgraded > 100/2)
1861 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
1862 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1863 SetMiscWarning(strWarning);
1864 if (!fWarned) {
1865 AlertNotify(strWarning);
1866 fWarned = true;
1870 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
1871 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
1872 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1873 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1874 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
1875 if (!warningMessages.empty())
1876 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
1877 LogPrintf("\n");
1881 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
1882 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
1884 CBlockIndex *pindexDelete = chainActive.Tip();
1885 assert(pindexDelete);
1886 // Read block from disk.
1887 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
1888 CBlock& block = *pblock;
1889 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
1890 return AbortNode(state, "Failed to read block");
1891 // Apply the block atomically to the chain state.
1892 int64_t nStart = GetTimeMicros();
1894 CCoinsViewCache view(pcoinsTip);
1895 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
1896 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
1897 bool flushed = view.Flush();
1898 assert(flushed);
1900 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1901 // Write the chain state to disk, if necessary.
1902 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
1903 return false;
1905 if (!fBare) {
1906 // Resurrect mempool transactions from the disconnected block.
1907 std::vector<uint256> vHashUpdate;
1908 for (const auto& it : block.vtx) {
1909 const CTransaction& tx = *it;
1910 // ignore validation errors in resurrected transactions
1911 CValidationState stateDummy;
1912 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
1913 mempool.removeRecursive(tx, MemPoolRemovalReason::REORG);
1914 } else if (mempool.exists(tx.GetHash())) {
1915 vHashUpdate.push_back(tx.GetHash());
1918 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
1919 // no in-mempool children, which is generally not true when adding
1920 // previously-confirmed transactions back to the mempool.
1921 // UpdateTransactionsFromBlock finds descendants of any transactions in this
1922 // block that were added back and cleans up the mempool state.
1923 mempool.UpdateTransactionsFromBlock(vHashUpdate);
1926 // Update chainActive and related variables.
1927 UpdateTip(pindexDelete->pprev, chainparams);
1928 // Let wallets know transactions went from 1-confirmed to
1929 // 0-confirmed or conflicted:
1930 GetMainSignals().BlockDisconnected(pblock);
1931 return true;
1934 static int64_t nTimeReadFromDisk = 0;
1935 static int64_t nTimeConnectTotal = 0;
1936 static int64_t nTimeFlush = 0;
1937 static int64_t nTimeChainState = 0;
1938 static int64_t nTimePostConnect = 0;
1940 struct PerBlockConnectTrace {
1941 CBlockIndex* pindex = NULL;
1942 std::shared_ptr<const CBlock> pblock;
1943 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
1944 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
1947 * Used to track blocks whose transactions were applied to the UTXO state as a
1948 * part of a single ActivateBestChainStep call.
1950 * This class also tracks transactions that are removed from the mempool as
1951 * conflicts (per block) and can be used to pass all those transactions
1952 * through SyncTransaction.
1954 * This class assumes (and asserts) that the conflicted transactions for a given
1955 * block are added via mempool callbacks prior to the BlockConnected() associated
1956 * with those transactions. If any transactions are marked conflicted, it is
1957 * assumed that an associated block will always be added.
1959 * This class is single-use, once you call GetBlocksConnected() you have to throw
1960 * it away and make a new one.
1962 class ConnectTrace {
1963 private:
1964 std::vector<PerBlockConnectTrace> blocksConnected;
1965 CTxMemPool &pool;
1967 public:
1968 ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
1969 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
1972 ~ConnectTrace() {
1973 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
1976 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
1977 assert(!blocksConnected.back().pindex);
1978 assert(pindex);
1979 assert(pblock);
1980 blocksConnected.back().pindex = pindex;
1981 blocksConnected.back().pblock = std::move(pblock);
1982 blocksConnected.emplace_back();
1985 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
1986 // We always keep one extra block at the end of our list because
1987 // blocks are added after all the conflicted transactions have
1988 // been filled in. Thus, the last entry should always be an empty
1989 // one waiting for the transactions from the next block. We pop
1990 // the last entry here to make sure the list we return is sane.
1991 assert(!blocksConnected.back().pindex);
1992 assert(blocksConnected.back().conflictedTxs->empty());
1993 blocksConnected.pop_back();
1994 return blocksConnected;
1997 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
1998 assert(!blocksConnected.back().pindex);
1999 if (reason == MemPoolRemovalReason::CONFLICT) {
2000 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2006 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2007 * corresponding to pindexNew, to bypass loading it again from disk.
2009 * The block is added to connectTrace if connection succeeds.
2011 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2013 assert(pindexNew->pprev == chainActive.Tip());
2014 // Read block from disk.
2015 int64_t nTime1 = GetTimeMicros();
2016 std::shared_ptr<const CBlock> pthisBlock;
2017 if (!pblock) {
2018 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2019 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2020 return AbortNode(state, "Failed to read block");
2021 pthisBlock = pblockNew;
2022 } else {
2023 pthisBlock = pblock;
2025 const CBlock& blockConnecting = *pthisBlock;
2026 // Apply the block atomically to the chain state.
2027 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2028 int64_t nTime3;
2029 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2031 CCoinsViewCache view(pcoinsTip);
2032 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2033 GetMainSignals().BlockChecked(blockConnecting, state);
2034 if (!rv) {
2035 if (state.IsInvalid())
2036 InvalidBlockFound(pindexNew, state);
2037 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2039 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2040 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2041 bool flushed = view.Flush();
2042 assert(flushed);
2044 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2045 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2046 // Write the chain state to disk, if necessary.
2047 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2048 return false;
2049 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2050 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2051 // Remove conflicting transactions from the mempool.;
2052 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2053 // Update chainActive & related variables.
2054 UpdateTip(pindexNew, chainparams);
2056 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2057 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2058 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2060 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2061 return true;
2065 * Return the tip of the chain with the most work in it, that isn't
2066 * known to be invalid (it's however far from certain to be valid).
2068 static CBlockIndex* FindMostWorkChain() {
2069 do {
2070 CBlockIndex *pindexNew = NULL;
2072 // Find the best candidate header.
2074 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2075 if (it == setBlockIndexCandidates.rend())
2076 return NULL;
2077 pindexNew = *it;
2080 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2081 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2082 CBlockIndex *pindexTest = pindexNew;
2083 bool fInvalidAncestor = false;
2084 while (pindexTest && !chainActive.Contains(pindexTest)) {
2085 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2087 // Pruned nodes may have entries in setBlockIndexCandidates for
2088 // which block files have been deleted. Remove those as candidates
2089 // for the most work chain if we come across them; we can't switch
2090 // to a chain unless we have all the non-active-chain parent blocks.
2091 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2092 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2093 if (fFailedChain || fMissingData) {
2094 // Candidate chain is not usable (either invalid or missing data)
2095 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2096 pindexBestInvalid = pindexNew;
2097 CBlockIndex *pindexFailed = pindexNew;
2098 // Remove the entire chain from the set.
2099 while (pindexTest != pindexFailed) {
2100 if (fFailedChain) {
2101 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2102 } else if (fMissingData) {
2103 // If we're missing data, then add back to mapBlocksUnlinked,
2104 // so that if the block arrives in the future we can try adding
2105 // to setBlockIndexCandidates again.
2106 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2108 setBlockIndexCandidates.erase(pindexFailed);
2109 pindexFailed = pindexFailed->pprev;
2111 setBlockIndexCandidates.erase(pindexTest);
2112 fInvalidAncestor = true;
2113 break;
2115 pindexTest = pindexTest->pprev;
2117 if (!fInvalidAncestor)
2118 return pindexNew;
2119 } while(true);
2122 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2123 static void PruneBlockIndexCandidates() {
2124 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2125 // reorganization to a better block fails.
2126 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2127 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2128 setBlockIndexCandidates.erase(it++);
2130 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2131 assert(!setBlockIndexCandidates.empty());
2135 * Try to make some progress towards making pindexMostWork the active block.
2136 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2138 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2140 AssertLockHeld(cs_main);
2141 const CBlockIndex *pindexOldTip = chainActive.Tip();
2142 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2144 // Disconnect active blocks which are no longer in the best chain.
2145 bool fBlocksDisconnected = false;
2146 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2147 if (!DisconnectTip(state, chainparams))
2148 return false;
2149 fBlocksDisconnected = true;
2152 // Build list of new blocks to connect.
2153 std::vector<CBlockIndex*> vpindexToConnect;
2154 bool fContinue = true;
2155 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2156 while (fContinue && nHeight != pindexMostWork->nHeight) {
2157 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2158 // a few blocks along the way.
2159 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2160 vpindexToConnect.clear();
2161 vpindexToConnect.reserve(nTargetHeight - nHeight);
2162 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2163 while (pindexIter && pindexIter->nHeight != nHeight) {
2164 vpindexToConnect.push_back(pindexIter);
2165 pindexIter = pindexIter->pprev;
2167 nHeight = nTargetHeight;
2169 // Connect new blocks.
2170 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2171 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2172 if (state.IsInvalid()) {
2173 // The block violates a consensus rule.
2174 if (!state.CorruptionPossible())
2175 InvalidChainFound(vpindexToConnect.back());
2176 state = CValidationState();
2177 fInvalidFound = true;
2178 fContinue = false;
2179 break;
2180 } else {
2181 // A system error occurred (disk space, database error, ...).
2182 return false;
2184 } else {
2185 PruneBlockIndexCandidates();
2186 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2187 // We're in a better position than we were. Return temporarily to release the lock.
2188 fContinue = false;
2189 break;
2195 if (fBlocksDisconnected) {
2196 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2197 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2199 mempool.check(pcoinsTip);
2201 // Callbacks/notifications for a new best chain.
2202 if (fInvalidFound)
2203 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2204 else
2205 CheckForkWarningConditions();
2207 return true;
2210 static void NotifyHeaderTip() {
2211 bool fNotify = false;
2212 bool fInitialBlockDownload = false;
2213 static CBlockIndex* pindexHeaderOld = NULL;
2214 CBlockIndex* pindexHeader = NULL;
2216 LOCK(cs_main);
2217 pindexHeader = pindexBestHeader;
2219 if (pindexHeader != pindexHeaderOld) {
2220 fNotify = true;
2221 fInitialBlockDownload = IsInitialBlockDownload();
2222 pindexHeaderOld = pindexHeader;
2225 // Send block tip changed notifications without cs_main
2226 if (fNotify) {
2227 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2232 * Make the best chain active, in multiple steps. The result is either failure
2233 * or an activated best chain. pblock is either NULL or a pointer to a block
2234 * that is already loaded (to avoid loading it again from disk).
2236 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2237 // Note that while we're often called here from ProcessNewBlock, this is
2238 // far from a guarantee. Things in the P2P/RPC will often end up calling
2239 // us in the middle of ProcessNewBlock - do not assume pblock is set
2240 // sanely for performance or correctness!
2242 CBlockIndex *pindexMostWork = NULL;
2243 CBlockIndex *pindexNewTip = NULL;
2244 do {
2245 boost::this_thread::interruption_point();
2246 if (ShutdownRequested())
2247 break;
2249 const CBlockIndex *pindexFork;
2250 bool fInitialDownload;
2252 LOCK(cs_main);
2253 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2255 CBlockIndex *pindexOldTip = chainActive.Tip();
2256 if (pindexMostWork == NULL) {
2257 pindexMostWork = FindMostWorkChain();
2260 // Whether we have anything to do at all.
2261 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2262 return true;
2264 bool fInvalidFound = false;
2265 std::shared_ptr<const CBlock> nullBlockPtr;
2266 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2267 return false;
2269 if (fInvalidFound) {
2270 // Wipe cache, we may need another branch now.
2271 pindexMostWork = NULL;
2273 pindexNewTip = chainActive.Tip();
2274 pindexFork = chainActive.FindFork(pindexOldTip);
2275 fInitialDownload = IsInitialBlockDownload();
2277 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2278 assert(trace.pblock && trace.pindex);
2279 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2282 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2284 // Notifications/callbacks that can run without cs_main
2286 // Notify external listeners about the new tip.
2287 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2289 // Always notify the UI if a new block tip was connected
2290 if (pindexFork != pindexNewTip) {
2291 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2293 } while (pindexNewTip != pindexMostWork);
2294 CheckBlockIndex(chainparams.GetConsensus());
2296 // Write changes periodically to disk, after relay.
2297 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2298 return false;
2301 int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2302 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2304 return true;
2308 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2311 LOCK(cs_main);
2312 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2313 // Nothing to do, this block is not at the tip.
2314 return true;
2316 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2317 // The chain has been extended since the last call, reset the counter.
2318 nBlockReverseSequenceId = -1;
2320 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2321 setBlockIndexCandidates.erase(pindex);
2322 pindex->nSequenceId = nBlockReverseSequenceId;
2323 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2324 // We can't keep reducing the counter if somebody really wants to
2325 // call preciousblock 2**31-1 times on the same set of tips...
2326 nBlockReverseSequenceId--;
2328 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2329 setBlockIndexCandidates.insert(pindex);
2330 PruneBlockIndexCandidates();
2334 return ActivateBestChain(state, params);
2337 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2339 AssertLockHeld(cs_main);
2341 // Mark the block itself as invalid.
2342 pindex->nStatus |= BLOCK_FAILED_VALID;
2343 setDirtyBlockIndex.insert(pindex);
2344 setBlockIndexCandidates.erase(pindex);
2346 while (chainActive.Contains(pindex)) {
2347 CBlockIndex *pindexWalk = chainActive.Tip();
2348 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2349 setDirtyBlockIndex.insert(pindexWalk);
2350 setBlockIndexCandidates.erase(pindexWalk);
2351 // ActivateBestChain considers blocks already in chainActive
2352 // unconditionally valid already, so force disconnect away from it.
2353 if (!DisconnectTip(state, chainparams)) {
2354 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2355 return false;
2359 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2361 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2362 // add it again.
2363 BlockMap::iterator it = mapBlockIndex.begin();
2364 while (it != mapBlockIndex.end()) {
2365 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2366 setBlockIndexCandidates.insert(it->second);
2368 it++;
2371 InvalidChainFound(pindex);
2372 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2373 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2374 return true;
2377 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2378 AssertLockHeld(cs_main);
2380 int nHeight = pindex->nHeight;
2382 // Remove the invalidity flag from this block and all its descendants.
2383 BlockMap::iterator it = mapBlockIndex.begin();
2384 while (it != mapBlockIndex.end()) {
2385 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2386 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2387 setDirtyBlockIndex.insert(it->second);
2388 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2389 setBlockIndexCandidates.insert(it->second);
2391 if (it->second == pindexBestInvalid) {
2392 // Reset invalid block marker if it was pointing to one of those.
2393 pindexBestInvalid = NULL;
2396 it++;
2399 // Remove the invalidity flag from all ancestors too.
2400 while (pindex != NULL) {
2401 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2402 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2403 setDirtyBlockIndex.insert(pindex);
2405 pindex = pindex->pprev;
2407 return true;
2410 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2412 // Check for duplicate
2413 uint256 hash = block.GetHash();
2414 BlockMap::iterator it = mapBlockIndex.find(hash);
2415 if (it != mapBlockIndex.end())
2416 return it->second;
2418 // Construct new block index object
2419 CBlockIndex* pindexNew = new CBlockIndex(block);
2420 assert(pindexNew);
2421 // We assign the sequence id to blocks only when the full data is available,
2422 // to avoid miners withholding blocks but broadcasting headers, to get a
2423 // competitive advantage.
2424 pindexNew->nSequenceId = 0;
2425 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2426 pindexNew->phashBlock = &((*mi).first);
2427 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2428 if (miPrev != mapBlockIndex.end())
2430 pindexNew->pprev = (*miPrev).second;
2431 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2432 pindexNew->BuildSkip();
2434 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2435 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2436 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2437 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2438 pindexBestHeader = pindexNew;
2440 setDirtyBlockIndex.insert(pindexNew);
2442 return pindexNew;
2445 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2446 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2448 pindexNew->nTx = block.vtx.size();
2449 pindexNew->nChainTx = 0;
2450 pindexNew->nFile = pos.nFile;
2451 pindexNew->nDataPos = pos.nPos;
2452 pindexNew->nUndoPos = 0;
2453 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2454 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2455 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2457 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2458 setDirtyBlockIndex.insert(pindexNew);
2460 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2461 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2462 std::deque<CBlockIndex*> queue;
2463 queue.push_back(pindexNew);
2465 // Recursively process any descendant blocks that now may be eligible to be connected.
2466 while (!queue.empty()) {
2467 CBlockIndex *pindex = queue.front();
2468 queue.pop_front();
2469 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2471 LOCK(cs_nBlockSequenceId);
2472 pindex->nSequenceId = nBlockSequenceId++;
2474 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2475 setBlockIndexCandidates.insert(pindex);
2477 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2478 while (range.first != range.second) {
2479 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2480 queue.push_back(it->second);
2481 range.first++;
2482 mapBlocksUnlinked.erase(it);
2485 } else {
2486 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2487 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2491 return true;
2494 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2496 LOCK(cs_LastBlockFile);
2498 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2499 if (vinfoBlockFile.size() <= nFile) {
2500 vinfoBlockFile.resize(nFile + 1);
2503 if (!fKnown) {
2504 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2505 nFile++;
2506 if (vinfoBlockFile.size() <= nFile) {
2507 vinfoBlockFile.resize(nFile + 1);
2510 pos.nFile = nFile;
2511 pos.nPos = vinfoBlockFile[nFile].nSize;
2514 if ((int)nFile != nLastBlockFile) {
2515 if (!fKnown) {
2516 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2518 FlushBlockFile(!fKnown);
2519 nLastBlockFile = nFile;
2522 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2523 if (fKnown)
2524 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2525 else
2526 vinfoBlockFile[nFile].nSize += nAddSize;
2528 if (!fKnown) {
2529 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2530 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2531 if (nNewChunks > nOldChunks) {
2532 if (fPruneMode)
2533 fCheckForPruning = true;
2534 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2535 FILE *file = OpenBlockFile(pos);
2536 if (file) {
2537 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2538 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2539 fclose(file);
2542 else
2543 return state.Error("out of disk space");
2547 setDirtyFileInfo.insert(nFile);
2548 return true;
2551 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2553 pos.nFile = nFile;
2555 LOCK(cs_LastBlockFile);
2557 unsigned int nNewSize;
2558 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2559 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2560 setDirtyFileInfo.insert(nFile);
2562 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2563 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2564 if (nNewChunks > nOldChunks) {
2565 if (fPruneMode)
2566 fCheckForPruning = true;
2567 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2568 FILE *file = OpenUndoFile(pos);
2569 if (file) {
2570 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2571 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2572 fclose(file);
2575 else
2576 return state.Error("out of disk space");
2579 return true;
2582 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW)
2584 // Check proof of work matches claimed amount
2585 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2586 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2588 return true;
2591 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2593 // These are checks that are independent of context.
2595 if (block.fChecked)
2596 return true;
2598 // Check that the header is valid (particularly PoW). This is mostly
2599 // redundant with the call in AcceptBlockHeader.
2600 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2601 return false;
2603 // Check the merkle root.
2604 if (fCheckMerkleRoot) {
2605 bool mutated;
2606 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2607 if (block.hashMerkleRoot != hashMerkleRoot2)
2608 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2610 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2611 // of transactions in a block without affecting the merkle root of a block,
2612 // while still invalidating it.
2613 if (mutated)
2614 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2617 // All potential-corruption validation must be done before we do any
2618 // transaction validation, as otherwise we may mark the header as invalid
2619 // because we receive the wrong transactions for it.
2620 // Note that witness malleability is checked in ContextualCheckBlock, so no
2621 // checks that use witness data may be performed here.
2623 // Size limits
2624 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_BASE_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
2625 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2627 // First transaction must be coinbase, the rest must not be
2628 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2629 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2630 for (unsigned int i = 1; i < block.vtx.size(); i++)
2631 if (block.vtx[i]->IsCoinBase())
2632 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2634 // Check transactions
2635 for (const auto& tx : block.vtx)
2636 if (!CheckTransaction(*tx, state, false))
2637 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2638 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2640 unsigned int nSigOps = 0;
2641 for (const auto& tx : block.vtx)
2643 nSigOps += GetLegacySigOpCount(*tx);
2645 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2646 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2648 if (fCheckPOW && fCheckMerkleRoot)
2649 block.fChecked = true;
2651 return true;
2654 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2656 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2657 return true;
2659 int nHeight = pindexPrev->nHeight+1;
2660 // Don't accept any forks from the main chain prior to last checkpoint.
2661 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2662 // MapBlockIndex.
2663 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2664 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2665 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2667 return true;
2670 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2672 LOCK(cs_main);
2673 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2676 // Compute at which vout of the block's coinbase transaction the witness
2677 // commitment occurs, or -1 if not found.
2678 static int GetWitnessCommitmentIndex(const CBlock& block)
2680 int commitpos = -1;
2681 if (!block.vtx.empty()) {
2682 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2683 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) {
2684 commitpos = o;
2688 return commitpos;
2691 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2693 int commitpos = GetWitnessCommitmentIndex(block);
2694 static const std::vector<unsigned char> nonce(32, 0x00);
2695 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2696 CMutableTransaction tx(*block.vtx[0]);
2697 tx.vin[0].scriptWitness.stack.resize(1);
2698 tx.vin[0].scriptWitness.stack[0] = nonce;
2699 block.vtx[0] = MakeTransactionRef(std::move(tx));
2703 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2705 std::vector<unsigned char> commitment;
2706 int commitpos = GetWitnessCommitmentIndex(block);
2707 std::vector<unsigned char> ret(32, 0x00);
2708 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2709 if (commitpos == -1) {
2710 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2711 CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2712 CTxOut out;
2713 out.nValue = 0;
2714 out.scriptPubKey.resize(38);
2715 out.scriptPubKey[0] = OP_RETURN;
2716 out.scriptPubKey[1] = 0x24;
2717 out.scriptPubKey[2] = 0xaa;
2718 out.scriptPubKey[3] = 0x21;
2719 out.scriptPubKey[4] = 0xa9;
2720 out.scriptPubKey[5] = 0xed;
2721 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2722 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2723 CMutableTransaction tx(*block.vtx[0]);
2724 tx.vout.push_back(out);
2725 block.vtx[0] = MakeTransactionRef(std::move(tx));
2728 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2729 return commitment;
2732 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2734 assert(pindexPrev != NULL);
2735 const int nHeight = pindexPrev->nHeight + 1;
2736 // Check proof of work
2737 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2738 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2740 // Check timestamp against prev
2741 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2742 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2744 // Check timestamp
2745 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2746 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2748 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2749 // check for version 2, 3 and 4 upgrades
2750 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2751 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2752 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2753 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2754 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2756 return true;
2759 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2761 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2763 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2764 int nLockTimeFlags = 0;
2765 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2766 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2769 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2770 ? pindexPrev->GetMedianTimePast()
2771 : block.GetBlockTime();
2773 // Check that all transactions are finalized
2774 for (const auto& tx : block.vtx) {
2775 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2776 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2780 // Enforce rule that the coinbase starts with serialized block height
2781 if (nHeight >= consensusParams.BIP34Height)
2783 CScript expect = CScript() << nHeight;
2784 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2785 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2786 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2790 // Validation for witness commitments.
2791 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2792 // coinbase (where 0x0000....0000 is used instead).
2793 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2794 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2795 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2796 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2797 // multiple, the last one is used.
2798 bool fHaveWitness = false;
2799 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2800 int commitpos = GetWitnessCommitmentIndex(block);
2801 if (commitpos != -1) {
2802 bool malleated = false;
2803 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2804 // The malleation check is ignored; as the transaction tree itself
2805 // already does not permit it, it is impossible to trigger in the
2806 // witness tree.
2807 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
2808 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
2810 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
2811 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
2812 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
2814 fHaveWitness = true;
2818 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
2819 if (!fHaveWitness) {
2820 for (size_t i = 0; i < block.vtx.size(); i++) {
2821 if (block.vtx[i]->HasWitness()) {
2822 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
2827 // After the coinbase witness nonce and commitment are verified,
2828 // we can check if the block weight passes (before we've checked the
2829 // coinbase witness, it would be possible for the weight to be too
2830 // large by filling up the coinbase witness, which doesn't change
2831 // the block hash, so we couldn't mark the block as permanently
2832 // failed).
2833 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
2834 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
2837 return true;
2840 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
2842 AssertLockHeld(cs_main);
2843 // Check for duplicate
2844 uint256 hash = block.GetHash();
2845 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2846 CBlockIndex *pindex = NULL;
2847 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2849 if (miSelf != mapBlockIndex.end()) {
2850 // Block header is already known.
2851 pindex = miSelf->second;
2852 if (ppindex)
2853 *ppindex = pindex;
2854 if (pindex->nStatus & BLOCK_FAILED_MASK)
2855 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
2856 return true;
2859 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
2860 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
2862 // Get prev block index
2863 CBlockIndex* pindexPrev = NULL;
2864 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2865 if (mi == mapBlockIndex.end())
2866 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
2867 pindexPrev = (*mi).second;
2868 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2869 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2871 assert(pindexPrev);
2872 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
2873 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2875 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
2876 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
2878 if (pindex == NULL)
2879 pindex = AddToBlockIndex(block);
2881 if (ppindex)
2882 *ppindex = pindex;
2884 CheckBlockIndex(chainparams.GetConsensus());
2886 return true;
2889 // Exposed wrapper for AcceptBlockHeader
2890 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
2893 LOCK(cs_main);
2894 for (const CBlockHeader& header : headers) {
2895 CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
2896 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
2897 return false;
2899 if (ppindex) {
2900 *ppindex = pindex;
2904 NotifyHeaderTip();
2905 return true;
2908 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
2909 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
2911 const CBlock& block = *pblock;
2913 if (fNewBlock) *fNewBlock = false;
2914 AssertLockHeld(cs_main);
2916 CBlockIndex *pindexDummy = NULL;
2917 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
2919 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
2920 return false;
2922 // Try to process all requested blocks that we don't have, but only
2923 // process an unrequested block if it's new and has enough work to
2924 // advance our tip, and isn't too many blocks ahead.
2925 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
2926 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
2927 // Blocks that are too out-of-order needlessly limit the effectiveness of
2928 // pruning, because pruning will not delete block files that contain any
2929 // blocks which are too close in height to the tip. Apply this test
2930 // regardless of whether pruning is enabled; it should generally be safe to
2931 // not process unrequested blocks.
2932 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
2934 // TODO: Decouple this function from the block download logic by removing fRequested
2935 // This requires some new chain data structure to efficiently look up if a
2936 // block is in a chain leading to a candidate for best tip, despite not
2937 // being such a candidate itself.
2939 // TODO: deal better with return value and error conditions for duplicate
2940 // and unrequested blocks.
2941 if (fAlreadyHave) return true;
2942 if (!fRequested) { // If we didn't ask for it:
2943 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
2944 if (!fHasMoreWork) return true; // Don't process less-work chains
2945 if (fTooFarAhead) return true; // Block height is too high
2947 if (fNewBlock) *fNewBlock = true;
2949 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
2950 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
2951 if (state.IsInvalid() && !state.CorruptionPossible()) {
2952 pindex->nStatus |= BLOCK_FAILED_VALID;
2953 setDirtyBlockIndex.insert(pindex);
2955 return error("%s: %s", __func__, FormatStateMessage(state));
2958 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
2959 // (but if it does not build on our best tip, let the SendMessages loop relay it)
2960 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
2961 GetMainSignals().NewPoWValidBlock(pindex, pblock);
2963 int nHeight = pindex->nHeight;
2965 // Write block to history file
2966 try {
2967 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2968 CDiskBlockPos blockPos;
2969 if (dbp != NULL)
2970 blockPos = *dbp;
2971 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2972 return error("AcceptBlock(): FindBlockPos failed");
2973 if (dbp == NULL)
2974 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2975 AbortNode(state, "Failed to write block");
2976 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
2977 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2978 } catch (const std::runtime_error& e) {
2979 return AbortNode(state, std::string("System error: ") + e.what());
2982 if (fCheckForPruning)
2983 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2985 return true;
2988 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
2991 CBlockIndex *pindex = NULL;
2992 if (fNewBlock) *fNewBlock = false;
2993 CValidationState state;
2994 // Ensure that CheckBlock() passes before calling AcceptBlock, as
2995 // belt-and-suspenders.
2996 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
2998 LOCK(cs_main);
3000 if (ret) {
3001 // Store to disk
3002 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3004 CheckBlockIndex(chainparams.GetConsensus());
3005 if (!ret) {
3006 GetMainSignals().BlockChecked(*pblock, state);
3007 return error("%s: AcceptBlock FAILED", __func__);
3011 NotifyHeaderTip();
3013 CValidationState state; // Only used to report errors, not invalidity - ignore it
3014 if (!ActivateBestChain(state, chainparams, pblock))
3015 return error("%s: ActivateBestChain failed", __func__);
3017 return true;
3020 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3022 AssertLockHeld(cs_main);
3023 assert(pindexPrev && pindexPrev == chainActive.Tip());
3024 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3025 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3027 CCoinsViewCache viewNew(pcoinsTip);
3028 CBlockIndex indexDummy(block);
3029 indexDummy.pprev = pindexPrev;
3030 indexDummy.nHeight = pindexPrev->nHeight + 1;
3032 // NOTE: CheckBlockHeader is called by CheckBlock
3033 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3034 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3035 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3036 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3037 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3038 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3039 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3040 return false;
3041 assert(state.IsValid());
3043 return true;
3047 * BLOCK PRUNING CODE
3050 /* Calculate the amount of disk space the block & undo files currently use */
3051 uint64_t CalculateCurrentUsage()
3053 uint64_t retval = 0;
3054 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3055 retval += file.nSize + file.nUndoSize;
3057 return retval;
3060 /* Prune a block file (modify associated database entries)*/
3061 void PruneOneBlockFile(const int fileNumber)
3063 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3064 CBlockIndex* pindex = it->second;
3065 if (pindex->nFile == fileNumber) {
3066 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3067 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3068 pindex->nFile = 0;
3069 pindex->nDataPos = 0;
3070 pindex->nUndoPos = 0;
3071 setDirtyBlockIndex.insert(pindex);
3073 // Prune from mapBlocksUnlinked -- any block we prune would have
3074 // to be downloaded again in order to consider its chain, at which
3075 // point it would be considered as a candidate for
3076 // mapBlocksUnlinked or setBlockIndexCandidates.
3077 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3078 while (range.first != range.second) {
3079 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3080 range.first++;
3081 if (_it->second == pindex) {
3082 mapBlocksUnlinked.erase(_it);
3088 vinfoBlockFile[fileNumber].SetNull();
3089 setDirtyFileInfo.insert(fileNumber);
3093 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3095 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3096 CDiskBlockPos pos(*it, 0);
3097 fs::remove(GetBlockPosFilename(pos, "blk"));
3098 fs::remove(GetBlockPosFilename(pos, "rev"));
3099 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3103 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3104 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3106 assert(fPruneMode && nManualPruneHeight > 0);
3108 LOCK2(cs_main, cs_LastBlockFile);
3109 if (chainActive.Tip() == NULL)
3110 return;
3112 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3113 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3114 int count=0;
3115 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3116 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3117 continue;
3118 PruneOneBlockFile(fileNumber);
3119 setFilesToPrune.insert(fileNumber);
3120 count++;
3122 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3125 /* This function is called from the RPC code for pruneblockchain */
3126 void PruneBlockFilesManual(int nManualPruneHeight)
3128 CValidationState state;
3129 FlushStateToDisk(state, FLUSH_STATE_NONE, nManualPruneHeight);
3132 /* Calculate the block/rev files that should be deleted to remain under target*/
3133 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3135 LOCK2(cs_main, cs_LastBlockFile);
3136 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3137 return;
3139 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3140 return;
3143 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3144 uint64_t nCurrentUsage = CalculateCurrentUsage();
3145 // We don't check to prune until after we've allocated new space for files
3146 // So we should leave a buffer under our target to account for another allocation
3147 // before the next pruning.
3148 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3149 uint64_t nBytesToPrune;
3150 int count=0;
3152 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3153 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3154 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3156 if (vinfoBlockFile[fileNumber].nSize == 0)
3157 continue;
3159 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3160 break;
3162 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3163 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3164 continue;
3166 PruneOneBlockFile(fileNumber);
3167 // Queue up the files for removal
3168 setFilesToPrune.insert(fileNumber);
3169 nCurrentUsage -= nBytesToPrune;
3170 count++;
3174 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3175 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3176 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3177 nLastBlockWeCanPrune, count);
3180 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3182 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3184 // Check for nMinDiskSpace bytes (currently 50MB)
3185 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3186 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3188 return true;
3191 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3193 if (pos.IsNull())
3194 return NULL;
3195 fs::path path = GetBlockPosFilename(pos, prefix);
3196 fs::create_directories(path.parent_path());
3197 FILE* file = fsbridge::fopen(path, "rb+");
3198 if (!file && !fReadOnly)
3199 file = fsbridge::fopen(path, "wb+");
3200 if (!file) {
3201 LogPrintf("Unable to open file %s\n", path.string());
3202 return NULL;
3204 if (pos.nPos) {
3205 if (fseek(file, pos.nPos, SEEK_SET)) {
3206 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3207 fclose(file);
3208 return NULL;
3211 return file;
3214 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3215 return OpenDiskFile(pos, "blk", fReadOnly);
3218 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3219 return OpenDiskFile(pos, "rev", fReadOnly);
3222 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3224 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3227 CBlockIndex * InsertBlockIndex(uint256 hash)
3229 if (hash.IsNull())
3230 return NULL;
3232 // Return existing
3233 BlockMap::iterator mi = mapBlockIndex.find(hash);
3234 if (mi != mapBlockIndex.end())
3235 return (*mi).second;
3237 // Create new
3238 CBlockIndex* pindexNew = new CBlockIndex();
3239 if (!pindexNew)
3240 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3241 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3242 pindexNew->phashBlock = &((*mi).first);
3244 return pindexNew;
3247 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3249 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3250 return false;
3252 boost::this_thread::interruption_point();
3254 // Calculate nChainWork
3255 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3256 vSortedByHeight.reserve(mapBlockIndex.size());
3257 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3259 CBlockIndex* pindex = item.second;
3260 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3262 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3263 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3265 CBlockIndex* pindex = item.second;
3266 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3267 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3268 // We can link the chain of blocks for which we've received transactions at some point.
3269 // Pruned nodes may have deleted the block.
3270 if (pindex->nTx > 0) {
3271 if (pindex->pprev) {
3272 if (pindex->pprev->nChainTx) {
3273 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3274 } else {
3275 pindex->nChainTx = 0;
3276 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3278 } else {
3279 pindex->nChainTx = pindex->nTx;
3282 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3283 setBlockIndexCandidates.insert(pindex);
3284 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3285 pindexBestInvalid = pindex;
3286 if (pindex->pprev)
3287 pindex->BuildSkip();
3288 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3289 pindexBestHeader = pindex;
3292 // Load block file info
3293 pblocktree->ReadLastBlockFile(nLastBlockFile);
3294 vinfoBlockFile.resize(nLastBlockFile + 1);
3295 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3296 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3297 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3299 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3300 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3301 CBlockFileInfo info;
3302 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3303 vinfoBlockFile.push_back(info);
3304 } else {
3305 break;
3309 // Check presence of blk files
3310 LogPrintf("Checking all blk files are present...\n");
3311 std::set<int> setBlkDataFiles;
3312 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3314 CBlockIndex* pindex = item.second;
3315 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3316 setBlkDataFiles.insert(pindex->nFile);
3319 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3321 CDiskBlockPos pos(*it, 0);
3322 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3323 return false;
3327 // Check whether we have ever pruned block & undo files
3328 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3329 if (fHavePruned)
3330 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3332 // Check whether we need to continue reindexing
3333 bool fReindexing = false;
3334 pblocktree->ReadReindexing(fReindexing);
3335 fReindex |= fReindexing;
3337 // Check whether we have a transaction index
3338 pblocktree->ReadFlag("txindex", fTxIndex);
3339 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3341 // Load pointer to end of best chain
3342 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3343 if (it == mapBlockIndex.end())
3344 return true;
3345 chainActive.SetTip(it->second);
3347 PruneBlockIndexCandidates();
3349 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3350 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3351 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3352 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3354 return true;
3357 CVerifyDB::CVerifyDB()
3359 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3362 CVerifyDB::~CVerifyDB()
3364 uiInterface.ShowProgress("", 100);
3367 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3369 LOCK(cs_main);
3370 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3371 return true;
3373 // Verify blocks in the best chain
3374 if (nCheckDepth <= 0)
3375 nCheckDepth = 1000000000; // suffices until the year 19000
3376 if (nCheckDepth > chainActive.Height())
3377 nCheckDepth = chainActive.Height();
3378 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3379 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3380 CCoinsViewCache coins(coinsview);
3381 CBlockIndex* pindexState = chainActive.Tip();
3382 CBlockIndex* pindexFailure = NULL;
3383 int nGoodTransactions = 0;
3384 CValidationState state;
3385 int reportDone = 0;
3386 LogPrintf("[0%%]...");
3387 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3389 boost::this_thread::interruption_point();
3390 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3391 if (reportDone < percentageDone/10) {
3392 // report every 10% step
3393 LogPrintf("[%d%%]...", percentageDone);
3394 reportDone = percentageDone/10;
3396 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3397 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3398 break;
3399 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3400 // If pruning, only go back as far as we have data.
3401 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3402 break;
3404 CBlock block;
3405 // check level 0: read from disk
3406 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3407 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3408 // check level 1: verify block validity
3409 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3410 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3411 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3412 // check level 2: verify undo validity
3413 if (nCheckLevel >= 2 && pindex) {
3414 CBlockUndo undo;
3415 CDiskBlockPos pos = pindex->GetUndoPos();
3416 if (!pos.IsNull()) {
3417 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3418 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3421 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3422 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3423 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3424 if (res == DISCONNECT_FAILED) {
3425 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3427 pindexState = pindex->pprev;
3428 if (res == DISCONNECT_UNCLEAN) {
3429 nGoodTransactions = 0;
3430 pindexFailure = pindex;
3431 } else {
3432 nGoodTransactions += block.vtx.size();
3435 if (ShutdownRequested())
3436 return true;
3438 if (pindexFailure)
3439 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3441 // check level 4: try reconnecting blocks
3442 if (nCheckLevel >= 4) {
3443 CBlockIndex *pindex = pindexState;
3444 while (pindex != chainActive.Tip()) {
3445 boost::this_thread::interruption_point();
3446 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3447 pindex = chainActive.Next(pindex);
3448 CBlock block;
3449 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3450 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3451 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3452 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3456 LogPrintf("[DONE].\n");
3457 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3459 return true;
3462 bool RewindBlockIndex(const CChainParams& params)
3464 LOCK(cs_main);
3466 int nHeight = 1;
3467 while (nHeight <= chainActive.Height()) {
3468 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3469 break;
3471 nHeight++;
3474 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3475 CValidationState state;
3476 CBlockIndex* pindex = chainActive.Tip();
3477 while (chainActive.Height() >= nHeight) {
3478 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3479 // If pruning, don't try rewinding past the HAVE_DATA point;
3480 // since older blocks can't be served anyway, there's
3481 // no need to walk further, and trying to DisconnectTip()
3482 // will fail (and require a needless reindex/redownload
3483 // of the blockchain).
3484 break;
3486 if (!DisconnectTip(state, params, true)) {
3487 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3489 // Occasionally flush state to disk.
3490 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3491 return false;
3494 // Reduce validity flag and have-data flags.
3495 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3496 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3497 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3498 CBlockIndex* pindexIter = it->second;
3500 // Note: If we encounter an insufficiently validated block that
3501 // is on chainActive, it must be because we are a pruning node, and
3502 // this block or some successor doesn't HAVE_DATA, so we were unable to
3503 // rewind all the way. Blocks remaining on chainActive at this point
3504 // must not have their validity reduced.
3505 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3506 // Reduce validity
3507 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3508 // Remove have-data flags.
3509 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3510 // Remove storage location.
3511 pindexIter->nFile = 0;
3512 pindexIter->nDataPos = 0;
3513 pindexIter->nUndoPos = 0;
3514 // Remove various other things
3515 pindexIter->nTx = 0;
3516 pindexIter->nChainTx = 0;
3517 pindexIter->nSequenceId = 0;
3518 // Make sure it gets written.
3519 setDirtyBlockIndex.insert(pindexIter);
3520 // Update indexes
3521 setBlockIndexCandidates.erase(pindexIter);
3522 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3523 while (ret.first != ret.second) {
3524 if (ret.first->second == pindexIter) {
3525 mapBlocksUnlinked.erase(ret.first++);
3526 } else {
3527 ++ret.first;
3530 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3531 setBlockIndexCandidates.insert(pindexIter);
3535 PruneBlockIndexCandidates();
3537 CheckBlockIndex(params.GetConsensus());
3539 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3540 return false;
3543 return true;
3546 // May NOT be used after any connections are up as much
3547 // of the peer-processing logic assumes a consistent
3548 // block index state
3549 void UnloadBlockIndex()
3551 LOCK(cs_main);
3552 setBlockIndexCandidates.clear();
3553 chainActive.SetTip(NULL);
3554 pindexBestInvalid = NULL;
3555 pindexBestHeader = NULL;
3556 mempool.clear();
3557 mapBlocksUnlinked.clear();
3558 vinfoBlockFile.clear();
3559 nLastBlockFile = 0;
3560 nBlockSequenceId = 1;
3561 setDirtyBlockIndex.clear();
3562 setDirtyFileInfo.clear();
3563 versionbitscache.Clear();
3564 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3565 warningcache[b].clear();
3568 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3569 delete entry.second;
3571 mapBlockIndex.clear();
3572 fHavePruned = false;
3575 bool LoadBlockIndex(const CChainParams& chainparams)
3577 // Load block index from databases
3578 if (!fReindex && !LoadBlockIndexDB(chainparams))
3579 return false;
3580 return true;
3583 bool InitBlockIndex(const CChainParams& chainparams)
3585 LOCK(cs_main);
3587 // Check whether we're already initialized
3588 if (chainActive.Genesis() != NULL)
3589 return true;
3591 // Use the provided setting for -txindex in the new database
3592 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3593 pblocktree->WriteFlag("txindex", fTxIndex);
3594 LogPrintf("Initializing databases...\n");
3596 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3597 if (!fReindex) {
3598 try {
3599 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3600 // Start new block file
3601 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3602 CDiskBlockPos blockPos;
3603 CValidationState state;
3604 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3605 return error("LoadBlockIndex(): FindBlockPos failed");
3606 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3607 return error("LoadBlockIndex(): writing genesis block to disk failed");
3608 CBlockIndex *pindex = AddToBlockIndex(block);
3609 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3610 return error("LoadBlockIndex(): genesis block not accepted");
3611 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3612 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3613 } catch (const std::runtime_error& e) {
3614 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3618 return true;
3621 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3623 // Map of disk positions for blocks with unknown parent (only used for reindex)
3624 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3625 int64_t nStart = GetTimeMillis();
3627 int nLoaded = 0;
3628 try {
3629 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3630 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3631 uint64_t nRewind = blkdat.GetPos();
3632 while (!blkdat.eof()) {
3633 boost::this_thread::interruption_point();
3635 blkdat.SetPos(nRewind);
3636 nRewind++; // start one byte further next time, in case of failure
3637 blkdat.SetLimit(); // remove former limit
3638 unsigned int nSize = 0;
3639 try {
3640 // locate a header
3641 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3642 blkdat.FindByte(chainparams.MessageStart()[0]);
3643 nRewind = blkdat.GetPos()+1;
3644 blkdat >> FLATDATA(buf);
3645 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3646 continue;
3647 // read size
3648 blkdat >> nSize;
3649 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3650 continue;
3651 } catch (const std::exception&) {
3652 // no valid block header found; don't complain
3653 break;
3655 try {
3656 // read block
3657 uint64_t nBlockPos = blkdat.GetPos();
3658 if (dbp)
3659 dbp->nPos = nBlockPos;
3660 blkdat.SetLimit(nBlockPos + nSize);
3661 blkdat.SetPos(nBlockPos);
3662 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3663 CBlock& block = *pblock;
3664 blkdat >> block;
3665 nRewind = blkdat.GetPos();
3667 // detect out of order blocks, and store them for later
3668 uint256 hash = block.GetHash();
3669 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3670 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3671 block.hashPrevBlock.ToString());
3672 if (dbp)
3673 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3674 continue;
3677 // process in case the block isn't known yet
3678 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3679 LOCK(cs_main);
3680 CValidationState state;
3681 if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3682 nLoaded++;
3683 if (state.IsError())
3684 break;
3685 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3686 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3689 // Activate the genesis block so normal node progress can continue
3690 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3691 CValidationState state;
3692 if (!ActivateBestChain(state, chainparams)) {
3693 break;
3697 NotifyHeaderTip();
3699 // Recursively process earlier encountered successors of this block
3700 std::deque<uint256> queue;
3701 queue.push_back(hash);
3702 while (!queue.empty()) {
3703 uint256 head = queue.front();
3704 queue.pop_front();
3705 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3706 while (range.first != range.second) {
3707 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3708 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
3709 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
3711 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
3712 head.ToString());
3713 LOCK(cs_main);
3714 CValidationState dummy;
3715 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
3717 nLoaded++;
3718 queue.push_back(pblockrecursive->GetHash());
3721 range.first++;
3722 mapBlocksUnknownParent.erase(it);
3723 NotifyHeaderTip();
3726 } catch (const std::exception& e) {
3727 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3730 } catch (const std::runtime_error& e) {
3731 AbortNode(std::string("System error: ") + e.what());
3733 if (nLoaded > 0)
3734 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3735 return nLoaded > 0;
3738 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3740 if (!fCheckBlockIndex) {
3741 return;
3744 LOCK(cs_main);
3746 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3747 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3748 // iterating the block tree require that chainActive has been initialized.)
3749 if (chainActive.Height() < 0) {
3750 assert(mapBlockIndex.size() <= 1);
3751 return;
3754 // Build forward-pointing map of the entire block tree.
3755 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3756 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3757 forward.insert(std::make_pair(it->second->pprev, it->second));
3760 assert(forward.size() == mapBlockIndex.size());
3762 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3763 CBlockIndex *pindex = rangeGenesis.first->second;
3764 rangeGenesis.first++;
3765 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3767 // Iterate over the entire block tree, using depth-first search.
3768 // Along the way, remember whether there are blocks on the path from genesis
3769 // block being explored which are the first to have certain properties.
3770 size_t nNodes = 0;
3771 int nHeight = 0;
3772 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3773 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3774 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3775 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3776 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3777 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3778 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3779 while (pindex != NULL) {
3780 nNodes++;
3781 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3782 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3783 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3784 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3785 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3786 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3787 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3789 // Begin: actual consistency checks.
3790 if (pindex->pprev == NULL) {
3791 // Genesis block checks.
3792 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3793 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3795 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)
3796 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3797 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3798 if (!fHavePruned) {
3799 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3800 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3801 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3802 } else {
3803 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3804 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3806 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3807 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3808 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3809 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3810 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3811 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3812 assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
3813 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3814 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3815 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3816 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3817 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3818 if (pindexFirstInvalid == NULL) {
3819 // Checks for not-invalid blocks.
3820 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3822 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3823 if (pindexFirstInvalid == NULL) {
3824 // If this block sorts at least as good as the current tip and
3825 // is valid and we have all data for its parents, it must be in
3826 // setBlockIndexCandidates. chainActive.Tip() must also be there
3827 // even if some data has been pruned.
3828 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3829 assert(setBlockIndexCandidates.count(pindex));
3831 // If some parent is missing, then it could be that this block was in
3832 // setBlockIndexCandidates but had to be removed because of the missing data.
3833 // In this case it must be in mapBlocksUnlinked -- see test below.
3835 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3836 assert(setBlockIndexCandidates.count(pindex) == 0);
3838 // Check whether this block is in mapBlocksUnlinked.
3839 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3840 bool foundInUnlinked = false;
3841 while (rangeUnlinked.first != rangeUnlinked.second) {
3842 assert(rangeUnlinked.first->first == pindex->pprev);
3843 if (rangeUnlinked.first->second == pindex) {
3844 foundInUnlinked = true;
3845 break;
3847 rangeUnlinked.first++;
3849 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3850 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3851 assert(foundInUnlinked);
3853 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3854 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3855 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3856 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3857 assert(fHavePruned); // We must have pruned.
3858 // This block may have entered mapBlocksUnlinked if:
3859 // - it has a descendant that at some point had more work than the
3860 // tip, and
3861 // - we tried switching to that descendant but were missing
3862 // data for some intermediate block between chainActive and the
3863 // tip.
3864 // So if this block is itself better than chainActive.Tip() and it wasn't in
3865 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3866 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3867 if (pindexFirstInvalid == NULL) {
3868 assert(foundInUnlinked);
3872 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3873 // End: actual consistency checks.
3875 // Try descending into the first subnode.
3876 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3877 if (range.first != range.second) {
3878 // A subnode was found.
3879 pindex = range.first->second;
3880 nHeight++;
3881 continue;
3883 // This is a leaf node.
3884 // Move upwards until we reach a node of which we have not yet visited the last child.
3885 while (pindex) {
3886 // We are going to either move to a parent or a sibling of pindex.
3887 // If pindex was the first with a certain property, unset the corresponding variable.
3888 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3889 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3890 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3891 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3892 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3893 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3894 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3895 // Find our parent.
3896 CBlockIndex* pindexPar = pindex->pprev;
3897 // Find which child we just visited.
3898 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3899 while (rangePar.first->second != pindex) {
3900 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3901 rangePar.first++;
3903 // Proceed to the next one.
3904 rangePar.first++;
3905 if (rangePar.first != rangePar.second) {
3906 // Move to the sibling.
3907 pindex = rangePar.first->second;
3908 break;
3909 } else {
3910 // Move up further.
3911 pindex = pindexPar;
3912 nHeight--;
3913 continue;
3918 // Check that we actually traversed the entire map.
3919 assert(nNodes == forward.size());
3922 std::string CBlockFileInfo::ToString() const
3924 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));
3927 CBlockFileInfo* GetBlockFileInfo(size_t n)
3929 return &vinfoBlockFile.at(n);
3932 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
3934 LOCK(cs_main);
3935 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
3938 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
3940 LOCK(cs_main);
3941 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
3944 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
3946 bool LoadMempool(void)
3948 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
3949 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
3950 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
3951 if (file.IsNull()) {
3952 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
3953 return false;
3956 int64_t count = 0;
3957 int64_t skipped = 0;
3958 int64_t failed = 0;
3959 int64_t nNow = GetTime();
3961 try {
3962 uint64_t version;
3963 file >> version;
3964 if (version != MEMPOOL_DUMP_VERSION) {
3965 return false;
3967 uint64_t num;
3968 file >> num;
3969 while (num--) {
3970 CTransactionRef tx;
3971 int64_t nTime;
3972 int64_t nFeeDelta;
3973 file >> tx;
3974 file >> nTime;
3975 file >> nFeeDelta;
3977 CAmount amountdelta = nFeeDelta;
3978 if (amountdelta) {
3979 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
3981 CValidationState state;
3982 if (nTime + nExpiryTimeout > nNow) {
3983 LOCK(cs_main);
3984 AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
3985 if (state.IsValid()) {
3986 ++count;
3987 } else {
3988 ++failed;
3990 } else {
3991 ++skipped;
3993 if (ShutdownRequested())
3994 return false;
3996 std::map<uint256, CAmount> mapDeltas;
3997 file >> mapDeltas;
3999 for (const auto& i : mapDeltas) {
4000 mempool.PrioritiseTransaction(i.first, i.second);
4002 } catch (const std::exception& e) {
4003 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4004 return false;
4007 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4008 return true;
4011 void DumpMempool(void)
4013 int64_t start = GetTimeMicros();
4015 std::map<uint256, CAmount> mapDeltas;
4016 std::vector<TxMempoolInfo> vinfo;
4019 LOCK(mempool.cs);
4020 for (const auto &i : mempool.mapDeltas) {
4021 mapDeltas[i.first] = i.second;
4023 vinfo = mempool.infoAll();
4026 int64_t mid = GetTimeMicros();
4028 try {
4029 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4030 if (!filestr) {
4031 return;
4034 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4036 uint64_t version = MEMPOOL_DUMP_VERSION;
4037 file << version;
4039 file << (uint64_t)vinfo.size();
4040 for (const auto& i : vinfo) {
4041 file << *(i.tx);
4042 file << (int64_t)i.nTime;
4043 file << (int64_t)i.nFeeDelta;
4044 mapDeltas.erase(i.tx->GetHash());
4047 file << mapDeltas;
4048 FileCommit(file.Get());
4049 file.fclose();
4050 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4051 int64_t last = GetTimeMicros();
4052 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4053 } catch (const std::exception& e) {
4054 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4058 //! Guess how far we are in the verification process at the given block index
4059 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4060 if (pindex == NULL)
4061 return 0.0;
4063 int64_t nNow = time(NULL);
4065 double fTxTotal;
4067 if (pindex->nChainTx <= data.nTxCount) {
4068 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4069 } else {
4070 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4073 return pindex->nChainTx / fTxTotal;
4076 class CMainCleanup
4078 public:
4079 CMainCleanup() {}
4080 ~CMainCleanup() {
4081 // block headers
4082 BlockMap::iterator it1 = mapBlockIndex.begin();
4083 for (; it1 != mapBlockIndex.end(); it1++)
4084 delete (*it1).second;
4085 mapBlockIndex.clear();
4087 } instance_of_cmaincleanup;