Remove/ignore tx version in utxo and undo
[bitcoinplatinum.git] / src / validation.cpp
blobbe0c9b564e150c6564ed74f6a00b733743629ded
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);
312 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
313 int expired = pool.Expire(GetTime() - age);
314 if (expired != 0) {
315 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
318 std::vector<uint256> vNoSpendsRemaining;
319 pool.TrimToSize(limit, &vNoSpendsRemaining);
320 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
321 pcoinsTip->Uncache(removed);
324 /** Convert CValidationState to a human-readable message for logging */
325 std::string FormatStateMessage(const CValidationState &state)
327 return strprintf("%s%s (code %i)",
328 state.GetRejectReason(),
329 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
330 state.GetRejectCode());
333 static bool IsCurrentForFeeEstimation()
335 AssertLockHeld(cs_main);
336 if (IsInitialBlockDownload())
337 return false;
338 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
339 return false;
340 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
341 return false;
342 return true;
345 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
346 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
347 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
349 const CTransaction& tx = *ptx;
350 const uint256 hash = tx.GetHash();
351 AssertLockHeld(cs_main);
352 if (pfMissingInputs)
353 *pfMissingInputs = false;
355 if (!CheckTransaction(tx, state))
356 return false; // state filled in by CheckTransaction
358 // Coinbase is only valid in a block, not as a loose transaction
359 if (tx.IsCoinBase())
360 return state.DoS(100, false, REJECT_INVALID, "coinbase");
362 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
363 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus());
364 if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
365 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
368 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
369 std::string reason;
370 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
371 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
373 // Only accept nLockTime-using transactions that can be mined in the next
374 // block; we don't want our mempool filled up with transactions that can't
375 // be mined yet.
376 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
377 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
379 // is it already in the memory pool?
380 if (pool.exists(hash))
381 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
383 // Check for conflicts with in-memory transactions
384 std::set<uint256> setConflicts;
386 LOCK(pool.cs); // protect pool.mapNextTx
387 BOOST_FOREACH(const CTxIn &txin, tx.vin)
389 auto itConflicting = pool.mapNextTx.find(txin.prevout);
390 if (itConflicting != pool.mapNextTx.end())
392 const CTransaction *ptxConflicting = itConflicting->second;
393 if (!setConflicts.count(ptxConflicting->GetHash()))
395 // Allow opt-out of transaction replacement by setting
396 // nSequence >= maxint-1 on all inputs.
398 // maxint-1 is picked to still allow use of nLockTime by
399 // non-replaceable transactions. All inputs rather than just one
400 // is for the sake of multi-party protocols, where we don't
401 // want a single party to be able to disable replacement.
403 // The opt-out ignores descendants as anyone relying on
404 // first-seen mempool behavior should be checking all
405 // unconfirmed ancestors anyway; doing otherwise is hopelessly
406 // insecure.
407 bool fReplacementOptOut = true;
408 if (fEnableReplacement)
410 BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
412 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
414 fReplacementOptOut = false;
415 break;
419 if (fReplacementOptOut)
420 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
422 setConflicts.insert(ptxConflicting->GetHash());
429 CCoinsView dummy;
430 CCoinsViewCache view(&dummy);
432 CAmount nValueIn = 0;
433 LockPoints lp;
435 LOCK(pool.cs);
436 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
437 view.SetBackend(viewMemPool);
439 // do we already have it?
440 bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
441 if (view.HaveCoins(hash)) {
442 if (!fHadTxInCache)
443 vHashTxnToUncache.push_back(hash);
444 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
447 // do all inputs exist?
448 // Note that this does not check for the presence of actual outputs (see the next check for that),
449 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
450 BOOST_FOREACH(const CTxIn txin, tx.vin) {
451 if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
452 vHashTxnToUncache.push_back(txin.prevout.hash);
453 if (!view.HaveCoins(txin.prevout.hash)) {
454 if (pfMissingInputs)
455 *pfMissingInputs = true;
456 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
460 // are the actual inputs available?
461 if (!view.HaveInputs(tx))
462 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
464 // Bring the best block into scope
465 view.GetBestBlock();
467 nValueIn = view.GetValueIn(tx);
469 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
470 view.SetBackend(dummy);
472 // Only accept BIP68 sequence locked transactions that can be mined in the next
473 // block; we don't want our mempool filled up with transactions that can't
474 // be mined yet.
475 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
476 // CoinsViewCache instead of create its own
477 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
478 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
481 // Check for non-standard pay-to-script-hash in inputs
482 if (fRequireStandard && !AreInputsStandard(tx, view))
483 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
485 // Check for non-standard witness in P2WSH
486 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
487 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
489 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
491 CAmount nValueOut = tx.GetValueOut();
492 CAmount nFees = nValueIn-nValueOut;
493 // nModifiedFees includes any fee deltas from PrioritiseTransaction
494 CAmount nModifiedFees = nFees;
495 pool.ApplyDelta(hash, nModifiedFees);
497 // Keep track of transactions that spend a coinbase, which we re-scan
498 // during reorgs to ensure COINBASE_MATURITY is still met.
499 bool fSpendsCoinbase = false;
500 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
501 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
502 if (coins->IsCoinBase()) {
503 fSpendsCoinbase = true;
504 break;
508 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
509 fSpendsCoinbase, nSigOpsCost, lp);
510 unsigned int nSize = entry.GetTxSize();
512 // Check that the transaction doesn't have an excessive number of
513 // sigops, making it impossible to mine. Since the coinbase transaction
514 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
515 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
516 // merely non-standard transaction.
517 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
518 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
519 strprintf("%d", nSigOpsCost));
521 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
522 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
523 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
526 // No transactions are allowed below minRelayTxFee except from disconnected blocks
527 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
528 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
531 if (nAbsurdFee && nFees > nAbsurdFee)
532 return state.Invalid(false,
533 REJECT_HIGHFEE, "absurdly-high-fee",
534 strprintf("%d > %d", nFees, nAbsurdFee));
536 // Calculate in-mempool ancestors, up to a limit.
537 CTxMemPool::setEntries setAncestors;
538 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
539 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
540 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
541 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
542 std::string errString;
543 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
544 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
547 // A transaction that spends outputs that would be replaced by it is invalid. Now
548 // that we have the set of all ancestors we can detect this
549 // pathological case by making sure setConflicts and setAncestors don't
550 // intersect.
551 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
553 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
554 if (setConflicts.count(hashAncestor))
556 return state.DoS(10, false,
557 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
558 strprintf("%s spends conflicting transaction %s",
559 hash.ToString(),
560 hashAncestor.ToString()));
564 // Check if it's economically rational to mine this transaction rather
565 // than the ones it replaces.
566 CAmount nConflictingFees = 0;
567 size_t nConflictingSize = 0;
568 uint64_t nConflictingCount = 0;
569 CTxMemPool::setEntries allConflicting;
571 // If we don't hold the lock allConflicting might be incomplete; the
572 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
573 // mempool consistency for us.
574 LOCK(pool.cs);
575 const bool fReplacementTransaction = setConflicts.size();
576 if (fReplacementTransaction)
578 CFeeRate newFeeRate(nModifiedFees, nSize);
579 std::set<uint256> setConflictsParents;
580 const int maxDescendantsToVisit = 100;
581 CTxMemPool::setEntries setIterConflicting;
582 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
584 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
585 if (mi == pool.mapTx.end())
586 continue;
588 // Save these to avoid repeated lookups
589 setIterConflicting.insert(mi);
591 // Don't allow the replacement to reduce the feerate of the
592 // mempool.
594 // We usually don't want to accept replacements with lower
595 // feerates than what they replaced as that would lower the
596 // feerate of the next block. Requiring that the feerate always
597 // be increased is also an easy-to-reason about way to prevent
598 // DoS attacks via replacements.
600 // The mining code doesn't (currently) take children into
601 // account (CPFP) so we only consider the feerates of
602 // transactions being directly replaced, not their indirect
603 // descendants. While that does mean high feerate children are
604 // ignored when deciding whether or not to replace, we do
605 // require the replacement to pay more overall fees too,
606 // mitigating most cases.
607 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
608 if (newFeeRate <= oldFeeRate)
610 return state.DoS(0, false,
611 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
612 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
613 hash.ToString(),
614 newFeeRate.ToString(),
615 oldFeeRate.ToString()));
618 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
620 setConflictsParents.insert(txin.prevout.hash);
623 nConflictingCount += mi->GetCountWithDescendants();
625 // This potentially overestimates the number of actual descendants
626 // but we just want to be conservative to avoid doing too much
627 // work.
628 if (nConflictingCount <= maxDescendantsToVisit) {
629 // If not too many to replace, then calculate the set of
630 // transactions that would have to be evicted
631 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
632 pool.CalculateDescendants(it, allConflicting);
634 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
635 nConflictingFees += it->GetModifiedFee();
636 nConflictingSize += it->GetTxSize();
638 } else {
639 return state.DoS(0, false,
640 REJECT_NONSTANDARD, "too many potential replacements", false,
641 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
642 hash.ToString(),
643 nConflictingCount,
644 maxDescendantsToVisit));
647 for (unsigned int j = 0; j < tx.vin.size(); j++)
649 // We don't want to accept replacements that require low
650 // feerate junk to be mined first. Ideally we'd keep track of
651 // the ancestor feerates and make the decision based on that,
652 // but for now requiring all new inputs to be confirmed works.
653 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
655 // Rather than check the UTXO set - potentially expensive -
656 // it's cheaper to just check if the new input refers to a
657 // tx that's in the mempool.
658 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
659 return state.DoS(0, false,
660 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
661 strprintf("replacement %s adds unconfirmed input, idx %d",
662 hash.ToString(), j));
666 // The replacement must pay greater fees than the transactions it
667 // replaces - if we did the bandwidth used by those conflicting
668 // transactions would not be paid for.
669 if (nModifiedFees < nConflictingFees)
671 return state.DoS(0, false,
672 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
673 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
674 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
677 // Finally in addition to paying more fees than the conflicts the
678 // new transaction must pay for its own bandwidth.
679 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
680 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
682 return state.DoS(0, false,
683 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
684 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
685 hash.ToString(),
686 FormatMoney(nDeltaFees),
687 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
691 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
692 if (!Params().RequireStandard()) {
693 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
696 // Check against previous transactions
697 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
698 PrecomputedTransactionData txdata(tx);
699 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
700 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
701 // need to turn both off, and compare against just turning off CLEANSTACK
702 // to see if the failure is specifically due to witness validation.
703 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
704 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
705 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
706 // Only the witness is missing, so the transaction itself may be fine.
707 state.SetCorruptionPossible();
709 return false; // state filled in by CheckInputs
712 // Check again against just the consensus-critical mandatory script
713 // verification flags, in case of bugs in the standard flags that cause
714 // transactions to pass as valid when they're actually invalid. For
715 // instance the STRICTENC flag was incorrectly allowing certain
716 // CHECKSIG NOT scripts to pass, even though they were invalid.
718 // There is a similar check in CreateNewBlock() to prevent creating
719 // invalid blocks, however allowing such transactions into the mempool
720 // can be exploited as a DoS attack.
721 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
723 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
724 __func__, hash.ToString(), FormatStateMessage(state));
727 // Remove conflicting transactions from the mempool
728 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
730 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
731 it->GetTx().GetHash().ToString(),
732 hash.ToString(),
733 FormatMoney(nModifiedFees - nConflictingFees),
734 (int)nSize - (int)nConflictingSize);
735 if (plTxnReplaced)
736 plTxnReplaced->push_back(it->GetSharedTx());
738 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
740 // This transaction should only count for fee estimation if it isn't a
741 // BIP 125 replacement transaction (may not be widely supported), the
742 // node is not behind, and the transaction is not dependent on any other
743 // transactions in the mempool.
744 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
746 // Store transaction in memory
747 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
749 // trim mempool and check if tx was trimmed
750 if (!fOverrideMempoolLimit) {
751 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
752 if (!pool.exists(hash))
753 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
757 GetMainSignals().TransactionAddedToMempool(ptx);
759 return true;
762 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
763 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
764 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
766 std::vector<uint256> vHashTxToUncache;
767 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
768 if (!res) {
769 BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
770 pcoinsTip->Uncache(hashTx);
772 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
773 CValidationState stateDummy;
774 FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
775 return res;
778 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
779 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
780 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
782 return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
785 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
786 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
788 CBlockIndex *pindexSlow = NULL;
790 LOCK(cs_main);
792 CTransactionRef ptx = mempool.get(hash);
793 if (ptx)
795 txOut = ptx;
796 return true;
799 if (fTxIndex) {
800 CDiskTxPos postx;
801 if (pblocktree->ReadTxIndex(hash, postx)) {
802 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
803 if (file.IsNull())
804 return error("%s: OpenBlockFile failed", __func__);
805 CBlockHeader header;
806 try {
807 file >> header;
808 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
809 file >> txOut;
810 } catch (const std::exception& e) {
811 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
813 hashBlock = header.GetHash();
814 if (txOut->GetHash() != hash)
815 return error("%s: txid mismatch", __func__);
816 return true;
820 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
821 int nHeight = -1;
823 const CCoinsViewCache& view = *pcoinsTip;
824 const CCoins* coins = view.AccessCoins(hash);
825 if (coins)
826 nHeight = coins->nHeight;
828 if (nHeight > 0)
829 pindexSlow = chainActive[nHeight];
832 if (pindexSlow) {
833 CBlock block;
834 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
835 for (const auto& tx : block.vtx) {
836 if (tx->GetHash() == hash) {
837 txOut = tx;
838 hashBlock = pindexSlow->GetBlockHash();
839 return true;
845 return false;
853 //////////////////////////////////////////////////////////////////////////////
855 // CBlock and CBlockIndex
858 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
860 // Open history file to append
861 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
862 if (fileout.IsNull())
863 return error("WriteBlockToDisk: OpenBlockFile failed");
865 // Write index header
866 unsigned int nSize = GetSerializeSize(fileout, block);
867 fileout << FLATDATA(messageStart) << nSize;
869 // Write block
870 long fileOutPos = ftell(fileout.Get());
871 if (fileOutPos < 0)
872 return error("WriteBlockToDisk: ftell failed");
873 pos.nPos = (unsigned int)fileOutPos;
874 fileout << block;
876 return true;
879 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
881 block.SetNull();
883 // Open history file to read
884 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
885 if (filein.IsNull())
886 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
888 // Read block
889 try {
890 filein >> block;
892 catch (const std::exception& e) {
893 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
896 // Check the header
897 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
898 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
900 return true;
903 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
905 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
906 return false;
907 if (block.GetHash() != pindex->GetBlockHash())
908 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
909 pindex->ToString(), pindex->GetBlockPos().ToString());
910 return true;
913 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
915 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
916 // Force block reward to zero when right shift is undefined.
917 if (halvings >= 64)
918 return 0;
920 CAmount nSubsidy = 50 * COIN;
921 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
922 nSubsidy >>= halvings;
923 return nSubsidy;
926 bool IsInitialBlockDownload()
928 const CChainParams& chainParams = Params();
930 // Once this function has returned false, it must remain false.
931 static std::atomic<bool> latchToFalse{false};
932 // Optimization: pre-test latch before taking the lock.
933 if (latchToFalse.load(std::memory_order_relaxed))
934 return false;
936 LOCK(cs_main);
937 if (latchToFalse.load(std::memory_order_relaxed))
938 return false;
939 if (fImporting || fReindex)
940 return true;
941 if (chainActive.Tip() == NULL)
942 return true;
943 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
944 return true;
945 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
946 return true;
947 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
948 latchToFalse.store(true, std::memory_order_relaxed);
949 return false;
952 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
954 static void AlertNotify(const std::string& strMessage)
956 uiInterface.NotifyAlertChanged();
957 std::string strCmd = GetArg("-alertnotify", "");
958 if (strCmd.empty()) return;
960 // Alert text should be plain ascii coming from a trusted source, but to
961 // be safe we first strip anything not in safeChars, then add single quotes around
962 // the whole string before passing it to the shell:
963 std::string singleQuote("'");
964 std::string safeStatus = SanitizeString(strMessage);
965 safeStatus = singleQuote+safeStatus+singleQuote;
966 boost::replace_all(strCmd, "%s", safeStatus);
968 boost::thread t(runCommand, strCmd); // thread runs free
971 void CheckForkWarningConditions()
973 AssertLockHeld(cs_main);
974 // Before we get past initial download, we cannot reliably alert about forks
975 // (we assume we don't get stuck on a fork before finishing our initial sync)
976 if (IsInitialBlockDownload())
977 return;
979 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
980 // of our head, drop it
981 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
982 pindexBestForkTip = NULL;
984 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
986 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
988 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
989 pindexBestForkBase->phashBlock->ToString() + std::string("'");
990 AlertNotify(warning);
992 if (pindexBestForkTip && pindexBestForkBase)
994 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__,
995 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
996 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
997 SetfLargeWorkForkFound(true);
999 else
1001 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1002 SetfLargeWorkInvalidChainFound(true);
1005 else
1007 SetfLargeWorkForkFound(false);
1008 SetfLargeWorkInvalidChainFound(false);
1012 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1014 AssertLockHeld(cs_main);
1015 // If we are on a fork that is sufficiently large, set a warning flag
1016 CBlockIndex* pfork = pindexNewForkTip;
1017 CBlockIndex* plonger = chainActive.Tip();
1018 while (pfork && pfork != plonger)
1020 while (plonger && plonger->nHeight > pfork->nHeight)
1021 plonger = plonger->pprev;
1022 if (pfork == plonger)
1023 break;
1024 pfork = pfork->pprev;
1027 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1028 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1029 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1030 // hash rate operating on the fork.
1031 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1032 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1033 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1034 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1035 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1036 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1038 pindexBestForkTip = pindexNewForkTip;
1039 pindexBestForkBase = pfork;
1042 CheckForkWarningConditions();
1045 void static InvalidChainFound(CBlockIndex* pindexNew)
1047 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1048 pindexBestInvalid = pindexNew;
1050 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1051 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1052 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1053 pindexNew->GetBlockTime()));
1054 CBlockIndex *tip = chainActive.Tip();
1055 assert (tip);
1056 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1057 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1058 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1059 CheckForkWarningConditions();
1062 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1063 if (!state.CorruptionPossible()) {
1064 pindex->nStatus |= BLOCK_FAILED_VALID;
1065 setDirtyBlockIndex.insert(pindex);
1066 setBlockIndexCandidates.erase(pindex);
1067 InvalidChainFound(pindex);
1071 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1073 // mark inputs spent
1074 if (!tx.IsCoinBase()) {
1075 txundo.vprevout.reserve(tx.vin.size());
1076 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1077 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1078 unsigned nPos = txin.prevout.n;
1080 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1081 assert(false);
1082 // mark an outpoint spent, and construct undo information
1083 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1084 coins->Spend(nPos);
1085 if (coins->vout.size() == 0) {
1086 CTxInUndo& undo = txundo.vprevout.back();
1087 undo.nHeight = coins->nHeight;
1088 undo.fCoinBase = coins->fCoinBase;
1092 // add outputs
1093 inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1096 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1098 CTxUndo txundo;
1099 UpdateCoins(tx, inputs, txundo, nHeight);
1102 bool CScriptCheck::operator()() {
1103 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1104 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1105 return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1108 int GetSpendHeight(const CCoinsViewCache& inputs)
1110 LOCK(cs_main);
1111 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1112 return pindexPrev->nHeight + 1;
1115 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1117 if (!tx.IsCoinBase())
1119 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1120 return false;
1122 if (pvChecks)
1123 pvChecks->reserve(tx.vin.size());
1125 // The first loop above does all the inexpensive checks.
1126 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1127 // Helps prevent CPU exhaustion attacks.
1129 // Skip script verification when connecting blocks under the
1130 // assumevalid block. Assuming the assumevalid block is valid this
1131 // is safe because block merkle hashes are still computed and checked,
1132 // Of course, if an assumed valid block is invalid due to false scriptSigs
1133 // this optimization would allow an invalid chain to be accepted.
1134 if (fScriptChecks) {
1135 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1136 const COutPoint &prevout = tx.vin[i].prevout;
1137 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1138 assert(coins);
1140 // Verify signature
1141 CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1142 if (pvChecks) {
1143 pvChecks->push_back(CScriptCheck());
1144 check.swap(pvChecks->back());
1145 } else if (!check()) {
1146 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1147 // Check whether the failure was caused by a
1148 // non-mandatory script verification check, such as
1149 // non-standard DER encodings or non-null dummy
1150 // arguments; if so, don't trigger DoS protection to
1151 // avoid splitting the network between upgraded and
1152 // non-upgraded nodes.
1153 CScriptCheck check2(*coins, tx, i,
1154 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1155 if (check2())
1156 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1158 // Failures of other flags indicate a transaction that is
1159 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1160 // such nodes as they are not following the protocol. That
1161 // said during an upgrade careful thought should be taken
1162 // as to the correct behavior - we may want to continue
1163 // peering with non-upgraded nodes even after soft-fork
1164 // super-majority signaling has occurred.
1165 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1171 return true;
1174 namespace {
1176 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1178 // Open history file to append
1179 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1180 if (fileout.IsNull())
1181 return error("%s: OpenUndoFile failed", __func__);
1183 // Write index header
1184 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1185 fileout << FLATDATA(messageStart) << nSize;
1187 // Write undo data
1188 long fileOutPos = ftell(fileout.Get());
1189 if (fileOutPos < 0)
1190 return error("%s: ftell failed", __func__);
1191 pos.nPos = (unsigned int)fileOutPos;
1192 fileout << blockundo;
1194 // calculate & write checksum
1195 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1196 hasher << hashBlock;
1197 hasher << blockundo;
1198 fileout << hasher.GetHash();
1200 return true;
1203 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1205 // Open history file to read
1206 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1207 if (filein.IsNull())
1208 return error("%s: OpenUndoFile failed", __func__);
1210 // Read block
1211 uint256 hashChecksum;
1212 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1213 try {
1214 verifier << hashBlock;
1215 verifier >> 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 if (hashChecksum != verifier.GetHash())
1224 return error("%s: Checksum mismatch", __func__);
1226 return true;
1229 /** Abort with a message */
1230 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1232 SetMiscWarning(strMessage);
1233 LogPrintf("*** %s\n", strMessage);
1234 uiInterface.ThreadSafeMessageBox(
1235 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1236 "", CClientUIInterface::MSG_ERROR);
1237 StartShutdown();
1238 return false;
1241 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1243 AbortNode(strMessage, userMessage);
1244 return state.Error(strMessage);
1247 } // anon namespace
1249 enum DisconnectResult
1251 DISCONNECT_OK, // All good.
1252 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1253 DISCONNECT_FAILED // Something else went wrong.
1257 * Apply the undo operation of a CTxInUndo to the given chain state.
1258 * @param undo The undo object.
1259 * @param view The coins view to which to apply the changes.
1260 * @param out The out point that corresponds to the tx input.
1261 * @return A DisconnectResult as an int
1263 int ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1265 bool fClean = true;
1267 CCoinsModifier coins = view.ModifyCoins(out.hash);
1268 if (undo.nHeight != 0) {
1269 // undo data contains height: this is the last output of the prevout tx being spent
1270 if (!coins->IsPruned()) fClean = false; // overwriting existing transaction
1271 coins->fCoinBase = undo.fCoinBase;
1272 coins->nHeight = undo.nHeight;
1273 } else {
1274 if (coins->IsPruned()) fClean = false; // adding output to missing transaction
1276 if (coins->IsAvailable(out.n)) fClean = false; // overwriting existing output
1277 if (coins->vout.size() < out.n+1)
1278 coins->vout.resize(out.n+1);
1279 coins->vout[out.n] = undo.txout;
1281 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1284 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1285 * When UNCLEAN or FAILED is returned, view is left in an indeterminate state. */
1286 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1288 assert(pindex->GetBlockHash() == view.GetBestBlock());
1290 bool fClean = true;
1292 CBlockUndo blockUndo;
1293 CDiskBlockPos pos = pindex->GetUndoPos();
1294 if (pos.IsNull()) {
1295 error("DisconnectBlock(): no undo data available");
1296 return DISCONNECT_FAILED;
1298 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1299 error("DisconnectBlock(): failure reading undo data");
1300 return DISCONNECT_FAILED;
1303 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1304 error("DisconnectBlock(): block and undo data inconsistent");
1305 return DISCONNECT_FAILED;
1308 // undo transactions in reverse order
1309 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1310 const CTransaction &tx = *(block.vtx[i]);
1311 uint256 hash = tx.GetHash();
1313 // Check that all outputs are available and match the outputs in the block itself
1314 // exactly.
1316 CCoinsModifier outs = view.ModifyCoins(hash);
1317 outs->ClearUnspendable();
1319 CCoins outsBlock(tx, pindex->nHeight);
1320 if (*outs != outsBlock) fClean = false; // transaction mismatch
1322 // remove outputs
1323 outs->Clear();
1326 // restore inputs
1327 if (i > 0) { // not coinbases
1328 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1329 if (txundo.vprevout.size() != tx.vin.size()) {
1330 error("DisconnectBlock(): transaction and undo data inconsistent");
1331 return DISCONNECT_FAILED;
1333 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1334 const COutPoint &out = tx.vin[j].prevout;
1335 const CTxInUndo &undo = txundo.vprevout[j];
1336 int res = ApplyTxInUndo(undo, view, out);
1337 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1338 fClean = fClean && res != DISCONNECT_UNCLEAN;
1343 // move best block pointer to prevout block
1344 view.SetBestBlock(pindex->pprev->GetBlockHash());
1346 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1349 void static FlushBlockFile(bool fFinalize = false)
1351 LOCK(cs_LastBlockFile);
1353 CDiskBlockPos posOld(nLastBlockFile, 0);
1355 FILE *fileOld = OpenBlockFile(posOld);
1356 if (fileOld) {
1357 if (fFinalize)
1358 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1359 FileCommit(fileOld);
1360 fclose(fileOld);
1363 fileOld = OpenUndoFile(posOld);
1364 if (fileOld) {
1365 if (fFinalize)
1366 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1367 FileCommit(fileOld);
1368 fclose(fileOld);
1372 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1374 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1376 void ThreadScriptCheck() {
1377 RenameThread("bitcoin-scriptch");
1378 scriptcheckqueue.Thread();
1381 // Protected by cs_main
1382 VersionBitsCache versionbitscache;
1384 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1386 LOCK(cs_main);
1387 int32_t nVersion = VERSIONBITS_TOP_BITS;
1389 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1390 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1391 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1392 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1396 return nVersion;
1400 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1402 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1404 private:
1405 int bit;
1407 public:
1408 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1410 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1411 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1412 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1413 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1415 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1417 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1418 ((pindex->nVersion >> bit) & 1) != 0 &&
1419 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1423 // Protected by cs_main
1424 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1426 static int64_t nTimeCheck = 0;
1427 static int64_t nTimeForks = 0;
1428 static int64_t nTimeVerify = 0;
1429 static int64_t nTimeConnect = 0;
1430 static int64_t nTimeIndex = 0;
1431 static int64_t nTimeCallbacks = 0;
1432 static int64_t nTimeTotal = 0;
1434 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1435 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1436 * can fail if those validity checks fail (among other reasons). */
1437 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1438 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1440 AssertLockHeld(cs_main);
1441 assert(pindex);
1442 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1443 assert((pindex->phashBlock == NULL) ||
1444 (*pindex->phashBlock == block.GetHash()));
1445 int64_t nTimeStart = GetTimeMicros();
1447 // Check it again in case a previous version let a bad block in
1448 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1449 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1451 // verify that the view's current state corresponds to the previous block
1452 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1453 assert(hashPrevBlock == view.GetBestBlock());
1455 // Special case for the genesis block, skipping connection of its transactions
1456 // (its coinbase is unspendable)
1457 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1458 if (!fJustCheck)
1459 view.SetBestBlock(pindex->GetBlockHash());
1460 return true;
1463 bool fScriptChecks = true;
1464 if (!hashAssumeValid.IsNull()) {
1465 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1466 // A suitable default value is included with the software and updated from time to time. Because validity
1467 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1468 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1469 // effectively caching the result of part of the verification.
1470 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1471 if (it != mapBlockIndex.end()) {
1472 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1473 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1474 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1475 // This block is a member of the assumed verified chain and an ancestor of the best header.
1476 // The equivalent time check discourages hash power from extorting the network via DOS attack
1477 // into accepting an invalid block through telling users they must manually set assumevalid.
1478 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1479 // it hard to hide the implication of the demand. This also avoids having release candidates
1480 // that are hardly doing any signature verification at all in testing without having to
1481 // artificially set the default assumed verified block further back.
1482 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1483 // least as good as the expected chain.
1484 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1489 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1490 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1492 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1493 // unless those are already completely spent.
1494 // If such overwrites are allowed, coinbases and transactions depending upon those
1495 // can be duplicated to remove the ability to spend the first instance -- even after
1496 // being sent to another address.
1497 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1498 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1499 // already refuses previously-known transaction ids entirely.
1500 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1501 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1502 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1503 // initial block download.
1504 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1505 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1506 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1508 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1509 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1510 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1511 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1512 // duplicate transactions descending from the known pairs either.
1513 // 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.
1514 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1515 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1516 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1518 if (fEnforceBIP30) {
1519 for (const auto& tx : block.vtx) {
1520 const CCoins* coins = view.AccessCoins(tx->GetHash());
1521 if (coins && !coins->IsPruned())
1522 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1523 REJECT_INVALID, "bad-txns-BIP30");
1527 // BIP16 didn't become active until Apr 1 2012
1528 int64_t nBIP16SwitchTime = 1333238400;
1529 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1531 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1533 // Start enforcing the DERSIG (BIP66) rule
1534 if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
1535 flags |= SCRIPT_VERIFY_DERSIG;
1538 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1539 if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
1540 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1543 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1544 int nLockTimeFlags = 0;
1545 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1546 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1547 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1550 // Start enforcing WITNESS rules using versionbits logic.
1551 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) {
1552 flags |= SCRIPT_VERIFY_WITNESS;
1553 flags |= SCRIPT_VERIFY_NULLDUMMY;
1556 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1557 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1559 CBlockUndo blockundo;
1561 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1563 std::vector<int> prevheights;
1564 CAmount nFees = 0;
1565 int nInputs = 0;
1566 int64_t nSigOpsCost = 0;
1567 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1568 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1569 vPos.reserve(block.vtx.size());
1570 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1571 std::vector<PrecomputedTransactionData> txdata;
1572 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1573 for (unsigned int i = 0; i < block.vtx.size(); i++)
1575 const CTransaction &tx = *(block.vtx[i]);
1577 nInputs += tx.vin.size();
1579 if (!tx.IsCoinBase())
1581 if (!view.HaveInputs(tx))
1582 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1583 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1585 // Check that transaction is BIP68 final
1586 // BIP68 lock checks (as opposed to nLockTime checks) must
1587 // be in ConnectBlock because they require the UTXO set
1588 prevheights.resize(tx.vin.size());
1589 for (size_t j = 0; j < tx.vin.size(); j++) {
1590 prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
1593 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1594 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1595 REJECT_INVALID, "bad-txns-nonfinal");
1599 // GetTransactionSigOpCost counts 3 types of sigops:
1600 // * legacy (always)
1601 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1602 // * witness (when witness enabled in flags and excludes coinbase)
1603 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1604 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1605 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1606 REJECT_INVALID, "bad-blk-sigops");
1608 txdata.emplace_back(tx);
1609 if (!tx.IsCoinBase())
1611 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1613 std::vector<CScriptCheck> vChecks;
1614 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1615 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1616 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1617 tx.GetHash().ToString(), FormatStateMessage(state));
1618 control.Add(vChecks);
1621 CTxUndo undoDummy;
1622 if (i > 0) {
1623 blockundo.vtxundo.push_back(CTxUndo());
1625 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1627 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1628 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1630 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1631 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);
1633 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1634 if (block.vtx[0]->GetValueOut() > blockReward)
1635 return state.DoS(100,
1636 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1637 block.vtx[0]->GetValueOut(), blockReward),
1638 REJECT_INVALID, "bad-cb-amount");
1640 if (!control.Wait())
1641 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1642 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1643 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);
1645 if (fJustCheck)
1646 return true;
1648 // Write undo information to disk
1649 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1651 if (pindex->GetUndoPos().IsNull()) {
1652 CDiskBlockPos _pos;
1653 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1654 return error("ConnectBlock(): FindUndoPos failed");
1655 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1656 return AbortNode(state, "Failed to write undo data");
1658 // update nUndoPos in block index
1659 pindex->nUndoPos = _pos.nPos;
1660 pindex->nStatus |= BLOCK_HAVE_UNDO;
1663 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1664 setDirtyBlockIndex.insert(pindex);
1667 if (fTxIndex)
1668 if (!pblocktree->WriteTxIndex(vPos))
1669 return AbortNode(state, "Failed to write transaction index");
1671 // add this block to the view's block chain
1672 view.SetBestBlock(pindex->GetBlockHash());
1674 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1675 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1677 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1678 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1680 return true;
1684 * Update the on-disk chain state.
1685 * The caches and indexes are flushed depending on the mode we're called with
1686 * if they're too large, if it's been a while since the last write,
1687 * or always and in all cases if we're in prune mode and are deleting files.
1689 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1690 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1691 const CChainParams& chainparams = Params();
1692 LOCK2(cs_main, cs_LastBlockFile);
1693 static int64_t nLastWrite = 0;
1694 static int64_t nLastFlush = 0;
1695 static int64_t nLastSetChain = 0;
1696 std::set<int> setFilesToPrune;
1697 bool fFlushForPrune = false;
1698 try {
1699 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1700 if (nManualPruneHeight > 0) {
1701 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1702 } else {
1703 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1704 fCheckForPruning = false;
1706 if (!setFilesToPrune.empty()) {
1707 fFlushForPrune = true;
1708 if (!fHavePruned) {
1709 pblocktree->WriteFlag("prunedblockfiles", true);
1710 fHavePruned = true;
1714 int64_t nNow = GetTimeMicros();
1715 // Avoid writing/flushing immediately after startup.
1716 if (nLastWrite == 0) {
1717 nLastWrite = nNow;
1719 if (nLastFlush == 0) {
1720 nLastFlush = nNow;
1722 if (nLastSetChain == 0) {
1723 nLastSetChain = nNow;
1725 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1726 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
1727 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1728 // 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).
1729 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::min(std::max(nTotalSpace / 2, nTotalSpace - MIN_BLOCK_COINSDB_USAGE * 1024 * 1024),
1730 std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024));
1731 // The cache is over the limit, we have to write now.
1732 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1733 // 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.
1734 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1735 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1736 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1737 // Combine all conditions that result in a full cache flush.
1738 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1739 // Write blocks and block index to disk.
1740 if (fDoFullFlush || fPeriodicWrite) {
1741 // Depend on nMinDiskSpace to ensure we can write block index
1742 if (!CheckDiskSpace(0))
1743 return state.Error("out of disk space");
1744 // First make sure all block and undo data is flushed to disk.
1745 FlushBlockFile();
1746 // Then update all block file information (which may refer to block and undo files).
1748 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1749 vFiles.reserve(setDirtyFileInfo.size());
1750 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1751 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1752 setDirtyFileInfo.erase(it++);
1754 std::vector<const CBlockIndex*> vBlocks;
1755 vBlocks.reserve(setDirtyBlockIndex.size());
1756 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1757 vBlocks.push_back(*it);
1758 setDirtyBlockIndex.erase(it++);
1760 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1761 return AbortNode(state, "Failed to write to block index database");
1764 // Finally remove any pruned files
1765 if (fFlushForPrune)
1766 UnlinkPrunedFiles(setFilesToPrune);
1767 nLastWrite = nNow;
1769 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1770 if (fDoFullFlush) {
1771 // Typical CCoins structures on disk are around 128 bytes in size.
1772 // Pushing a new one to the database can cause it to be written
1773 // twice (once in the log, and once in the tables). This is already
1774 // an overestimation, as most will delete an existing entry or
1775 // overwrite one. Still, use a conservative safety factor of 2.
1776 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
1777 return state.Error("out of disk space");
1778 // Flush the chainstate (which may refer to block index entries).
1779 if (!pcoinsTip->Flush())
1780 return AbortNode(state, "Failed to write to coin database");
1781 nLastFlush = nNow;
1783 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1784 // Update best block in wallet (so we can detect restored wallets).
1785 GetMainSignals().SetBestChain(chainActive.GetLocator());
1786 nLastSetChain = nNow;
1788 } catch (const std::runtime_error& e) {
1789 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1791 return true;
1794 void FlushStateToDisk() {
1795 CValidationState state;
1796 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1799 void PruneAndFlush() {
1800 CValidationState state;
1801 fCheckForPruning = true;
1802 FlushStateToDisk(state, FLUSH_STATE_NONE);
1805 /** Update chainActive and related internal data structures. */
1806 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
1807 chainActive.SetTip(pindexNew);
1809 // New best block
1810 mempool.AddTransactionsUpdated(1);
1812 cvBlockChange.notify_all();
1814 static bool fWarned = false;
1815 std::vector<std::string> warningMessages;
1816 if (!IsInitialBlockDownload())
1818 int nUpgraded = 0;
1819 const CBlockIndex* pindex = chainActive.Tip();
1820 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
1821 WarningBitsConditionChecker checker(bit);
1822 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
1823 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
1824 if (state == THRESHOLD_ACTIVE) {
1825 std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
1826 SetMiscWarning(strWarning);
1827 if (!fWarned) {
1828 AlertNotify(strWarning);
1829 fWarned = true;
1831 } else {
1832 warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
1836 // Check the version of the last 100 blocks to see if we need to upgrade:
1837 for (int i = 0; i < 100 && pindex != NULL; i++)
1839 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
1840 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
1841 ++nUpgraded;
1842 pindex = pindex->pprev;
1844 if (nUpgraded > 0)
1845 warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
1846 if (nUpgraded > 100/2)
1848 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
1849 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1850 SetMiscWarning(strWarning);
1851 if (!fWarned) {
1852 AlertNotify(strWarning);
1853 fWarned = true;
1857 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
1858 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
1859 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1860 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1861 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
1862 if (!warningMessages.empty())
1863 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
1864 LogPrintf("\n");
1868 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
1869 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
1871 CBlockIndex *pindexDelete = chainActive.Tip();
1872 assert(pindexDelete);
1873 // Read block from disk.
1874 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
1875 CBlock& block = *pblock;
1876 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
1877 return AbortNode(state, "Failed to read block");
1878 // Apply the block atomically to the chain state.
1879 int64_t nStart = GetTimeMicros();
1881 CCoinsViewCache view(pcoinsTip);
1882 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
1883 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
1884 bool flushed = view.Flush();
1885 assert(flushed);
1887 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1888 // Write the chain state to disk, if necessary.
1889 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
1890 return false;
1892 if (!fBare) {
1893 // Resurrect mempool transactions from the disconnected block.
1894 std::vector<uint256> vHashUpdate;
1895 for (const auto& it : block.vtx) {
1896 const CTransaction& tx = *it;
1897 // ignore validation errors in resurrected transactions
1898 CValidationState stateDummy;
1899 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
1900 mempool.removeRecursive(tx, MemPoolRemovalReason::REORG);
1901 } else if (mempool.exists(tx.GetHash())) {
1902 vHashUpdate.push_back(tx.GetHash());
1905 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
1906 // no in-mempool children, which is generally not true when adding
1907 // previously-confirmed transactions back to the mempool.
1908 // UpdateTransactionsFromBlock finds descendants of any transactions in this
1909 // block that were added back and cleans up the mempool state.
1910 mempool.UpdateTransactionsFromBlock(vHashUpdate);
1913 // Update chainActive and related variables.
1914 UpdateTip(pindexDelete->pprev, chainparams);
1915 // Let wallets know transactions went from 1-confirmed to
1916 // 0-confirmed or conflicted:
1917 GetMainSignals().BlockDisconnected(pblock);
1918 return true;
1921 static int64_t nTimeReadFromDisk = 0;
1922 static int64_t nTimeConnectTotal = 0;
1923 static int64_t nTimeFlush = 0;
1924 static int64_t nTimeChainState = 0;
1925 static int64_t nTimePostConnect = 0;
1927 struct PerBlockConnectTrace {
1928 CBlockIndex* pindex = NULL;
1929 std::shared_ptr<const CBlock> pblock;
1930 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
1931 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
1934 * Used to track blocks whose transactions were applied to the UTXO state as a
1935 * part of a single ActivateBestChainStep call.
1937 * This class also tracks transactions that are removed from the mempool as
1938 * conflicts (per block) and can be used to pass all those transactions
1939 * through SyncTransaction.
1941 * This class assumes (and asserts) that the conflicted transactions for a given
1942 * block are added via mempool callbacks prior to the BlockConnected() associated
1943 * with those transactions. If any transactions are marked conflicted, it is
1944 * assumed that an associated block will always be added.
1946 * This class is single-use, once you call GetBlocksConnected() you have to throw
1947 * it away and make a new one.
1949 class ConnectTrace {
1950 private:
1951 std::vector<PerBlockConnectTrace> blocksConnected;
1952 CTxMemPool &pool;
1954 public:
1955 ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
1956 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
1959 ~ConnectTrace() {
1960 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
1963 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
1964 assert(!blocksConnected.back().pindex);
1965 assert(pindex);
1966 assert(pblock);
1967 blocksConnected.back().pindex = pindex;
1968 blocksConnected.back().pblock = std::move(pblock);
1969 blocksConnected.emplace_back();
1972 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
1973 // We always keep one extra block at the end of our list because
1974 // blocks are added after all the conflicted transactions have
1975 // been filled in. Thus, the last entry should always be an empty
1976 // one waiting for the transactions from the next block. We pop
1977 // the last entry here to make sure the list we return is sane.
1978 assert(!blocksConnected.back().pindex);
1979 assert(blocksConnected.back().conflictedTxs->empty());
1980 blocksConnected.pop_back();
1981 return blocksConnected;
1984 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
1985 assert(!blocksConnected.back().pindex);
1986 if (reason == MemPoolRemovalReason::CONFLICT) {
1987 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
1993 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
1994 * corresponding to pindexNew, to bypass loading it again from disk.
1996 * The block is added to connectTrace if connection succeeds.
1998 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2000 assert(pindexNew->pprev == chainActive.Tip());
2001 // Read block from disk.
2002 int64_t nTime1 = GetTimeMicros();
2003 std::shared_ptr<const CBlock> pthisBlock;
2004 if (!pblock) {
2005 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2006 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2007 return AbortNode(state, "Failed to read block");
2008 pthisBlock = pblockNew;
2009 } else {
2010 pthisBlock = pblock;
2012 const CBlock& blockConnecting = *pthisBlock;
2013 // Apply the block atomically to the chain state.
2014 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2015 int64_t nTime3;
2016 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2018 CCoinsViewCache view(pcoinsTip);
2019 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2020 GetMainSignals().BlockChecked(blockConnecting, state);
2021 if (!rv) {
2022 if (state.IsInvalid())
2023 InvalidBlockFound(pindexNew, state);
2024 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2026 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2027 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2028 bool flushed = view.Flush();
2029 assert(flushed);
2031 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2032 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2033 // Write the chain state to disk, if necessary.
2034 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2035 return false;
2036 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2037 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2038 // Remove conflicting transactions from the mempool.;
2039 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2040 // Update chainActive & related variables.
2041 UpdateTip(pindexNew, chainparams);
2043 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2044 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2045 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2047 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2048 return true;
2052 * Return the tip of the chain with the most work in it, that isn't
2053 * known to be invalid (it's however far from certain to be valid).
2055 static CBlockIndex* FindMostWorkChain() {
2056 do {
2057 CBlockIndex *pindexNew = NULL;
2059 // Find the best candidate header.
2061 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2062 if (it == setBlockIndexCandidates.rend())
2063 return NULL;
2064 pindexNew = *it;
2067 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2068 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2069 CBlockIndex *pindexTest = pindexNew;
2070 bool fInvalidAncestor = false;
2071 while (pindexTest && !chainActive.Contains(pindexTest)) {
2072 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2074 // Pruned nodes may have entries in setBlockIndexCandidates for
2075 // which block files have been deleted. Remove those as candidates
2076 // for the most work chain if we come across them; we can't switch
2077 // to a chain unless we have all the non-active-chain parent blocks.
2078 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2079 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2080 if (fFailedChain || fMissingData) {
2081 // Candidate chain is not usable (either invalid or missing data)
2082 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2083 pindexBestInvalid = pindexNew;
2084 CBlockIndex *pindexFailed = pindexNew;
2085 // Remove the entire chain from the set.
2086 while (pindexTest != pindexFailed) {
2087 if (fFailedChain) {
2088 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2089 } else if (fMissingData) {
2090 // If we're missing data, then add back to mapBlocksUnlinked,
2091 // so that if the block arrives in the future we can try adding
2092 // to setBlockIndexCandidates again.
2093 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2095 setBlockIndexCandidates.erase(pindexFailed);
2096 pindexFailed = pindexFailed->pprev;
2098 setBlockIndexCandidates.erase(pindexTest);
2099 fInvalidAncestor = true;
2100 break;
2102 pindexTest = pindexTest->pprev;
2104 if (!fInvalidAncestor)
2105 return pindexNew;
2106 } while(true);
2109 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2110 static void PruneBlockIndexCandidates() {
2111 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2112 // reorganization to a better block fails.
2113 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2114 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2115 setBlockIndexCandidates.erase(it++);
2117 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2118 assert(!setBlockIndexCandidates.empty());
2122 * Try to make some progress towards making pindexMostWork the active block.
2123 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2125 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2127 AssertLockHeld(cs_main);
2128 const CBlockIndex *pindexOldTip = chainActive.Tip();
2129 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2131 // Disconnect active blocks which are no longer in the best chain.
2132 bool fBlocksDisconnected = false;
2133 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2134 if (!DisconnectTip(state, chainparams))
2135 return false;
2136 fBlocksDisconnected = true;
2139 // Build list of new blocks to connect.
2140 std::vector<CBlockIndex*> vpindexToConnect;
2141 bool fContinue = true;
2142 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2143 while (fContinue && nHeight != pindexMostWork->nHeight) {
2144 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2145 // a few blocks along the way.
2146 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2147 vpindexToConnect.clear();
2148 vpindexToConnect.reserve(nTargetHeight - nHeight);
2149 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2150 while (pindexIter && pindexIter->nHeight != nHeight) {
2151 vpindexToConnect.push_back(pindexIter);
2152 pindexIter = pindexIter->pprev;
2154 nHeight = nTargetHeight;
2156 // Connect new blocks.
2157 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2158 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2159 if (state.IsInvalid()) {
2160 // The block violates a consensus rule.
2161 if (!state.CorruptionPossible())
2162 InvalidChainFound(vpindexToConnect.back());
2163 state = CValidationState();
2164 fInvalidFound = true;
2165 fContinue = false;
2166 break;
2167 } else {
2168 // A system error occurred (disk space, database error, ...).
2169 return false;
2171 } else {
2172 PruneBlockIndexCandidates();
2173 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2174 // We're in a better position than we were. Return temporarily to release the lock.
2175 fContinue = false;
2176 break;
2182 if (fBlocksDisconnected) {
2183 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2184 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2186 mempool.check(pcoinsTip);
2188 // Callbacks/notifications for a new best chain.
2189 if (fInvalidFound)
2190 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2191 else
2192 CheckForkWarningConditions();
2194 return true;
2197 static void NotifyHeaderTip() {
2198 bool fNotify = false;
2199 bool fInitialBlockDownload = false;
2200 static CBlockIndex* pindexHeaderOld = NULL;
2201 CBlockIndex* pindexHeader = NULL;
2203 LOCK(cs_main);
2204 pindexHeader = pindexBestHeader;
2206 if (pindexHeader != pindexHeaderOld) {
2207 fNotify = true;
2208 fInitialBlockDownload = IsInitialBlockDownload();
2209 pindexHeaderOld = pindexHeader;
2212 // Send block tip changed notifications without cs_main
2213 if (fNotify) {
2214 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2219 * Make the best chain active, in multiple steps. The result is either failure
2220 * or an activated best chain. pblock is either NULL or a pointer to a block
2221 * that is already loaded (to avoid loading it again from disk).
2223 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2224 // Note that while we're often called here from ProcessNewBlock, this is
2225 // far from a guarantee. Things in the P2P/RPC will often end up calling
2226 // us in the middle of ProcessNewBlock - do not assume pblock is set
2227 // sanely for performance or correctness!
2229 CBlockIndex *pindexMostWork = NULL;
2230 CBlockIndex *pindexNewTip = NULL;
2231 do {
2232 boost::this_thread::interruption_point();
2233 if (ShutdownRequested())
2234 break;
2236 const CBlockIndex *pindexFork;
2237 bool fInitialDownload;
2239 LOCK(cs_main);
2240 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2242 CBlockIndex *pindexOldTip = chainActive.Tip();
2243 if (pindexMostWork == NULL) {
2244 pindexMostWork = FindMostWorkChain();
2247 // Whether we have anything to do at all.
2248 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2249 return true;
2251 bool fInvalidFound = false;
2252 std::shared_ptr<const CBlock> nullBlockPtr;
2253 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2254 return false;
2256 if (fInvalidFound) {
2257 // Wipe cache, we may need another branch now.
2258 pindexMostWork = NULL;
2260 pindexNewTip = chainActive.Tip();
2261 pindexFork = chainActive.FindFork(pindexOldTip);
2262 fInitialDownload = IsInitialBlockDownload();
2264 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2265 assert(trace.pblock && trace.pindex);
2266 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2269 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2271 // Notifications/callbacks that can run without cs_main
2273 // Notify external listeners about the new tip.
2274 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2276 // Always notify the UI if a new block tip was connected
2277 if (pindexFork != pindexNewTip) {
2278 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2280 } while (pindexNewTip != pindexMostWork);
2281 CheckBlockIndex(chainparams.GetConsensus());
2283 // Write changes periodically to disk, after relay.
2284 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2285 return false;
2288 int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2289 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2291 return true;
2295 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2298 LOCK(cs_main);
2299 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2300 // Nothing to do, this block is not at the tip.
2301 return true;
2303 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2304 // The chain has been extended since the last call, reset the counter.
2305 nBlockReverseSequenceId = -1;
2307 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2308 setBlockIndexCandidates.erase(pindex);
2309 pindex->nSequenceId = nBlockReverseSequenceId;
2310 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2311 // We can't keep reducing the counter if somebody really wants to
2312 // call preciousblock 2**31-1 times on the same set of tips...
2313 nBlockReverseSequenceId--;
2315 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2316 setBlockIndexCandidates.insert(pindex);
2317 PruneBlockIndexCandidates();
2321 return ActivateBestChain(state, params);
2324 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2326 AssertLockHeld(cs_main);
2328 // Mark the block itself as invalid.
2329 pindex->nStatus |= BLOCK_FAILED_VALID;
2330 setDirtyBlockIndex.insert(pindex);
2331 setBlockIndexCandidates.erase(pindex);
2333 while (chainActive.Contains(pindex)) {
2334 CBlockIndex *pindexWalk = chainActive.Tip();
2335 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2336 setDirtyBlockIndex.insert(pindexWalk);
2337 setBlockIndexCandidates.erase(pindexWalk);
2338 // ActivateBestChain considers blocks already in chainActive
2339 // unconditionally valid already, so force disconnect away from it.
2340 if (!DisconnectTip(state, chainparams)) {
2341 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2342 return false;
2346 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2348 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2349 // add it again.
2350 BlockMap::iterator it = mapBlockIndex.begin();
2351 while (it != mapBlockIndex.end()) {
2352 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2353 setBlockIndexCandidates.insert(it->second);
2355 it++;
2358 InvalidChainFound(pindex);
2359 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2360 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2361 return true;
2364 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2365 AssertLockHeld(cs_main);
2367 int nHeight = pindex->nHeight;
2369 // Remove the invalidity flag from this block and all its descendants.
2370 BlockMap::iterator it = mapBlockIndex.begin();
2371 while (it != mapBlockIndex.end()) {
2372 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2373 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2374 setDirtyBlockIndex.insert(it->second);
2375 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2376 setBlockIndexCandidates.insert(it->second);
2378 if (it->second == pindexBestInvalid) {
2379 // Reset invalid block marker if it was pointing to one of those.
2380 pindexBestInvalid = NULL;
2383 it++;
2386 // Remove the invalidity flag from all ancestors too.
2387 while (pindex != NULL) {
2388 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2389 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2390 setDirtyBlockIndex.insert(pindex);
2392 pindex = pindex->pprev;
2394 return true;
2397 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2399 // Check for duplicate
2400 uint256 hash = block.GetHash();
2401 BlockMap::iterator it = mapBlockIndex.find(hash);
2402 if (it != mapBlockIndex.end())
2403 return it->second;
2405 // Construct new block index object
2406 CBlockIndex* pindexNew = new CBlockIndex(block);
2407 assert(pindexNew);
2408 // We assign the sequence id to blocks only when the full data is available,
2409 // to avoid miners withholding blocks but broadcasting headers, to get a
2410 // competitive advantage.
2411 pindexNew->nSequenceId = 0;
2412 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2413 pindexNew->phashBlock = &((*mi).first);
2414 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2415 if (miPrev != mapBlockIndex.end())
2417 pindexNew->pprev = (*miPrev).second;
2418 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2419 pindexNew->BuildSkip();
2421 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2422 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2423 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2424 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2425 pindexBestHeader = pindexNew;
2427 setDirtyBlockIndex.insert(pindexNew);
2429 return pindexNew;
2432 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2433 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2435 pindexNew->nTx = block.vtx.size();
2436 pindexNew->nChainTx = 0;
2437 pindexNew->nFile = pos.nFile;
2438 pindexNew->nDataPos = pos.nPos;
2439 pindexNew->nUndoPos = 0;
2440 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2441 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2442 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2444 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2445 setDirtyBlockIndex.insert(pindexNew);
2447 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2448 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2449 std::deque<CBlockIndex*> queue;
2450 queue.push_back(pindexNew);
2452 // Recursively process any descendant blocks that now may be eligible to be connected.
2453 while (!queue.empty()) {
2454 CBlockIndex *pindex = queue.front();
2455 queue.pop_front();
2456 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2458 LOCK(cs_nBlockSequenceId);
2459 pindex->nSequenceId = nBlockSequenceId++;
2461 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2462 setBlockIndexCandidates.insert(pindex);
2464 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2465 while (range.first != range.second) {
2466 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2467 queue.push_back(it->second);
2468 range.first++;
2469 mapBlocksUnlinked.erase(it);
2472 } else {
2473 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2474 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2478 return true;
2481 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2483 LOCK(cs_LastBlockFile);
2485 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2486 if (vinfoBlockFile.size() <= nFile) {
2487 vinfoBlockFile.resize(nFile + 1);
2490 if (!fKnown) {
2491 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2492 nFile++;
2493 if (vinfoBlockFile.size() <= nFile) {
2494 vinfoBlockFile.resize(nFile + 1);
2497 pos.nFile = nFile;
2498 pos.nPos = vinfoBlockFile[nFile].nSize;
2501 if ((int)nFile != nLastBlockFile) {
2502 if (!fKnown) {
2503 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2505 FlushBlockFile(!fKnown);
2506 nLastBlockFile = nFile;
2509 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2510 if (fKnown)
2511 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2512 else
2513 vinfoBlockFile[nFile].nSize += nAddSize;
2515 if (!fKnown) {
2516 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2517 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2518 if (nNewChunks > nOldChunks) {
2519 if (fPruneMode)
2520 fCheckForPruning = true;
2521 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2522 FILE *file = OpenBlockFile(pos);
2523 if (file) {
2524 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2525 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2526 fclose(file);
2529 else
2530 return state.Error("out of disk space");
2534 setDirtyFileInfo.insert(nFile);
2535 return true;
2538 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2540 pos.nFile = nFile;
2542 LOCK(cs_LastBlockFile);
2544 unsigned int nNewSize;
2545 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2546 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2547 setDirtyFileInfo.insert(nFile);
2549 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2550 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2551 if (nNewChunks > nOldChunks) {
2552 if (fPruneMode)
2553 fCheckForPruning = true;
2554 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2555 FILE *file = OpenUndoFile(pos);
2556 if (file) {
2557 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2558 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2559 fclose(file);
2562 else
2563 return state.Error("out of disk space");
2566 return true;
2569 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW)
2571 // Check proof of work matches claimed amount
2572 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2573 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2575 return true;
2578 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2580 // These are checks that are independent of context.
2582 if (block.fChecked)
2583 return true;
2585 // Check that the header is valid (particularly PoW). This is mostly
2586 // redundant with the call in AcceptBlockHeader.
2587 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2588 return false;
2590 // Check the merkle root.
2591 if (fCheckMerkleRoot) {
2592 bool mutated;
2593 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2594 if (block.hashMerkleRoot != hashMerkleRoot2)
2595 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2597 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2598 // of transactions in a block without affecting the merkle root of a block,
2599 // while still invalidating it.
2600 if (mutated)
2601 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2604 // All potential-corruption validation must be done before we do any
2605 // transaction validation, as otherwise we may mark the header as invalid
2606 // because we receive the wrong transactions for it.
2607 // Note that witness malleability is checked in ContextualCheckBlock, so no
2608 // checks that use witness data may be performed here.
2610 // Size limits
2611 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)
2612 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2614 // First transaction must be coinbase, the rest must not be
2615 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2616 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2617 for (unsigned int i = 1; i < block.vtx.size(); i++)
2618 if (block.vtx[i]->IsCoinBase())
2619 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2621 // Check transactions
2622 for (const auto& tx : block.vtx)
2623 if (!CheckTransaction(*tx, state, false))
2624 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2625 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2627 unsigned int nSigOps = 0;
2628 for (const auto& tx : block.vtx)
2630 nSigOps += GetLegacySigOpCount(*tx);
2632 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2633 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2635 if (fCheckPOW && fCheckMerkleRoot)
2636 block.fChecked = true;
2638 return true;
2641 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2643 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2644 return true;
2646 int nHeight = pindexPrev->nHeight+1;
2647 // Don't accept any forks from the main chain prior to last checkpoint.
2648 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2649 // MapBlockIndex.
2650 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2651 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2652 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2654 return true;
2657 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2659 LOCK(cs_main);
2660 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2663 // Compute at which vout of the block's coinbase transaction the witness
2664 // commitment occurs, or -1 if not found.
2665 static int GetWitnessCommitmentIndex(const CBlock& block)
2667 int commitpos = -1;
2668 if (!block.vtx.empty()) {
2669 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2670 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) {
2671 commitpos = o;
2675 return commitpos;
2678 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2680 int commitpos = GetWitnessCommitmentIndex(block);
2681 static const std::vector<unsigned char> nonce(32, 0x00);
2682 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2683 CMutableTransaction tx(*block.vtx[0]);
2684 tx.vin[0].scriptWitness.stack.resize(1);
2685 tx.vin[0].scriptWitness.stack[0] = nonce;
2686 block.vtx[0] = MakeTransactionRef(std::move(tx));
2690 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2692 std::vector<unsigned char> commitment;
2693 int commitpos = GetWitnessCommitmentIndex(block);
2694 std::vector<unsigned char> ret(32, 0x00);
2695 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2696 if (commitpos == -1) {
2697 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2698 CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2699 CTxOut out;
2700 out.nValue = 0;
2701 out.scriptPubKey.resize(38);
2702 out.scriptPubKey[0] = OP_RETURN;
2703 out.scriptPubKey[1] = 0x24;
2704 out.scriptPubKey[2] = 0xaa;
2705 out.scriptPubKey[3] = 0x21;
2706 out.scriptPubKey[4] = 0xa9;
2707 out.scriptPubKey[5] = 0xed;
2708 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2709 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2710 CMutableTransaction tx(*block.vtx[0]);
2711 tx.vout.push_back(out);
2712 block.vtx[0] = MakeTransactionRef(std::move(tx));
2715 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2716 return commitment;
2719 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2721 assert(pindexPrev != NULL);
2722 const int nHeight = pindexPrev->nHeight + 1;
2723 // Check proof of work
2724 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2725 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2727 // Check timestamp against prev
2728 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2729 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2731 // Check timestamp
2732 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2733 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2735 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2736 // check for version 2, 3 and 4 upgrades
2737 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2738 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2739 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2740 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2741 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2743 return true;
2746 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2748 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2750 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2751 int nLockTimeFlags = 0;
2752 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2753 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2756 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2757 ? pindexPrev->GetMedianTimePast()
2758 : block.GetBlockTime();
2760 // Check that all transactions are finalized
2761 for (const auto& tx : block.vtx) {
2762 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2763 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2767 // Enforce rule that the coinbase starts with serialized block height
2768 if (nHeight >= consensusParams.BIP34Height)
2770 CScript expect = CScript() << nHeight;
2771 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2772 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2773 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2777 // Validation for witness commitments.
2778 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2779 // coinbase (where 0x0000....0000 is used instead).
2780 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2781 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2782 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2783 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2784 // multiple, the last one is used.
2785 bool fHaveWitness = false;
2786 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2787 int commitpos = GetWitnessCommitmentIndex(block);
2788 if (commitpos != -1) {
2789 bool malleated = false;
2790 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2791 // The malleation check is ignored; as the transaction tree itself
2792 // already does not permit it, it is impossible to trigger in the
2793 // witness tree.
2794 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
2795 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
2797 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
2798 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
2799 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
2801 fHaveWitness = true;
2805 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
2806 if (!fHaveWitness) {
2807 for (const auto& tx : block.vtx) {
2808 if (tx->HasWitness()) {
2809 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
2814 // After the coinbase witness nonce and commitment are verified,
2815 // we can check if the block weight passes (before we've checked the
2816 // coinbase witness, it would be possible for the weight to be too
2817 // large by filling up the coinbase witness, which doesn't change
2818 // the block hash, so we couldn't mark the block as permanently
2819 // failed).
2820 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
2821 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
2824 return true;
2827 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
2829 AssertLockHeld(cs_main);
2830 // Check for duplicate
2831 uint256 hash = block.GetHash();
2832 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2833 CBlockIndex *pindex = NULL;
2834 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2836 if (miSelf != mapBlockIndex.end()) {
2837 // Block header is already known.
2838 pindex = miSelf->second;
2839 if (ppindex)
2840 *ppindex = pindex;
2841 if (pindex->nStatus & BLOCK_FAILED_MASK)
2842 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
2843 return true;
2846 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
2847 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
2849 // Get prev block index
2850 CBlockIndex* pindexPrev = NULL;
2851 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2852 if (mi == mapBlockIndex.end())
2853 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
2854 pindexPrev = (*mi).second;
2855 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2856 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2858 assert(pindexPrev);
2859 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
2860 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2862 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
2863 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
2865 if (pindex == NULL)
2866 pindex = AddToBlockIndex(block);
2868 if (ppindex)
2869 *ppindex = pindex;
2871 CheckBlockIndex(chainparams.GetConsensus());
2873 return true;
2876 // Exposed wrapper for AcceptBlockHeader
2877 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
2880 LOCK(cs_main);
2881 for (const CBlockHeader& header : headers) {
2882 CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
2883 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
2884 return false;
2886 if (ppindex) {
2887 *ppindex = pindex;
2891 NotifyHeaderTip();
2892 return true;
2895 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
2896 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
2898 const CBlock& block = *pblock;
2900 if (fNewBlock) *fNewBlock = false;
2901 AssertLockHeld(cs_main);
2903 CBlockIndex *pindexDummy = NULL;
2904 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
2906 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
2907 return false;
2909 // Try to process all requested blocks that we don't have, but only
2910 // process an unrequested block if it's new and has enough work to
2911 // advance our tip, and isn't too many blocks ahead.
2912 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
2913 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
2914 // Blocks that are too out-of-order needlessly limit the effectiveness of
2915 // pruning, because pruning will not delete block files that contain any
2916 // blocks which are too close in height to the tip. Apply this test
2917 // regardless of whether pruning is enabled; it should generally be safe to
2918 // not process unrequested blocks.
2919 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
2921 // TODO: Decouple this function from the block download logic by removing fRequested
2922 // This requires some new chain data structure to efficiently look up if a
2923 // block is in a chain leading to a candidate for best tip, despite not
2924 // being such a candidate itself.
2926 // TODO: deal better with return value and error conditions for duplicate
2927 // and unrequested blocks.
2928 if (fAlreadyHave) return true;
2929 if (!fRequested) { // If we didn't ask for it:
2930 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
2931 if (!fHasMoreWork) return true; // Don't process less-work chains
2932 if (fTooFarAhead) return true; // Block height is too high
2934 if (fNewBlock) *fNewBlock = true;
2936 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
2937 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
2938 if (state.IsInvalid() && !state.CorruptionPossible()) {
2939 pindex->nStatus |= BLOCK_FAILED_VALID;
2940 setDirtyBlockIndex.insert(pindex);
2942 return error("%s: %s", __func__, FormatStateMessage(state));
2945 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
2946 // (but if it does not build on our best tip, let the SendMessages loop relay it)
2947 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
2948 GetMainSignals().NewPoWValidBlock(pindex, pblock);
2950 int nHeight = pindex->nHeight;
2952 // Write block to history file
2953 try {
2954 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2955 CDiskBlockPos blockPos;
2956 if (dbp != NULL)
2957 blockPos = *dbp;
2958 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2959 return error("AcceptBlock(): FindBlockPos failed");
2960 if (dbp == NULL)
2961 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2962 AbortNode(state, "Failed to write block");
2963 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
2964 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2965 } catch (const std::runtime_error& e) {
2966 return AbortNode(state, std::string("System error: ") + e.what());
2969 if (fCheckForPruning)
2970 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2972 return true;
2975 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
2978 CBlockIndex *pindex = NULL;
2979 if (fNewBlock) *fNewBlock = false;
2980 CValidationState state;
2981 // Ensure that CheckBlock() passes before calling AcceptBlock, as
2982 // belt-and-suspenders.
2983 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
2985 LOCK(cs_main);
2987 if (ret) {
2988 // Store to disk
2989 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
2991 CheckBlockIndex(chainparams.GetConsensus());
2992 if (!ret) {
2993 GetMainSignals().BlockChecked(*pblock, state);
2994 return error("%s: AcceptBlock FAILED", __func__);
2998 NotifyHeaderTip();
3000 CValidationState state; // Only used to report errors, not invalidity - ignore it
3001 if (!ActivateBestChain(state, chainparams, pblock))
3002 return error("%s: ActivateBestChain failed", __func__);
3004 return true;
3007 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3009 AssertLockHeld(cs_main);
3010 assert(pindexPrev && pindexPrev == chainActive.Tip());
3011 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3012 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3014 CCoinsViewCache viewNew(pcoinsTip);
3015 CBlockIndex indexDummy(block);
3016 indexDummy.pprev = pindexPrev;
3017 indexDummy.nHeight = pindexPrev->nHeight + 1;
3019 // NOTE: CheckBlockHeader is called by CheckBlock
3020 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3021 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3022 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3023 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3024 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3025 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3026 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3027 return false;
3028 assert(state.IsValid());
3030 return true;
3034 * BLOCK PRUNING CODE
3037 /* Calculate the amount of disk space the block & undo files currently use */
3038 uint64_t CalculateCurrentUsage()
3040 uint64_t retval = 0;
3041 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3042 retval += file.nSize + file.nUndoSize;
3044 return retval;
3047 /* Prune a block file (modify associated database entries)*/
3048 void PruneOneBlockFile(const int fileNumber)
3050 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3051 CBlockIndex* pindex = it->second;
3052 if (pindex->nFile == fileNumber) {
3053 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3054 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3055 pindex->nFile = 0;
3056 pindex->nDataPos = 0;
3057 pindex->nUndoPos = 0;
3058 setDirtyBlockIndex.insert(pindex);
3060 // Prune from mapBlocksUnlinked -- any block we prune would have
3061 // to be downloaded again in order to consider its chain, at which
3062 // point it would be considered as a candidate for
3063 // mapBlocksUnlinked or setBlockIndexCandidates.
3064 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3065 while (range.first != range.second) {
3066 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3067 range.first++;
3068 if (_it->second == pindex) {
3069 mapBlocksUnlinked.erase(_it);
3075 vinfoBlockFile[fileNumber].SetNull();
3076 setDirtyFileInfo.insert(fileNumber);
3080 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3082 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3083 CDiskBlockPos pos(*it, 0);
3084 fs::remove(GetBlockPosFilename(pos, "blk"));
3085 fs::remove(GetBlockPosFilename(pos, "rev"));
3086 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3090 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3091 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3093 assert(fPruneMode && nManualPruneHeight > 0);
3095 LOCK2(cs_main, cs_LastBlockFile);
3096 if (chainActive.Tip() == NULL)
3097 return;
3099 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3100 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3101 int count=0;
3102 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3103 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3104 continue;
3105 PruneOneBlockFile(fileNumber);
3106 setFilesToPrune.insert(fileNumber);
3107 count++;
3109 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3112 /* This function is called from the RPC code for pruneblockchain */
3113 void PruneBlockFilesManual(int nManualPruneHeight)
3115 CValidationState state;
3116 FlushStateToDisk(state, FLUSH_STATE_NONE, nManualPruneHeight);
3119 /* Calculate the block/rev files that should be deleted to remain under target*/
3120 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3122 LOCK2(cs_main, cs_LastBlockFile);
3123 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3124 return;
3126 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3127 return;
3130 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3131 uint64_t nCurrentUsage = CalculateCurrentUsage();
3132 // We don't check to prune until after we've allocated new space for files
3133 // So we should leave a buffer under our target to account for another allocation
3134 // before the next pruning.
3135 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3136 uint64_t nBytesToPrune;
3137 int count=0;
3139 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3140 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3141 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3143 if (vinfoBlockFile[fileNumber].nSize == 0)
3144 continue;
3146 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3147 break;
3149 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3150 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3151 continue;
3153 PruneOneBlockFile(fileNumber);
3154 // Queue up the files for removal
3155 setFilesToPrune.insert(fileNumber);
3156 nCurrentUsage -= nBytesToPrune;
3157 count++;
3161 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3162 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3163 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3164 nLastBlockWeCanPrune, count);
3167 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3169 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3171 // Check for nMinDiskSpace bytes (currently 50MB)
3172 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3173 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3175 return true;
3178 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3180 if (pos.IsNull())
3181 return NULL;
3182 fs::path path = GetBlockPosFilename(pos, prefix);
3183 fs::create_directories(path.parent_path());
3184 FILE* file = fsbridge::fopen(path, "rb+");
3185 if (!file && !fReadOnly)
3186 file = fsbridge::fopen(path, "wb+");
3187 if (!file) {
3188 LogPrintf("Unable to open file %s\n", path.string());
3189 return NULL;
3191 if (pos.nPos) {
3192 if (fseek(file, pos.nPos, SEEK_SET)) {
3193 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3194 fclose(file);
3195 return NULL;
3198 return file;
3201 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3202 return OpenDiskFile(pos, "blk", fReadOnly);
3205 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3206 return OpenDiskFile(pos, "rev", fReadOnly);
3209 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3211 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3214 CBlockIndex * InsertBlockIndex(uint256 hash)
3216 if (hash.IsNull())
3217 return NULL;
3219 // Return existing
3220 BlockMap::iterator mi = mapBlockIndex.find(hash);
3221 if (mi != mapBlockIndex.end())
3222 return (*mi).second;
3224 // Create new
3225 CBlockIndex* pindexNew = new CBlockIndex();
3226 if (!pindexNew)
3227 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3228 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3229 pindexNew->phashBlock = &((*mi).first);
3231 return pindexNew;
3234 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3236 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3237 return false;
3239 boost::this_thread::interruption_point();
3241 // Calculate nChainWork
3242 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3243 vSortedByHeight.reserve(mapBlockIndex.size());
3244 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3246 CBlockIndex* pindex = item.second;
3247 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3249 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3250 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3252 CBlockIndex* pindex = item.second;
3253 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3254 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3255 // We can link the chain of blocks for which we've received transactions at some point.
3256 // Pruned nodes may have deleted the block.
3257 if (pindex->nTx > 0) {
3258 if (pindex->pprev) {
3259 if (pindex->pprev->nChainTx) {
3260 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3261 } else {
3262 pindex->nChainTx = 0;
3263 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3265 } else {
3266 pindex->nChainTx = pindex->nTx;
3269 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3270 setBlockIndexCandidates.insert(pindex);
3271 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3272 pindexBestInvalid = pindex;
3273 if (pindex->pprev)
3274 pindex->BuildSkip();
3275 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3276 pindexBestHeader = pindex;
3279 // Load block file info
3280 pblocktree->ReadLastBlockFile(nLastBlockFile);
3281 vinfoBlockFile.resize(nLastBlockFile + 1);
3282 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3283 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3284 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3286 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3287 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3288 CBlockFileInfo info;
3289 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3290 vinfoBlockFile.push_back(info);
3291 } else {
3292 break;
3296 // Check presence of blk files
3297 LogPrintf("Checking all blk files are present...\n");
3298 std::set<int> setBlkDataFiles;
3299 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3301 CBlockIndex* pindex = item.second;
3302 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3303 setBlkDataFiles.insert(pindex->nFile);
3306 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3308 CDiskBlockPos pos(*it, 0);
3309 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3310 return false;
3314 // Check whether we have ever pruned block & undo files
3315 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3316 if (fHavePruned)
3317 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3319 // Check whether we need to continue reindexing
3320 bool fReindexing = false;
3321 pblocktree->ReadReindexing(fReindexing);
3322 fReindex |= fReindexing;
3324 // Check whether we have a transaction index
3325 pblocktree->ReadFlag("txindex", fTxIndex);
3326 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3328 // Load pointer to end of best chain
3329 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3330 if (it == mapBlockIndex.end())
3331 return true;
3332 chainActive.SetTip(it->second);
3334 PruneBlockIndexCandidates();
3336 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3337 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3338 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3339 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3341 return true;
3344 CVerifyDB::CVerifyDB()
3346 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3349 CVerifyDB::~CVerifyDB()
3351 uiInterface.ShowProgress("", 100);
3354 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3356 LOCK(cs_main);
3357 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3358 return true;
3360 // Verify blocks in the best chain
3361 if (nCheckDepth <= 0)
3362 nCheckDepth = 1000000000; // suffices until the year 19000
3363 if (nCheckDepth > chainActive.Height())
3364 nCheckDepth = chainActive.Height();
3365 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3366 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3367 CCoinsViewCache coins(coinsview);
3368 CBlockIndex* pindexState = chainActive.Tip();
3369 CBlockIndex* pindexFailure = NULL;
3370 int nGoodTransactions = 0;
3371 CValidationState state;
3372 int reportDone = 0;
3373 LogPrintf("[0%%]...");
3374 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3376 boost::this_thread::interruption_point();
3377 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3378 if (reportDone < percentageDone/10) {
3379 // report every 10% step
3380 LogPrintf("[%d%%]...", percentageDone);
3381 reportDone = percentageDone/10;
3383 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3384 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3385 break;
3386 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3387 // If pruning, only go back as far as we have data.
3388 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3389 break;
3391 CBlock block;
3392 // check level 0: read from disk
3393 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3394 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3395 // check level 1: verify block validity
3396 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3397 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3398 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3399 // check level 2: verify undo validity
3400 if (nCheckLevel >= 2 && pindex) {
3401 CBlockUndo undo;
3402 CDiskBlockPos pos = pindex->GetUndoPos();
3403 if (!pos.IsNull()) {
3404 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3405 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3408 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3409 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3410 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3411 if (res == DISCONNECT_FAILED) {
3412 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3414 pindexState = pindex->pprev;
3415 if (res == DISCONNECT_UNCLEAN) {
3416 nGoodTransactions = 0;
3417 pindexFailure = pindex;
3418 } else {
3419 nGoodTransactions += block.vtx.size();
3422 if (ShutdownRequested())
3423 return true;
3425 if (pindexFailure)
3426 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3428 // check level 4: try reconnecting blocks
3429 if (nCheckLevel >= 4) {
3430 CBlockIndex *pindex = pindexState;
3431 while (pindex != chainActive.Tip()) {
3432 boost::this_thread::interruption_point();
3433 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3434 pindex = chainActive.Next(pindex);
3435 CBlock block;
3436 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3437 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3438 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3439 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3443 LogPrintf("[DONE].\n");
3444 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3446 return true;
3449 bool RewindBlockIndex(const CChainParams& params)
3451 LOCK(cs_main);
3453 int nHeight = 1;
3454 while (nHeight <= chainActive.Height()) {
3455 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3456 break;
3458 nHeight++;
3461 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3462 CValidationState state;
3463 CBlockIndex* pindex = chainActive.Tip();
3464 while (chainActive.Height() >= nHeight) {
3465 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3466 // If pruning, don't try rewinding past the HAVE_DATA point;
3467 // since older blocks can't be served anyway, there's
3468 // no need to walk further, and trying to DisconnectTip()
3469 // will fail (and require a needless reindex/redownload
3470 // of the blockchain).
3471 break;
3473 if (!DisconnectTip(state, params, true)) {
3474 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3476 // Occasionally flush state to disk.
3477 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3478 return false;
3481 // Reduce validity flag and have-data flags.
3482 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3483 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3484 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3485 CBlockIndex* pindexIter = it->second;
3487 // Note: If we encounter an insufficiently validated block that
3488 // is on chainActive, it must be because we are a pruning node, and
3489 // this block or some successor doesn't HAVE_DATA, so we were unable to
3490 // rewind all the way. Blocks remaining on chainActive at this point
3491 // must not have their validity reduced.
3492 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3493 // Reduce validity
3494 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3495 // Remove have-data flags.
3496 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3497 // Remove storage location.
3498 pindexIter->nFile = 0;
3499 pindexIter->nDataPos = 0;
3500 pindexIter->nUndoPos = 0;
3501 // Remove various other things
3502 pindexIter->nTx = 0;
3503 pindexIter->nChainTx = 0;
3504 pindexIter->nSequenceId = 0;
3505 // Make sure it gets written.
3506 setDirtyBlockIndex.insert(pindexIter);
3507 // Update indexes
3508 setBlockIndexCandidates.erase(pindexIter);
3509 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3510 while (ret.first != ret.second) {
3511 if (ret.first->second == pindexIter) {
3512 mapBlocksUnlinked.erase(ret.first++);
3513 } else {
3514 ++ret.first;
3517 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3518 setBlockIndexCandidates.insert(pindexIter);
3522 PruneBlockIndexCandidates();
3524 CheckBlockIndex(params.GetConsensus());
3526 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3527 return false;
3530 return true;
3533 // May NOT be used after any connections are up as much
3534 // of the peer-processing logic assumes a consistent
3535 // block index state
3536 void UnloadBlockIndex()
3538 LOCK(cs_main);
3539 setBlockIndexCandidates.clear();
3540 chainActive.SetTip(NULL);
3541 pindexBestInvalid = NULL;
3542 pindexBestHeader = NULL;
3543 mempool.clear();
3544 mapBlocksUnlinked.clear();
3545 vinfoBlockFile.clear();
3546 nLastBlockFile = 0;
3547 nBlockSequenceId = 1;
3548 setDirtyBlockIndex.clear();
3549 setDirtyFileInfo.clear();
3550 versionbitscache.Clear();
3551 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3552 warningcache[b].clear();
3555 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3556 delete entry.second;
3558 mapBlockIndex.clear();
3559 fHavePruned = false;
3562 bool LoadBlockIndex(const CChainParams& chainparams)
3564 // Load block index from databases
3565 if (!fReindex && !LoadBlockIndexDB(chainparams))
3566 return false;
3567 return true;
3570 bool InitBlockIndex(const CChainParams& chainparams)
3572 LOCK(cs_main);
3574 // Check whether we're already initialized
3575 if (chainActive.Genesis() != NULL)
3576 return true;
3578 // Use the provided setting for -txindex in the new database
3579 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3580 pblocktree->WriteFlag("txindex", fTxIndex);
3581 LogPrintf("Initializing databases...\n");
3583 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3584 if (!fReindex) {
3585 try {
3586 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3587 // Start new block file
3588 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3589 CDiskBlockPos blockPos;
3590 CValidationState state;
3591 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3592 return error("LoadBlockIndex(): FindBlockPos failed");
3593 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3594 return error("LoadBlockIndex(): writing genesis block to disk failed");
3595 CBlockIndex *pindex = AddToBlockIndex(block);
3596 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3597 return error("LoadBlockIndex(): genesis block not accepted");
3598 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3599 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3600 } catch (const std::runtime_error& e) {
3601 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3605 return true;
3608 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3610 // Map of disk positions for blocks with unknown parent (only used for reindex)
3611 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3612 int64_t nStart = GetTimeMillis();
3614 int nLoaded = 0;
3615 try {
3616 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3617 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3618 uint64_t nRewind = blkdat.GetPos();
3619 while (!blkdat.eof()) {
3620 boost::this_thread::interruption_point();
3622 blkdat.SetPos(nRewind);
3623 nRewind++; // start one byte further next time, in case of failure
3624 blkdat.SetLimit(); // remove former limit
3625 unsigned int nSize = 0;
3626 try {
3627 // locate a header
3628 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3629 blkdat.FindByte(chainparams.MessageStart()[0]);
3630 nRewind = blkdat.GetPos()+1;
3631 blkdat >> FLATDATA(buf);
3632 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3633 continue;
3634 // read size
3635 blkdat >> nSize;
3636 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3637 continue;
3638 } catch (const std::exception&) {
3639 // no valid block header found; don't complain
3640 break;
3642 try {
3643 // read block
3644 uint64_t nBlockPos = blkdat.GetPos();
3645 if (dbp)
3646 dbp->nPos = nBlockPos;
3647 blkdat.SetLimit(nBlockPos + nSize);
3648 blkdat.SetPos(nBlockPos);
3649 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3650 CBlock& block = *pblock;
3651 blkdat >> block;
3652 nRewind = blkdat.GetPos();
3654 // detect out of order blocks, and store them for later
3655 uint256 hash = block.GetHash();
3656 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3657 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3658 block.hashPrevBlock.ToString());
3659 if (dbp)
3660 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3661 continue;
3664 // process in case the block isn't known yet
3665 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3666 LOCK(cs_main);
3667 CValidationState state;
3668 if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3669 nLoaded++;
3670 if (state.IsError())
3671 break;
3672 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3673 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3676 // Activate the genesis block so normal node progress can continue
3677 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3678 CValidationState state;
3679 if (!ActivateBestChain(state, chainparams)) {
3680 break;
3684 NotifyHeaderTip();
3686 // Recursively process earlier encountered successors of this block
3687 std::deque<uint256> queue;
3688 queue.push_back(hash);
3689 while (!queue.empty()) {
3690 uint256 head = queue.front();
3691 queue.pop_front();
3692 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3693 while (range.first != range.second) {
3694 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3695 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
3696 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
3698 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
3699 head.ToString());
3700 LOCK(cs_main);
3701 CValidationState dummy;
3702 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
3704 nLoaded++;
3705 queue.push_back(pblockrecursive->GetHash());
3708 range.first++;
3709 mapBlocksUnknownParent.erase(it);
3710 NotifyHeaderTip();
3713 } catch (const std::exception& e) {
3714 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3717 } catch (const std::runtime_error& e) {
3718 AbortNode(std::string("System error: ") + e.what());
3720 if (nLoaded > 0)
3721 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3722 return nLoaded > 0;
3725 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3727 if (!fCheckBlockIndex) {
3728 return;
3731 LOCK(cs_main);
3733 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3734 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3735 // iterating the block tree require that chainActive has been initialized.)
3736 if (chainActive.Height() < 0) {
3737 assert(mapBlockIndex.size() <= 1);
3738 return;
3741 // Build forward-pointing map of the entire block tree.
3742 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3743 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3744 forward.insert(std::make_pair(it->second->pprev, it->second));
3747 assert(forward.size() == mapBlockIndex.size());
3749 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3750 CBlockIndex *pindex = rangeGenesis.first->second;
3751 rangeGenesis.first++;
3752 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3754 // Iterate over the entire block tree, using depth-first search.
3755 // Along the way, remember whether there are blocks on the path from genesis
3756 // block being explored which are the first to have certain properties.
3757 size_t nNodes = 0;
3758 int nHeight = 0;
3759 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3760 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3761 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3762 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3763 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3764 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3765 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3766 while (pindex != NULL) {
3767 nNodes++;
3768 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3769 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3770 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3771 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3772 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3773 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3774 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3776 // Begin: actual consistency checks.
3777 if (pindex->pprev == NULL) {
3778 // Genesis block checks.
3779 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3780 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3782 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)
3783 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3784 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3785 if (!fHavePruned) {
3786 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3787 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3788 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3789 } else {
3790 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3791 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3793 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3794 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3795 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3796 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3797 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3798 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3799 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.
3800 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3801 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3802 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3803 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3804 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3805 if (pindexFirstInvalid == NULL) {
3806 // Checks for not-invalid blocks.
3807 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3809 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3810 if (pindexFirstInvalid == NULL) {
3811 // If this block sorts at least as good as the current tip and
3812 // is valid and we have all data for its parents, it must be in
3813 // setBlockIndexCandidates. chainActive.Tip() must also be there
3814 // even if some data has been pruned.
3815 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3816 assert(setBlockIndexCandidates.count(pindex));
3818 // If some parent is missing, then it could be that this block was in
3819 // setBlockIndexCandidates but had to be removed because of the missing data.
3820 // In this case it must be in mapBlocksUnlinked -- see test below.
3822 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3823 assert(setBlockIndexCandidates.count(pindex) == 0);
3825 // Check whether this block is in mapBlocksUnlinked.
3826 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3827 bool foundInUnlinked = false;
3828 while (rangeUnlinked.first != rangeUnlinked.second) {
3829 assert(rangeUnlinked.first->first == pindex->pprev);
3830 if (rangeUnlinked.first->second == pindex) {
3831 foundInUnlinked = true;
3832 break;
3834 rangeUnlinked.first++;
3836 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3837 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3838 assert(foundInUnlinked);
3840 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3841 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3842 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3843 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3844 assert(fHavePruned); // We must have pruned.
3845 // This block may have entered mapBlocksUnlinked if:
3846 // - it has a descendant that at some point had more work than the
3847 // tip, and
3848 // - we tried switching to that descendant but were missing
3849 // data for some intermediate block between chainActive and the
3850 // tip.
3851 // So if this block is itself better than chainActive.Tip() and it wasn't in
3852 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3853 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3854 if (pindexFirstInvalid == NULL) {
3855 assert(foundInUnlinked);
3859 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3860 // End: actual consistency checks.
3862 // Try descending into the first subnode.
3863 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3864 if (range.first != range.second) {
3865 // A subnode was found.
3866 pindex = range.first->second;
3867 nHeight++;
3868 continue;
3870 // This is a leaf node.
3871 // Move upwards until we reach a node of which we have not yet visited the last child.
3872 while (pindex) {
3873 // We are going to either move to a parent or a sibling of pindex.
3874 // If pindex was the first with a certain property, unset the corresponding variable.
3875 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3876 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3877 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3878 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3879 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3880 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3881 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3882 // Find our parent.
3883 CBlockIndex* pindexPar = pindex->pprev;
3884 // Find which child we just visited.
3885 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3886 while (rangePar.first->second != pindex) {
3887 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3888 rangePar.first++;
3890 // Proceed to the next one.
3891 rangePar.first++;
3892 if (rangePar.first != rangePar.second) {
3893 // Move to the sibling.
3894 pindex = rangePar.first->second;
3895 break;
3896 } else {
3897 // Move up further.
3898 pindex = pindexPar;
3899 nHeight--;
3900 continue;
3905 // Check that we actually traversed the entire map.
3906 assert(nNodes == forward.size());
3909 std::string CBlockFileInfo::ToString() const
3911 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));
3914 CBlockFileInfo* GetBlockFileInfo(size_t n)
3916 return &vinfoBlockFile.at(n);
3919 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
3921 LOCK(cs_main);
3922 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
3925 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
3927 LOCK(cs_main);
3928 return VersionBitsStatistics(chainActive.Tip(), params, pos);
3931 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
3933 LOCK(cs_main);
3934 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
3937 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
3939 bool LoadMempool(void)
3941 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
3942 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
3943 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
3944 if (file.IsNull()) {
3945 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
3946 return false;
3949 int64_t count = 0;
3950 int64_t skipped = 0;
3951 int64_t failed = 0;
3952 int64_t nNow = GetTime();
3954 try {
3955 uint64_t version;
3956 file >> version;
3957 if (version != MEMPOOL_DUMP_VERSION) {
3958 return false;
3960 uint64_t num;
3961 file >> num;
3962 while (num--) {
3963 CTransactionRef tx;
3964 int64_t nTime;
3965 int64_t nFeeDelta;
3966 file >> tx;
3967 file >> nTime;
3968 file >> nFeeDelta;
3970 CAmount amountdelta = nFeeDelta;
3971 if (amountdelta) {
3972 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
3974 CValidationState state;
3975 if (nTime + nExpiryTimeout > nNow) {
3976 LOCK(cs_main);
3977 AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
3978 if (state.IsValid()) {
3979 ++count;
3980 } else {
3981 ++failed;
3983 } else {
3984 ++skipped;
3986 if (ShutdownRequested())
3987 return false;
3989 std::map<uint256, CAmount> mapDeltas;
3990 file >> mapDeltas;
3992 for (const auto& i : mapDeltas) {
3993 mempool.PrioritiseTransaction(i.first, i.second);
3995 } catch (const std::exception& e) {
3996 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
3997 return false;
4000 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4001 return true;
4004 void DumpMempool(void)
4006 int64_t start = GetTimeMicros();
4008 std::map<uint256, CAmount> mapDeltas;
4009 std::vector<TxMempoolInfo> vinfo;
4012 LOCK(mempool.cs);
4013 for (const auto &i : mempool.mapDeltas) {
4014 mapDeltas[i.first] = i.second;
4016 vinfo = mempool.infoAll();
4019 int64_t mid = GetTimeMicros();
4021 try {
4022 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4023 if (!filestr) {
4024 return;
4027 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4029 uint64_t version = MEMPOOL_DUMP_VERSION;
4030 file << version;
4032 file << (uint64_t)vinfo.size();
4033 for (const auto& i : vinfo) {
4034 file << *(i.tx);
4035 file << (int64_t)i.nTime;
4036 file << (int64_t)i.nFeeDelta;
4037 mapDeltas.erase(i.tx->GetHash());
4040 file << mapDeltas;
4041 FileCommit(file.Get());
4042 file.fclose();
4043 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4044 int64_t last = GetTimeMicros();
4045 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4046 } catch (const std::exception& e) {
4047 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4051 //! Guess how far we are in the verification process at the given block index
4052 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4053 if (pindex == NULL)
4054 return 0.0;
4056 int64_t nNow = time(NULL);
4058 double fTxTotal;
4060 if (pindex->nChainTx <= data.nTxCount) {
4061 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4062 } else {
4063 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4066 return pindex->nChainTx / fTxTotal;
4069 class CMainCleanup
4071 public:
4072 CMainCleanup() {}
4073 ~CMainCleanup() {
4074 // block headers
4075 BlockMap::iterator it1 = mapBlockIndex.begin();
4076 for (; it1 != mapBlockIndex.end(); it1++)
4077 delete (*it1).second;
4078 mapBlockIndex.clear();
4080 } instance_of_cmaincleanup;