Replace rand() & ((1 << N) - 1) with randbits(N)
[bitcoinplatinum.git] / src / validation.cpp
blobde65839eef4fea216b8ac1463cc6e09e3a7e3b06
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 Coin coin;
272 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
273 return error("%s: Missing input", __func__);
275 if (coin.nHeight == MEMPOOL_HEIGHT) {
276 // Assume all mempool transaction confirm in the next block
277 prevheights[txinIndex] = tip->nHeight + 1;
278 } else {
279 prevheights[txinIndex] = coin.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<COutPoint> vNoSpendsRemaining;
319 pool.TrimToSize(limit, &vNoSpendsRemaining);
320 BOOST_FOREACH(const COutPoint& 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 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
346 * disconnected block transactions from the mempool, and also removing any
347 * other transactions from the mempool that are no longer valid given the new
348 * tip/height.
350 * Note: we assume that disconnectpool only contains transactions that are NOT
351 * confirmed in the current chain nor already in the mempool (otherwise,
352 * in-mempool descendants of such transactions would be removed).
354 * Passing fAddToMempool=false will skip trying to add the transactions back,
355 * and instead just erase from the mempool as needed.
358 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
360 AssertLockHeld(cs_main);
361 std::vector<uint256> vHashUpdate;
362 // disconnectpool's insertion_order index sorts the entries from
363 // oldest to newest, but the oldest entry will be the last tx from the
364 // latest mined block that was disconnected.
365 // Iterate disconnectpool in reverse, so that we add transactions
366 // back to the mempool starting with the earliest transaction that had
367 // been previously seen in a block.
368 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
369 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
370 // ignore validation errors in resurrected transactions
371 CValidationState stateDummy;
372 if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, NULL, NULL, true)) {
373 // If the transaction doesn't make it in to the mempool, remove any
374 // transactions that depend on it (which would now be orphans).
375 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
376 } else if (mempool.exists((*it)->GetHash())) {
377 vHashUpdate.push_back((*it)->GetHash());
379 ++it;
381 disconnectpool.queuedTx.clear();
382 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
383 // no in-mempool children, which is generally not true when adding
384 // previously-confirmed transactions back to the mempool.
385 // UpdateTransactionsFromBlock finds descendants of any transactions in
386 // the disconnectpool that were added back and cleans up the mempool state.
387 mempool.UpdateTransactionsFromBlock(vHashUpdate);
389 // We also need to remove any now-immature transactions
390 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
391 // Re-limit mempool size, in case we added any transactions
392 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
395 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
396 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
397 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
399 const CTransaction& tx = *ptx;
400 const uint256 hash = tx.GetHash();
401 AssertLockHeld(cs_main);
402 if (pfMissingInputs)
403 *pfMissingInputs = false;
405 if (!CheckTransaction(tx, state))
406 return false; // state filled in by CheckTransaction
408 // Coinbase is only valid in a block, not as a loose transaction
409 if (tx.IsCoinBase())
410 return state.DoS(100, false, REJECT_INVALID, "coinbase");
412 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
413 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus());
414 if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
415 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
418 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
419 std::string reason;
420 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
421 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
423 // Only accept nLockTime-using transactions that can be mined in the next
424 // block; we don't want our mempool filled up with transactions that can't
425 // be mined yet.
426 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
427 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
429 // is it already in the memory pool?
430 if (pool.exists(hash))
431 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
433 // Check for conflicts with in-memory transactions
434 std::set<uint256> setConflicts;
436 LOCK(pool.cs); // protect pool.mapNextTx
437 BOOST_FOREACH(const CTxIn &txin, tx.vin)
439 auto itConflicting = pool.mapNextTx.find(txin.prevout);
440 if (itConflicting != pool.mapNextTx.end())
442 const CTransaction *ptxConflicting = itConflicting->second;
443 if (!setConflicts.count(ptxConflicting->GetHash()))
445 // Allow opt-out of transaction replacement by setting
446 // nSequence >= maxint-1 on all inputs.
448 // maxint-1 is picked to still allow use of nLockTime by
449 // non-replaceable transactions. All inputs rather than just one
450 // is for the sake of multi-party protocols, where we don't
451 // want a single party to be able to disable replacement.
453 // The opt-out ignores descendants as anyone relying on
454 // first-seen mempool behavior should be checking all
455 // unconfirmed ancestors anyway; doing otherwise is hopelessly
456 // insecure.
457 bool fReplacementOptOut = true;
458 if (fEnableReplacement)
460 BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
462 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
464 fReplacementOptOut = false;
465 break;
469 if (fReplacementOptOut)
470 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
472 setConflicts.insert(ptxConflicting->GetHash());
479 CCoinsView dummy;
480 CCoinsViewCache view(&dummy);
482 CAmount nValueIn = 0;
483 LockPoints lp;
485 LOCK(pool.cs);
486 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
487 view.SetBackend(viewMemPool);
489 // do we already have it?
490 for (size_t out = 0; out < tx.vout.size(); out++) {
491 COutPoint outpoint(hash, out);
492 bool had_coin_in_cache = pcoinsTip->HaveCoinInCache(outpoint);
493 if (view.HaveCoin(outpoint)) {
494 if (!had_coin_in_cache) {
495 coins_to_uncache.push_back(outpoint);
497 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
501 // do all inputs exist?
502 BOOST_FOREACH(const CTxIn txin, tx.vin) {
503 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
504 coins_to_uncache.push_back(txin.prevout);
506 if (!view.HaveCoin(txin.prevout)) {
507 if (pfMissingInputs) {
508 *pfMissingInputs = true;
510 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
514 // Bring the best block into scope
515 view.GetBestBlock();
517 nValueIn = view.GetValueIn(tx);
519 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
520 view.SetBackend(dummy);
522 // Only accept BIP68 sequence locked transactions that can be mined in the next
523 // block; we don't want our mempool filled up with transactions that can't
524 // be mined yet.
525 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
526 // CoinsViewCache instead of create its own
527 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
528 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
531 // Check for non-standard pay-to-script-hash in inputs
532 if (fRequireStandard && !AreInputsStandard(tx, view))
533 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
535 // Check for non-standard witness in P2WSH
536 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
537 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
539 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
541 CAmount nValueOut = tx.GetValueOut();
542 CAmount nFees = nValueIn-nValueOut;
543 // nModifiedFees includes any fee deltas from PrioritiseTransaction
544 CAmount nModifiedFees = nFees;
545 pool.ApplyDelta(hash, nModifiedFees);
547 // Keep track of transactions that spend a coinbase, which we re-scan
548 // during reorgs to ensure COINBASE_MATURITY is still met.
549 bool fSpendsCoinbase = false;
550 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
551 const Coin &coin = view.AccessCoin(txin.prevout);
552 if (coin.IsCoinBase()) {
553 fSpendsCoinbase = true;
554 break;
558 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
559 fSpendsCoinbase, nSigOpsCost, lp);
560 unsigned int nSize = entry.GetTxSize();
562 // Check that the transaction doesn't have an excessive number of
563 // sigops, making it impossible to mine. Since the coinbase transaction
564 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
565 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
566 // merely non-standard transaction.
567 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
568 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
569 strprintf("%d", nSigOpsCost));
571 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
572 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
573 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
576 // No transactions are allowed below minRelayTxFee except from disconnected blocks
577 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
578 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
581 if (nAbsurdFee && nFees > nAbsurdFee)
582 return state.Invalid(false,
583 REJECT_HIGHFEE, "absurdly-high-fee",
584 strprintf("%d > %d", nFees, nAbsurdFee));
586 // Calculate in-mempool ancestors, up to a limit.
587 CTxMemPool::setEntries setAncestors;
588 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
589 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
590 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
591 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
592 std::string errString;
593 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
594 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
597 // A transaction that spends outputs that would be replaced by it is invalid. Now
598 // that we have the set of all ancestors we can detect this
599 // pathological case by making sure setConflicts and setAncestors don't
600 // intersect.
601 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
603 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
604 if (setConflicts.count(hashAncestor))
606 return state.DoS(10, false,
607 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
608 strprintf("%s spends conflicting transaction %s",
609 hash.ToString(),
610 hashAncestor.ToString()));
614 // Check if it's economically rational to mine this transaction rather
615 // than the ones it replaces.
616 CAmount nConflictingFees = 0;
617 size_t nConflictingSize = 0;
618 uint64_t nConflictingCount = 0;
619 CTxMemPool::setEntries allConflicting;
621 // If we don't hold the lock allConflicting might be incomplete; the
622 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
623 // mempool consistency for us.
624 LOCK(pool.cs);
625 const bool fReplacementTransaction = setConflicts.size();
626 if (fReplacementTransaction)
628 CFeeRate newFeeRate(nModifiedFees, nSize);
629 std::set<uint256> setConflictsParents;
630 const int maxDescendantsToVisit = 100;
631 CTxMemPool::setEntries setIterConflicting;
632 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
634 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
635 if (mi == pool.mapTx.end())
636 continue;
638 // Save these to avoid repeated lookups
639 setIterConflicting.insert(mi);
641 // Don't allow the replacement to reduce the feerate of the
642 // mempool.
644 // We usually don't want to accept replacements with lower
645 // feerates than what they replaced as that would lower the
646 // feerate of the next block. Requiring that the feerate always
647 // be increased is also an easy-to-reason about way to prevent
648 // DoS attacks via replacements.
650 // The mining code doesn't (currently) take children into
651 // account (CPFP) so we only consider the feerates of
652 // transactions being directly replaced, not their indirect
653 // descendants. While that does mean high feerate children are
654 // ignored when deciding whether or not to replace, we do
655 // require the replacement to pay more overall fees too,
656 // mitigating most cases.
657 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
658 if (newFeeRate <= oldFeeRate)
660 return state.DoS(0, false,
661 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
662 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
663 hash.ToString(),
664 newFeeRate.ToString(),
665 oldFeeRate.ToString()));
668 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
670 setConflictsParents.insert(txin.prevout.hash);
673 nConflictingCount += mi->GetCountWithDescendants();
675 // This potentially overestimates the number of actual descendants
676 // but we just want to be conservative to avoid doing too much
677 // work.
678 if (nConflictingCount <= maxDescendantsToVisit) {
679 // If not too many to replace, then calculate the set of
680 // transactions that would have to be evicted
681 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
682 pool.CalculateDescendants(it, allConflicting);
684 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
685 nConflictingFees += it->GetModifiedFee();
686 nConflictingSize += it->GetTxSize();
688 } else {
689 return state.DoS(0, false,
690 REJECT_NONSTANDARD, "too many potential replacements", false,
691 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
692 hash.ToString(),
693 nConflictingCount,
694 maxDescendantsToVisit));
697 for (unsigned int j = 0; j < tx.vin.size(); j++)
699 // We don't want to accept replacements that require low
700 // feerate junk to be mined first. Ideally we'd keep track of
701 // the ancestor feerates and make the decision based on that,
702 // but for now requiring all new inputs to be confirmed works.
703 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
705 // Rather than check the UTXO set - potentially expensive -
706 // it's cheaper to just check if the new input refers to a
707 // tx that's in the mempool.
708 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
709 return state.DoS(0, false,
710 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
711 strprintf("replacement %s adds unconfirmed input, idx %d",
712 hash.ToString(), j));
716 // The replacement must pay greater fees than the transactions it
717 // replaces - if we did the bandwidth used by those conflicting
718 // transactions would not be paid for.
719 if (nModifiedFees < nConflictingFees)
721 return state.DoS(0, false,
722 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
723 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
724 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
727 // Finally in addition to paying more fees than the conflicts the
728 // new transaction must pay for its own bandwidth.
729 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
730 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
732 return state.DoS(0, false,
733 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
734 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
735 hash.ToString(),
736 FormatMoney(nDeltaFees),
737 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
741 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
742 if (!Params().RequireStandard()) {
743 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
746 // Check against previous transactions
747 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
748 PrecomputedTransactionData txdata(tx);
749 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
750 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
751 // need to turn both off, and compare against just turning off CLEANSTACK
752 // to see if the failure is specifically due to witness validation.
753 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
754 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
755 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
756 // Only the witness is missing, so the transaction itself may be fine.
757 state.SetCorruptionPossible();
759 return false; // state filled in by CheckInputs
762 // Check again against just the consensus-critical mandatory script
763 // verification flags, in case of bugs in the standard flags that cause
764 // transactions to pass as valid when they're actually invalid. For
765 // instance the STRICTENC flag was incorrectly allowing certain
766 // CHECKSIG NOT scripts to pass, even though they were invalid.
768 // There is a similar check in CreateNewBlock() to prevent creating
769 // invalid blocks, however allowing such transactions into the mempool
770 // can be exploited as a DoS attack.
771 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
773 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
774 __func__, hash.ToString(), FormatStateMessage(state));
777 // Remove conflicting transactions from the mempool
778 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
780 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
781 it->GetTx().GetHash().ToString(),
782 hash.ToString(),
783 FormatMoney(nModifiedFees - nConflictingFees),
784 (int)nSize - (int)nConflictingSize);
785 if (plTxnReplaced)
786 plTxnReplaced->push_back(it->GetSharedTx());
788 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
790 // This transaction should only count for fee estimation if it isn't a
791 // BIP 125 replacement transaction (may not be widely supported), the
792 // node is not behind, and the transaction is not dependent on any other
793 // transactions in the mempool.
794 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
796 // Store transaction in memory
797 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
799 // trim mempool and check if tx was trimmed
800 if (!fOverrideMempoolLimit) {
801 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
802 if (!pool.exists(hash))
803 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
807 GetMainSignals().TransactionAddedToMempool(ptx);
809 return true;
812 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
813 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
814 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
816 std::vector<COutPoint> coins_to_uncache;
817 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache);
818 if (!res) {
819 BOOST_FOREACH(const COutPoint& hashTx, coins_to_uncache)
820 pcoinsTip->Uncache(hashTx);
822 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
823 CValidationState stateDummy;
824 FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
825 return res;
828 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
829 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
830 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
832 return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
835 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
836 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
838 CBlockIndex *pindexSlow = NULL;
840 LOCK(cs_main);
842 CTransactionRef ptx = mempool.get(hash);
843 if (ptx)
845 txOut = ptx;
846 return true;
849 if (fTxIndex) {
850 CDiskTxPos postx;
851 if (pblocktree->ReadTxIndex(hash, postx)) {
852 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
853 if (file.IsNull())
854 return error("%s: OpenBlockFile failed", __func__);
855 CBlockHeader header;
856 try {
857 file >> header;
858 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
859 file >> txOut;
860 } catch (const std::exception& e) {
861 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
863 hashBlock = header.GetHash();
864 if (txOut->GetHash() != hash)
865 return error("%s: txid mismatch", __func__);
866 return true;
870 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
871 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
872 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
875 if (pindexSlow) {
876 CBlock block;
877 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
878 for (const auto& tx : block.vtx) {
879 if (tx->GetHash() == hash) {
880 txOut = tx;
881 hashBlock = pindexSlow->GetBlockHash();
882 return true;
888 return false;
896 //////////////////////////////////////////////////////////////////////////////
898 // CBlock and CBlockIndex
901 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
903 // Open history file to append
904 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
905 if (fileout.IsNull())
906 return error("WriteBlockToDisk: OpenBlockFile failed");
908 // Write index header
909 unsigned int nSize = GetSerializeSize(fileout, block);
910 fileout << FLATDATA(messageStart) << nSize;
912 // Write block
913 long fileOutPos = ftell(fileout.Get());
914 if (fileOutPos < 0)
915 return error("WriteBlockToDisk: ftell failed");
916 pos.nPos = (unsigned int)fileOutPos;
917 fileout << block;
919 return true;
922 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
924 block.SetNull();
926 // Open history file to read
927 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
928 if (filein.IsNull())
929 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
931 // Read block
932 try {
933 filein >> block;
935 catch (const std::exception& e) {
936 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
939 // Check the header
940 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
941 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
943 return true;
946 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
948 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
949 return false;
950 if (block.GetHash() != pindex->GetBlockHash())
951 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
952 pindex->ToString(), pindex->GetBlockPos().ToString());
953 return true;
956 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
958 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
959 // Force block reward to zero when right shift is undefined.
960 if (halvings >= 64)
961 return 0;
963 CAmount nSubsidy = 50 * COIN;
964 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
965 nSubsidy >>= halvings;
966 return nSubsidy;
969 bool IsInitialBlockDownload()
971 const CChainParams& chainParams = Params();
973 // Once this function has returned false, it must remain false.
974 static std::atomic<bool> latchToFalse{false};
975 // Optimization: pre-test latch before taking the lock.
976 if (latchToFalse.load(std::memory_order_relaxed))
977 return false;
979 LOCK(cs_main);
980 if (latchToFalse.load(std::memory_order_relaxed))
981 return false;
982 if (fImporting || fReindex)
983 return true;
984 if (chainActive.Tip() == NULL)
985 return true;
986 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
987 return true;
988 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
989 return true;
990 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
991 latchToFalse.store(true, std::memory_order_relaxed);
992 return false;
995 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
997 static void AlertNotify(const std::string& strMessage)
999 uiInterface.NotifyAlertChanged();
1000 std::string strCmd = GetArg("-alertnotify", "");
1001 if (strCmd.empty()) return;
1003 // Alert text should be plain ascii coming from a trusted source, but to
1004 // be safe we first strip anything not in safeChars, then add single quotes around
1005 // the whole string before passing it to the shell:
1006 std::string singleQuote("'");
1007 std::string safeStatus = SanitizeString(strMessage);
1008 safeStatus = singleQuote+safeStatus+singleQuote;
1009 boost::replace_all(strCmd, "%s", safeStatus);
1011 boost::thread t(runCommand, strCmd); // thread runs free
1014 void CheckForkWarningConditions()
1016 AssertLockHeld(cs_main);
1017 // Before we get past initial download, we cannot reliably alert about forks
1018 // (we assume we don't get stuck on a fork before finishing our initial sync)
1019 if (IsInitialBlockDownload())
1020 return;
1022 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1023 // of our head, drop it
1024 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1025 pindexBestForkTip = NULL;
1027 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1029 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1031 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1032 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1033 AlertNotify(warning);
1035 if (pindexBestForkTip && pindexBestForkBase)
1037 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__,
1038 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1039 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1040 SetfLargeWorkForkFound(true);
1042 else
1044 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1045 SetfLargeWorkInvalidChainFound(true);
1048 else
1050 SetfLargeWorkForkFound(false);
1051 SetfLargeWorkInvalidChainFound(false);
1055 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1057 AssertLockHeld(cs_main);
1058 // If we are on a fork that is sufficiently large, set a warning flag
1059 CBlockIndex* pfork = pindexNewForkTip;
1060 CBlockIndex* plonger = chainActive.Tip();
1061 while (pfork && pfork != plonger)
1063 while (plonger && plonger->nHeight > pfork->nHeight)
1064 plonger = plonger->pprev;
1065 if (pfork == plonger)
1066 break;
1067 pfork = pfork->pprev;
1070 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1071 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1072 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1073 // hash rate operating on the fork.
1074 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1075 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1076 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1077 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1078 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1079 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1081 pindexBestForkTip = pindexNewForkTip;
1082 pindexBestForkBase = pfork;
1085 CheckForkWarningConditions();
1088 void static InvalidChainFound(CBlockIndex* pindexNew)
1090 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1091 pindexBestInvalid = pindexNew;
1093 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1094 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1095 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1096 pindexNew->GetBlockTime()));
1097 CBlockIndex *tip = chainActive.Tip();
1098 assert (tip);
1099 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1100 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1101 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1102 CheckForkWarningConditions();
1105 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1106 if (!state.CorruptionPossible()) {
1107 pindex->nStatus |= BLOCK_FAILED_VALID;
1108 setDirtyBlockIndex.insert(pindex);
1109 setBlockIndexCandidates.erase(pindex);
1110 InvalidChainFound(pindex);
1114 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1116 // mark inputs spent
1117 if (!tx.IsCoinBase()) {
1118 txundo.vprevout.reserve(tx.vin.size());
1119 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1120 txundo.vprevout.emplace_back();
1121 inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1124 // add outputs
1125 AddCoins(inputs, tx, nHeight);
1128 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1130 CTxUndo txundo;
1131 UpdateCoins(tx, inputs, txundo, nHeight);
1134 bool CScriptCheck::operator()() {
1135 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1136 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1137 return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1140 int GetSpendHeight(const CCoinsViewCache& inputs)
1142 LOCK(cs_main);
1143 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1144 return pindexPrev->nHeight + 1;
1147 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1149 if (!tx.IsCoinBase())
1151 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1152 return false;
1154 if (pvChecks)
1155 pvChecks->reserve(tx.vin.size());
1157 // The first loop above does all the inexpensive checks.
1158 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1159 // Helps prevent CPU exhaustion attacks.
1161 // Skip script verification when connecting blocks under the
1162 // assumevalid block. Assuming the assumevalid block is valid this
1163 // is safe because block merkle hashes are still computed and checked,
1164 // Of course, if an assumed valid block is invalid due to false scriptSigs
1165 // this optimization would allow an invalid chain to be accepted.
1166 if (fScriptChecks) {
1167 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1168 const COutPoint &prevout = tx.vin[i].prevout;
1169 const Coin& coin = inputs.AccessCoin(prevout);
1170 assert(!coin.IsSpent());
1172 // We very carefully only pass in things to CScriptCheck which
1173 // are clearly committed to by tx' witness hash. This provides
1174 // a sanity check that our caching is not introducing consensus
1175 // failures through additional data in, eg, the coins being
1176 // spent being checked as a part of CScriptCheck.
1177 const CScript& scriptPubKey = coin.out.scriptPubKey;
1178 const CAmount amount = coin.out.nValue;
1180 // Verify signature
1181 CScriptCheck check(scriptPubKey, amount, tx, i, flags, cacheStore, &txdata);
1182 if (pvChecks) {
1183 pvChecks->push_back(CScriptCheck());
1184 check.swap(pvChecks->back());
1185 } else if (!check()) {
1186 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1187 // Check whether the failure was caused by a
1188 // non-mandatory script verification check, such as
1189 // non-standard DER encodings or non-null dummy
1190 // arguments; if so, don't trigger DoS protection to
1191 // avoid splitting the network between upgraded and
1192 // non-upgraded nodes.
1193 CScriptCheck check2(scriptPubKey, amount, tx, i,
1194 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1195 if (check2())
1196 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1198 // Failures of other flags indicate a transaction that is
1199 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1200 // such nodes as they are not following the protocol. That
1201 // said during an upgrade careful thought should be taken
1202 // as to the correct behavior - we may want to continue
1203 // peering with non-upgraded nodes even after soft-fork
1204 // super-majority signaling has occurred.
1205 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1211 return true;
1214 namespace {
1216 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1218 // Open history file to append
1219 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1220 if (fileout.IsNull())
1221 return error("%s: OpenUndoFile failed", __func__);
1223 // Write index header
1224 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1225 fileout << FLATDATA(messageStart) << nSize;
1227 // Write undo data
1228 long fileOutPos = ftell(fileout.Get());
1229 if (fileOutPos < 0)
1230 return error("%s: ftell failed", __func__);
1231 pos.nPos = (unsigned int)fileOutPos;
1232 fileout << blockundo;
1234 // calculate & write checksum
1235 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1236 hasher << hashBlock;
1237 hasher << blockundo;
1238 fileout << hasher.GetHash();
1240 return true;
1243 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1245 // Open history file to read
1246 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1247 if (filein.IsNull())
1248 return error("%s: OpenUndoFile failed", __func__);
1250 // Read block
1251 uint256 hashChecksum;
1252 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1253 try {
1254 verifier << hashBlock;
1255 verifier >> blockundo;
1256 filein >> hashChecksum;
1258 catch (const std::exception& e) {
1259 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1262 // Verify checksum
1263 if (hashChecksum != verifier.GetHash())
1264 return error("%s: Checksum mismatch", __func__);
1266 return true;
1269 /** Abort with a message */
1270 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1272 SetMiscWarning(strMessage);
1273 LogPrintf("*** %s\n", strMessage);
1274 uiInterface.ThreadSafeMessageBox(
1275 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1276 "", CClientUIInterface::MSG_ERROR);
1277 StartShutdown();
1278 return false;
1281 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1283 AbortNode(strMessage, userMessage);
1284 return state.Error(strMessage);
1287 } // anon namespace
1289 enum DisconnectResult
1291 DISCONNECT_OK, // All good.
1292 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1293 DISCONNECT_FAILED // Something else went wrong.
1297 * Restore the UTXO in a Coin at a given COutPoint
1298 * @param undo The Coin to be restored.
1299 * @param view The coins view to which to apply the changes.
1300 * @param out The out point that corresponds to the tx input.
1301 * @return A DisconnectResult as an int
1303 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1305 bool fClean = true;
1307 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1309 if (undo.nHeight == 0) {
1310 // Missing undo metadata (height and coinbase). Older versions included this
1311 // information only in undo records for the last spend of a transactions'
1312 // outputs. This implies that it must be present for some other output of the same tx.
1313 const Coin& alternate = AccessByTxid(view, out.hash);
1314 if (!alternate.IsSpent()) {
1315 undo.nHeight = alternate.nHeight;
1316 undo.fCoinBase = alternate.fCoinBase;
1317 } else {
1318 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1321 view.AddCoin(out, std::move(undo), undo.fCoinBase);
1323 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1326 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1327 * When UNCLEAN or FAILED is returned, view is left in an indeterminate state. */
1328 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1330 assert(pindex->GetBlockHash() == view.GetBestBlock());
1332 bool fClean = true;
1334 CBlockUndo blockUndo;
1335 CDiskBlockPos pos = pindex->GetUndoPos();
1336 if (pos.IsNull()) {
1337 error("DisconnectBlock(): no undo data available");
1338 return DISCONNECT_FAILED;
1340 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1341 error("DisconnectBlock(): failure reading undo data");
1342 return DISCONNECT_FAILED;
1345 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1346 error("DisconnectBlock(): block and undo data inconsistent");
1347 return DISCONNECT_FAILED;
1350 // undo transactions in reverse order
1351 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1352 const CTransaction &tx = *(block.vtx[i]);
1353 uint256 hash = tx.GetHash();
1355 // Check that all outputs are available and match the outputs in the block itself
1356 // exactly.
1357 for (size_t o = 0; o < tx.vout.size(); o++) {
1358 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1359 COutPoint out(hash, o);
1360 Coin coin;
1361 view.SpendCoin(out, &coin);
1362 if (tx.vout[o] != coin.out) {
1363 fClean = false; // transaction output mismatch
1368 // restore inputs
1369 if (i > 0) { // not coinbases
1370 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1371 if (txundo.vprevout.size() != tx.vin.size()) {
1372 error("DisconnectBlock(): transaction and undo data inconsistent");
1373 return DISCONNECT_FAILED;
1375 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1376 const COutPoint &out = tx.vin[j].prevout;
1377 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1378 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1379 fClean = fClean && res != DISCONNECT_UNCLEAN;
1381 // At this point, all of txundo.vprevout should have been moved out.
1385 // move best block pointer to prevout block
1386 view.SetBestBlock(pindex->pprev->GetBlockHash());
1388 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1391 void static FlushBlockFile(bool fFinalize = false)
1393 LOCK(cs_LastBlockFile);
1395 CDiskBlockPos posOld(nLastBlockFile, 0);
1397 FILE *fileOld = OpenBlockFile(posOld);
1398 if (fileOld) {
1399 if (fFinalize)
1400 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1401 FileCommit(fileOld);
1402 fclose(fileOld);
1405 fileOld = OpenUndoFile(posOld);
1406 if (fileOld) {
1407 if (fFinalize)
1408 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1409 FileCommit(fileOld);
1410 fclose(fileOld);
1414 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1416 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1418 void ThreadScriptCheck() {
1419 RenameThread("bitcoin-scriptch");
1420 scriptcheckqueue.Thread();
1423 // Protected by cs_main
1424 VersionBitsCache versionbitscache;
1426 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1428 LOCK(cs_main);
1429 int32_t nVersion = VERSIONBITS_TOP_BITS;
1431 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1432 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1433 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1434 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1438 return nVersion;
1442 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1444 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1446 private:
1447 int bit;
1449 public:
1450 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1452 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1453 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1454 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1455 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1457 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1459 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1460 ((pindex->nVersion >> bit) & 1) != 0 &&
1461 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1465 // Protected by cs_main
1466 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1468 static int64_t nTimeCheck = 0;
1469 static int64_t nTimeForks = 0;
1470 static int64_t nTimeVerify = 0;
1471 static int64_t nTimeConnect = 0;
1472 static int64_t nTimeIndex = 0;
1473 static int64_t nTimeCallbacks = 0;
1474 static int64_t nTimeTotal = 0;
1476 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1477 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1478 * can fail if those validity checks fail (among other reasons). */
1479 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1480 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1482 AssertLockHeld(cs_main);
1483 assert(pindex);
1484 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1485 assert((pindex->phashBlock == NULL) ||
1486 (*pindex->phashBlock == block.GetHash()));
1487 int64_t nTimeStart = GetTimeMicros();
1489 // Check it again in case a previous version let a bad block in
1490 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1491 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1493 // verify that the view's current state corresponds to the previous block
1494 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1495 assert(hashPrevBlock == view.GetBestBlock());
1497 // Special case for the genesis block, skipping connection of its transactions
1498 // (its coinbase is unspendable)
1499 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1500 if (!fJustCheck)
1501 view.SetBestBlock(pindex->GetBlockHash());
1502 return true;
1505 bool fScriptChecks = true;
1506 if (!hashAssumeValid.IsNull()) {
1507 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1508 // A suitable default value is included with the software and updated from time to time. Because validity
1509 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1510 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1511 // effectively caching the result of part of the verification.
1512 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1513 if (it != mapBlockIndex.end()) {
1514 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1515 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1516 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1517 // This block is a member of the assumed verified chain and an ancestor of the best header.
1518 // The equivalent time check discourages hash power from extorting the network via DOS attack
1519 // into accepting an invalid block through telling users they must manually set assumevalid.
1520 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1521 // it hard to hide the implication of the demand. This also avoids having release candidates
1522 // that are hardly doing any signature verification at all in testing without having to
1523 // artificially set the default assumed verified block further back.
1524 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1525 // least as good as the expected chain.
1526 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1531 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1532 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1534 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1535 // unless those are already completely spent.
1536 // If such overwrites are allowed, coinbases and transactions depending upon those
1537 // can be duplicated to remove the ability to spend the first instance -- even after
1538 // being sent to another address.
1539 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1540 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1541 // already refuses previously-known transaction ids entirely.
1542 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1543 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1544 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1545 // initial block download.
1546 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1547 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1548 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1550 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1551 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1552 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1553 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1554 // duplicate transactions descending from the known pairs either.
1555 // 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.
1556 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1557 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1558 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1560 if (fEnforceBIP30) {
1561 for (const auto& tx : block.vtx) {
1562 for (size_t o = 0; o < tx->vout.size(); o++) {
1563 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1564 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1565 REJECT_INVALID, "bad-txns-BIP30");
1571 // BIP16 didn't become active until Apr 1 2012
1572 int64_t nBIP16SwitchTime = 1333238400;
1573 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1575 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1577 // Start enforcing the DERSIG (BIP66) rule
1578 if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
1579 flags |= SCRIPT_VERIFY_DERSIG;
1582 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1583 if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
1584 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1587 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1588 int nLockTimeFlags = 0;
1589 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1590 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1591 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1594 // Start enforcing WITNESS rules using versionbits logic.
1595 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) {
1596 flags |= SCRIPT_VERIFY_WITNESS;
1597 flags |= SCRIPT_VERIFY_NULLDUMMY;
1600 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1601 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1603 CBlockUndo blockundo;
1605 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1607 std::vector<int> prevheights;
1608 CAmount nFees = 0;
1609 int nInputs = 0;
1610 int64_t nSigOpsCost = 0;
1611 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1612 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1613 vPos.reserve(block.vtx.size());
1614 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1615 std::vector<PrecomputedTransactionData> txdata;
1616 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1617 for (unsigned int i = 0; i < block.vtx.size(); i++)
1619 const CTransaction &tx = *(block.vtx[i]);
1621 nInputs += tx.vin.size();
1623 if (!tx.IsCoinBase())
1625 if (!view.HaveInputs(tx))
1626 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1627 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1629 // Check that transaction is BIP68 final
1630 // BIP68 lock checks (as opposed to nLockTime checks) must
1631 // be in ConnectBlock because they require the UTXO set
1632 prevheights.resize(tx.vin.size());
1633 for (size_t j = 0; j < tx.vin.size(); j++) {
1634 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1637 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1638 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1639 REJECT_INVALID, "bad-txns-nonfinal");
1643 // GetTransactionSigOpCost counts 3 types of sigops:
1644 // * legacy (always)
1645 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1646 // * witness (when witness enabled in flags and excludes coinbase)
1647 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1648 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1649 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1650 REJECT_INVALID, "bad-blk-sigops");
1652 txdata.emplace_back(tx);
1653 if (!tx.IsCoinBase())
1655 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1657 std::vector<CScriptCheck> vChecks;
1658 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1659 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1660 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1661 tx.GetHash().ToString(), FormatStateMessage(state));
1662 control.Add(vChecks);
1665 CTxUndo undoDummy;
1666 if (i > 0) {
1667 blockundo.vtxundo.push_back(CTxUndo());
1669 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1671 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1672 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1674 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1675 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);
1677 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1678 if (block.vtx[0]->GetValueOut() > blockReward)
1679 return state.DoS(100,
1680 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1681 block.vtx[0]->GetValueOut(), blockReward),
1682 REJECT_INVALID, "bad-cb-amount");
1684 if (!control.Wait())
1685 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1686 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1687 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);
1689 if (fJustCheck)
1690 return true;
1692 // Write undo information to disk
1693 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1695 if (pindex->GetUndoPos().IsNull()) {
1696 CDiskBlockPos _pos;
1697 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1698 return error("ConnectBlock(): FindUndoPos failed");
1699 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1700 return AbortNode(state, "Failed to write undo data");
1702 // update nUndoPos in block index
1703 pindex->nUndoPos = _pos.nPos;
1704 pindex->nStatus |= BLOCK_HAVE_UNDO;
1707 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1708 setDirtyBlockIndex.insert(pindex);
1711 if (fTxIndex)
1712 if (!pblocktree->WriteTxIndex(vPos))
1713 return AbortNode(state, "Failed to write transaction index");
1715 // add this block to the view's block chain
1716 view.SetBestBlock(pindex->GetBlockHash());
1718 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1719 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1721 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1722 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1724 return true;
1728 * Update the on-disk chain state.
1729 * The caches and indexes are flushed depending on the mode we're called with
1730 * if they're too large, if it's been a while since the last write,
1731 * or always and in all cases if we're in prune mode and are deleting files.
1733 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1734 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1735 const CChainParams& chainparams = Params();
1736 LOCK2(cs_main, cs_LastBlockFile);
1737 static int64_t nLastWrite = 0;
1738 static int64_t nLastFlush = 0;
1739 static int64_t nLastSetChain = 0;
1740 std::set<int> setFilesToPrune;
1741 bool fFlushForPrune = false;
1742 try {
1743 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1744 if (nManualPruneHeight > 0) {
1745 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1746 } else {
1747 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1748 fCheckForPruning = false;
1750 if (!setFilesToPrune.empty()) {
1751 fFlushForPrune = true;
1752 if (!fHavePruned) {
1753 pblocktree->WriteFlag("prunedblockfiles", true);
1754 fHavePruned = true;
1758 int64_t nNow = GetTimeMicros();
1759 // Avoid writing/flushing immediately after startup.
1760 if (nLastWrite == 0) {
1761 nLastWrite = nNow;
1763 if (nLastFlush == 0) {
1764 nLastFlush = nNow;
1766 if (nLastSetChain == 0) {
1767 nLastSetChain = nNow;
1769 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1770 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
1771 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1772 // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
1773 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
1774 // The cache is over the limit, we have to write now.
1775 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1776 // 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.
1777 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1778 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1779 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1780 // Combine all conditions that result in a full cache flush.
1781 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1782 // Write blocks and block index to disk.
1783 if (fDoFullFlush || fPeriodicWrite) {
1784 // Depend on nMinDiskSpace to ensure we can write block index
1785 if (!CheckDiskSpace(0))
1786 return state.Error("out of disk space");
1787 // First make sure all block and undo data is flushed to disk.
1788 FlushBlockFile();
1789 // Then update all block file information (which may refer to block and undo files).
1791 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1792 vFiles.reserve(setDirtyFileInfo.size());
1793 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1794 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
1795 setDirtyFileInfo.erase(it++);
1797 std::vector<const CBlockIndex*> vBlocks;
1798 vBlocks.reserve(setDirtyBlockIndex.size());
1799 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1800 vBlocks.push_back(*it);
1801 setDirtyBlockIndex.erase(it++);
1803 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1804 return AbortNode(state, "Failed to write to block index database");
1807 // Finally remove any pruned files
1808 if (fFlushForPrune)
1809 UnlinkPrunedFiles(setFilesToPrune);
1810 nLastWrite = nNow;
1812 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1813 if (fDoFullFlush) {
1814 // Typical Coin structures on disk are around 48 bytes in size.
1815 // Pushing a new one to the database can cause it to be written
1816 // twice (once in the log, and once in the tables). This is already
1817 // an overestimation, as most will delete an existing entry or
1818 // overwrite one. Still, use a conservative safety factor of 2.
1819 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
1820 return state.Error("out of disk space");
1821 // Flush the chainstate (which may refer to block index entries).
1822 if (!pcoinsTip->Flush())
1823 return AbortNode(state, "Failed to write to coin database");
1824 nLastFlush = nNow;
1826 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
1827 // Update best block in wallet (so we can detect restored wallets).
1828 GetMainSignals().SetBestChain(chainActive.GetLocator());
1829 nLastSetChain = nNow;
1831 } catch (const std::runtime_error& e) {
1832 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1834 return true;
1837 void FlushStateToDisk() {
1838 CValidationState state;
1839 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1842 void PruneAndFlush() {
1843 CValidationState state;
1844 fCheckForPruning = true;
1845 FlushStateToDisk(state, FLUSH_STATE_NONE);
1848 static void DoWarning(const std::string& strWarning)
1850 static bool fWarned = false;
1851 SetMiscWarning(strWarning);
1852 if (!fWarned) {
1853 AlertNotify(strWarning);
1854 fWarned = true;
1858 /** Update chainActive and related internal data structures. */
1859 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
1860 chainActive.SetTip(pindexNew);
1862 // New best block
1863 mempool.AddTransactionsUpdated(1);
1865 cvBlockChange.notify_all();
1867 std::vector<std::string> warningMessages;
1868 if (!IsInitialBlockDownload())
1870 int nUpgraded = 0;
1871 const CBlockIndex* pindex = chainActive.Tip();
1872 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
1873 WarningBitsConditionChecker checker(bit);
1874 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
1875 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
1876 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
1877 if (state == THRESHOLD_ACTIVE) {
1878 DoWarning(strWarning);
1879 } else {
1880 warningMessages.push_back(strWarning);
1884 // Check the version of the last 100 blocks to see if we need to upgrade:
1885 for (int i = 0; i < 100 && pindex != NULL; i++)
1887 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
1888 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
1889 ++nUpgraded;
1890 pindex = pindex->pprev;
1892 if (nUpgraded > 0)
1893 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
1894 if (nUpgraded > 100/2)
1896 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
1897 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1898 DoWarning(strWarning);
1901 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
1902 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
1903 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1904 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1905 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
1906 if (!warningMessages.empty())
1907 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
1908 LogPrintf("\n");
1912 /** Disconnect chainActive's tip.
1913 * After calling, the mempool will be in an inconsistent state, with
1914 * transactions from disconnected blocks being added to disconnectpool. You
1915 * should make the mempool consistent again by calling UpdateMempoolForReorg.
1916 * with cs_main held.
1918 * If disconnectpool is NULL, then no disconnected transactions are added to
1919 * disconnectpool (note that the caller is responsible for mempool consistency
1920 * in any case).
1922 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
1924 CBlockIndex *pindexDelete = chainActive.Tip();
1925 assert(pindexDelete);
1926 // Read block from disk.
1927 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
1928 CBlock& block = *pblock;
1929 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
1930 return AbortNode(state, "Failed to read block");
1931 // Apply the block atomically to the chain state.
1932 int64_t nStart = GetTimeMicros();
1934 CCoinsViewCache view(pcoinsTip);
1935 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
1936 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
1937 bool flushed = view.Flush();
1938 assert(flushed);
1940 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1941 // Write the chain state to disk, if necessary.
1942 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
1943 return false;
1945 if (disconnectpool) {
1946 // Save transactions to re-add to mempool at end of reorg
1947 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
1948 disconnectpool->addTransaction(*it);
1950 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
1951 // Drop the earliest entry, and remove its children from the mempool.
1952 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
1953 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
1954 disconnectpool->removeEntry(it);
1958 // Update chainActive and related variables.
1959 UpdateTip(pindexDelete->pprev, chainparams);
1960 // Let wallets know transactions went from 1-confirmed to
1961 // 0-confirmed or conflicted:
1962 GetMainSignals().BlockDisconnected(pblock);
1963 return true;
1966 static int64_t nTimeReadFromDisk = 0;
1967 static int64_t nTimeConnectTotal = 0;
1968 static int64_t nTimeFlush = 0;
1969 static int64_t nTimeChainState = 0;
1970 static int64_t nTimePostConnect = 0;
1972 struct PerBlockConnectTrace {
1973 CBlockIndex* pindex = NULL;
1974 std::shared_ptr<const CBlock> pblock;
1975 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
1976 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
1979 * Used to track blocks whose transactions were applied to the UTXO state as a
1980 * part of a single ActivateBestChainStep call.
1982 * This class also tracks transactions that are removed from the mempool as
1983 * conflicts (per block) and can be used to pass all those transactions
1984 * through SyncTransaction.
1986 * This class assumes (and asserts) that the conflicted transactions for a given
1987 * block are added via mempool callbacks prior to the BlockConnected() associated
1988 * with those transactions. If any transactions are marked conflicted, it is
1989 * assumed that an associated block will always be added.
1991 * This class is single-use, once you call GetBlocksConnected() you have to throw
1992 * it away and make a new one.
1994 class ConnectTrace {
1995 private:
1996 std::vector<PerBlockConnectTrace> blocksConnected;
1997 CTxMemPool &pool;
1999 public:
2000 ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2001 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2004 ~ConnectTrace() {
2005 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2008 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2009 assert(!blocksConnected.back().pindex);
2010 assert(pindex);
2011 assert(pblock);
2012 blocksConnected.back().pindex = pindex;
2013 blocksConnected.back().pblock = std::move(pblock);
2014 blocksConnected.emplace_back();
2017 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2018 // We always keep one extra block at the end of our list because
2019 // blocks are added after all the conflicted transactions have
2020 // been filled in. Thus, the last entry should always be an empty
2021 // one waiting for the transactions from the next block. We pop
2022 // the last entry here to make sure the list we return is sane.
2023 assert(!blocksConnected.back().pindex);
2024 assert(blocksConnected.back().conflictedTxs->empty());
2025 blocksConnected.pop_back();
2026 return blocksConnected;
2029 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2030 assert(!blocksConnected.back().pindex);
2031 if (reason == MemPoolRemovalReason::CONFLICT) {
2032 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2038 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2039 * corresponding to pindexNew, to bypass loading it again from disk.
2041 * The block is added to connectTrace if connection succeeds.
2043 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2045 assert(pindexNew->pprev == chainActive.Tip());
2046 // Read block from disk.
2047 int64_t nTime1 = GetTimeMicros();
2048 std::shared_ptr<const CBlock> pthisBlock;
2049 if (!pblock) {
2050 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2051 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2052 return AbortNode(state, "Failed to read block");
2053 pthisBlock = pblockNew;
2054 } else {
2055 pthisBlock = pblock;
2057 const CBlock& blockConnecting = *pthisBlock;
2058 // Apply the block atomically to the chain state.
2059 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2060 int64_t nTime3;
2061 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2063 CCoinsViewCache view(pcoinsTip);
2064 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2065 GetMainSignals().BlockChecked(blockConnecting, state);
2066 if (!rv) {
2067 if (state.IsInvalid())
2068 InvalidBlockFound(pindexNew, state);
2069 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2071 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2072 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2073 bool flushed = view.Flush();
2074 assert(flushed);
2076 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2077 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2078 // Write the chain state to disk, if necessary.
2079 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2080 return false;
2081 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2082 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2083 // Remove conflicting transactions from the mempool.;
2084 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2085 disconnectpool.removeForBlock(blockConnecting.vtx);
2086 // Update chainActive & related variables.
2087 UpdateTip(pindexNew, chainparams);
2089 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2090 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2091 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2093 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2094 return true;
2098 * Return the tip of the chain with the most work in it, that isn't
2099 * known to be invalid (it's however far from certain to be valid).
2101 static CBlockIndex* FindMostWorkChain() {
2102 do {
2103 CBlockIndex *pindexNew = NULL;
2105 // Find the best candidate header.
2107 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2108 if (it == setBlockIndexCandidates.rend())
2109 return NULL;
2110 pindexNew = *it;
2113 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2114 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2115 CBlockIndex *pindexTest = pindexNew;
2116 bool fInvalidAncestor = false;
2117 while (pindexTest && !chainActive.Contains(pindexTest)) {
2118 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2120 // Pruned nodes may have entries in setBlockIndexCandidates for
2121 // which block files have been deleted. Remove those as candidates
2122 // for the most work chain if we come across them; we can't switch
2123 // to a chain unless we have all the non-active-chain parent blocks.
2124 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2125 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2126 if (fFailedChain || fMissingData) {
2127 // Candidate chain is not usable (either invalid or missing data)
2128 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2129 pindexBestInvalid = pindexNew;
2130 CBlockIndex *pindexFailed = pindexNew;
2131 // Remove the entire chain from the set.
2132 while (pindexTest != pindexFailed) {
2133 if (fFailedChain) {
2134 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2135 } else if (fMissingData) {
2136 // If we're missing data, then add back to mapBlocksUnlinked,
2137 // so that if the block arrives in the future we can try adding
2138 // to setBlockIndexCandidates again.
2139 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2141 setBlockIndexCandidates.erase(pindexFailed);
2142 pindexFailed = pindexFailed->pprev;
2144 setBlockIndexCandidates.erase(pindexTest);
2145 fInvalidAncestor = true;
2146 break;
2148 pindexTest = pindexTest->pprev;
2150 if (!fInvalidAncestor)
2151 return pindexNew;
2152 } while(true);
2155 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2156 static void PruneBlockIndexCandidates() {
2157 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2158 // reorganization to a better block fails.
2159 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2160 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2161 setBlockIndexCandidates.erase(it++);
2163 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2164 assert(!setBlockIndexCandidates.empty());
2168 * Try to make some progress towards making pindexMostWork the active block.
2169 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2171 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2173 AssertLockHeld(cs_main);
2174 const CBlockIndex *pindexOldTip = chainActive.Tip();
2175 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2177 // Disconnect active blocks which are no longer in the best chain.
2178 bool fBlocksDisconnected = false;
2179 DisconnectedBlockTransactions disconnectpool;
2180 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2181 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2182 // This is likely a fatal error, but keep the mempool consistent,
2183 // just in case. Only remove from the mempool in this case.
2184 UpdateMempoolForReorg(disconnectpool, false);
2185 return false;
2187 fBlocksDisconnected = true;
2190 // Build list of new blocks to connect.
2191 std::vector<CBlockIndex*> vpindexToConnect;
2192 bool fContinue = true;
2193 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2194 while (fContinue && nHeight != pindexMostWork->nHeight) {
2195 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2196 // a few blocks along the way.
2197 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2198 vpindexToConnect.clear();
2199 vpindexToConnect.reserve(nTargetHeight - nHeight);
2200 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2201 while (pindexIter && pindexIter->nHeight != nHeight) {
2202 vpindexToConnect.push_back(pindexIter);
2203 pindexIter = pindexIter->pprev;
2205 nHeight = nTargetHeight;
2207 // Connect new blocks.
2208 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2209 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2210 if (state.IsInvalid()) {
2211 // The block violates a consensus rule.
2212 if (!state.CorruptionPossible())
2213 InvalidChainFound(vpindexToConnect.back());
2214 state = CValidationState();
2215 fInvalidFound = true;
2216 fContinue = false;
2217 break;
2218 } else {
2219 // A system error occurred (disk space, database error, ...).
2220 // Make the mempool consistent with the current tip, just in case
2221 // any observers try to use it before shutdown.
2222 UpdateMempoolForReorg(disconnectpool, false);
2223 return false;
2225 } else {
2226 PruneBlockIndexCandidates();
2227 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2228 // We're in a better position than we were. Return temporarily to release the lock.
2229 fContinue = false;
2230 break;
2236 if (fBlocksDisconnected) {
2237 // If any blocks were disconnected, disconnectpool may be non empty. Add
2238 // any disconnected transactions back to the mempool.
2239 UpdateMempoolForReorg(disconnectpool, true);
2241 mempool.check(pcoinsTip);
2243 // Callbacks/notifications for a new best chain.
2244 if (fInvalidFound)
2245 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2246 else
2247 CheckForkWarningConditions();
2249 return true;
2252 static void NotifyHeaderTip() {
2253 bool fNotify = false;
2254 bool fInitialBlockDownload = false;
2255 static CBlockIndex* pindexHeaderOld = NULL;
2256 CBlockIndex* pindexHeader = NULL;
2258 LOCK(cs_main);
2259 pindexHeader = pindexBestHeader;
2261 if (pindexHeader != pindexHeaderOld) {
2262 fNotify = true;
2263 fInitialBlockDownload = IsInitialBlockDownload();
2264 pindexHeaderOld = pindexHeader;
2267 // Send block tip changed notifications without cs_main
2268 if (fNotify) {
2269 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2274 * Make the best chain active, in multiple steps. The result is either failure
2275 * or an activated best chain. pblock is either NULL or a pointer to a block
2276 * that is already loaded (to avoid loading it again from disk).
2278 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2279 // Note that while we're often called here from ProcessNewBlock, this is
2280 // far from a guarantee. Things in the P2P/RPC will often end up calling
2281 // us in the middle of ProcessNewBlock - do not assume pblock is set
2282 // sanely for performance or correctness!
2284 CBlockIndex *pindexMostWork = NULL;
2285 CBlockIndex *pindexNewTip = NULL;
2286 do {
2287 boost::this_thread::interruption_point();
2288 if (ShutdownRequested())
2289 break;
2291 const CBlockIndex *pindexFork;
2292 bool fInitialDownload;
2294 LOCK(cs_main);
2295 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2297 CBlockIndex *pindexOldTip = chainActive.Tip();
2298 if (pindexMostWork == NULL) {
2299 pindexMostWork = FindMostWorkChain();
2302 // Whether we have anything to do at all.
2303 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2304 return true;
2306 bool fInvalidFound = false;
2307 std::shared_ptr<const CBlock> nullBlockPtr;
2308 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2309 return false;
2311 if (fInvalidFound) {
2312 // Wipe cache, we may need another branch now.
2313 pindexMostWork = NULL;
2315 pindexNewTip = chainActive.Tip();
2316 pindexFork = chainActive.FindFork(pindexOldTip);
2317 fInitialDownload = IsInitialBlockDownload();
2319 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2320 assert(trace.pblock && trace.pindex);
2321 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2324 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2326 // Notifications/callbacks that can run without cs_main
2328 // Notify external listeners about the new tip.
2329 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2331 // Always notify the UI if a new block tip was connected
2332 if (pindexFork != pindexNewTip) {
2333 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2335 } while (pindexNewTip != pindexMostWork);
2336 CheckBlockIndex(chainparams.GetConsensus());
2338 // Write changes periodically to disk, after relay.
2339 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2340 return false;
2343 int nStopAtHeight = GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2344 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2346 return true;
2350 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2353 LOCK(cs_main);
2354 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2355 // Nothing to do, this block is not at the tip.
2356 return true;
2358 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2359 // The chain has been extended since the last call, reset the counter.
2360 nBlockReverseSequenceId = -1;
2362 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2363 setBlockIndexCandidates.erase(pindex);
2364 pindex->nSequenceId = nBlockReverseSequenceId;
2365 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2366 // We can't keep reducing the counter if somebody really wants to
2367 // call preciousblock 2**31-1 times on the same set of tips...
2368 nBlockReverseSequenceId--;
2370 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2371 setBlockIndexCandidates.insert(pindex);
2372 PruneBlockIndexCandidates();
2376 return ActivateBestChain(state, params);
2379 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2381 AssertLockHeld(cs_main);
2383 // Mark the block itself as invalid.
2384 pindex->nStatus |= BLOCK_FAILED_VALID;
2385 setDirtyBlockIndex.insert(pindex);
2386 setBlockIndexCandidates.erase(pindex);
2388 DisconnectedBlockTransactions disconnectpool;
2389 while (chainActive.Contains(pindex)) {
2390 CBlockIndex *pindexWalk = chainActive.Tip();
2391 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2392 setDirtyBlockIndex.insert(pindexWalk);
2393 setBlockIndexCandidates.erase(pindexWalk);
2394 // ActivateBestChain considers blocks already in chainActive
2395 // unconditionally valid already, so force disconnect away from it.
2396 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2397 // It's probably hopeless to try to make the mempool consistent
2398 // here if DisconnectTip failed, but we can try.
2399 UpdateMempoolForReorg(disconnectpool, false);
2400 return false;
2404 // DisconnectTip will add transactions to disconnectpool; try to add these
2405 // back to the mempool.
2406 UpdateMempoolForReorg(disconnectpool, true);
2408 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2409 // add it again.
2410 BlockMap::iterator it = mapBlockIndex.begin();
2411 while (it != mapBlockIndex.end()) {
2412 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2413 setBlockIndexCandidates.insert(it->second);
2415 it++;
2418 InvalidChainFound(pindex);
2419 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2420 return true;
2423 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2424 AssertLockHeld(cs_main);
2426 int nHeight = pindex->nHeight;
2428 // Remove the invalidity flag from this block and all its descendants.
2429 BlockMap::iterator it = mapBlockIndex.begin();
2430 while (it != mapBlockIndex.end()) {
2431 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2432 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2433 setDirtyBlockIndex.insert(it->second);
2434 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2435 setBlockIndexCandidates.insert(it->second);
2437 if (it->second == pindexBestInvalid) {
2438 // Reset invalid block marker if it was pointing to one of those.
2439 pindexBestInvalid = NULL;
2442 it++;
2445 // Remove the invalidity flag from all ancestors too.
2446 while (pindex != NULL) {
2447 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2448 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2449 setDirtyBlockIndex.insert(pindex);
2451 pindex = pindex->pprev;
2453 return true;
2456 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2458 // Check for duplicate
2459 uint256 hash = block.GetHash();
2460 BlockMap::iterator it = mapBlockIndex.find(hash);
2461 if (it != mapBlockIndex.end())
2462 return it->second;
2464 // Construct new block index object
2465 CBlockIndex* pindexNew = new CBlockIndex(block);
2466 assert(pindexNew);
2467 // We assign the sequence id to blocks only when the full data is available,
2468 // to avoid miners withholding blocks but broadcasting headers, to get a
2469 // competitive advantage.
2470 pindexNew->nSequenceId = 0;
2471 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2472 pindexNew->phashBlock = &((*mi).first);
2473 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2474 if (miPrev != mapBlockIndex.end())
2476 pindexNew->pprev = (*miPrev).second;
2477 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2478 pindexNew->BuildSkip();
2480 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2481 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2482 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2483 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2484 pindexBestHeader = pindexNew;
2486 setDirtyBlockIndex.insert(pindexNew);
2488 return pindexNew;
2491 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2492 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2494 pindexNew->nTx = block.vtx.size();
2495 pindexNew->nChainTx = 0;
2496 pindexNew->nFile = pos.nFile;
2497 pindexNew->nDataPos = pos.nPos;
2498 pindexNew->nUndoPos = 0;
2499 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2500 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2501 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2503 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2504 setDirtyBlockIndex.insert(pindexNew);
2506 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2507 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2508 std::deque<CBlockIndex*> queue;
2509 queue.push_back(pindexNew);
2511 // Recursively process any descendant blocks that now may be eligible to be connected.
2512 while (!queue.empty()) {
2513 CBlockIndex *pindex = queue.front();
2514 queue.pop_front();
2515 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2517 LOCK(cs_nBlockSequenceId);
2518 pindex->nSequenceId = nBlockSequenceId++;
2520 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2521 setBlockIndexCandidates.insert(pindex);
2523 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2524 while (range.first != range.second) {
2525 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2526 queue.push_back(it->second);
2527 range.first++;
2528 mapBlocksUnlinked.erase(it);
2531 } else {
2532 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2533 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2537 return true;
2540 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2542 LOCK(cs_LastBlockFile);
2544 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2545 if (vinfoBlockFile.size() <= nFile) {
2546 vinfoBlockFile.resize(nFile + 1);
2549 if (!fKnown) {
2550 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2551 nFile++;
2552 if (vinfoBlockFile.size() <= nFile) {
2553 vinfoBlockFile.resize(nFile + 1);
2556 pos.nFile = nFile;
2557 pos.nPos = vinfoBlockFile[nFile].nSize;
2560 if ((int)nFile != nLastBlockFile) {
2561 if (!fKnown) {
2562 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2564 FlushBlockFile(!fKnown);
2565 nLastBlockFile = nFile;
2568 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2569 if (fKnown)
2570 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2571 else
2572 vinfoBlockFile[nFile].nSize += nAddSize;
2574 if (!fKnown) {
2575 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2576 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2577 if (nNewChunks > nOldChunks) {
2578 if (fPruneMode)
2579 fCheckForPruning = true;
2580 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2581 FILE *file = OpenBlockFile(pos);
2582 if (file) {
2583 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2584 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2585 fclose(file);
2588 else
2589 return state.Error("out of disk space");
2593 setDirtyFileInfo.insert(nFile);
2594 return true;
2597 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2599 pos.nFile = nFile;
2601 LOCK(cs_LastBlockFile);
2603 unsigned int nNewSize;
2604 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2605 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2606 setDirtyFileInfo.insert(nFile);
2608 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2609 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2610 if (nNewChunks > nOldChunks) {
2611 if (fPruneMode)
2612 fCheckForPruning = true;
2613 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2614 FILE *file = OpenUndoFile(pos);
2615 if (file) {
2616 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2617 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2618 fclose(file);
2621 else
2622 return state.Error("out of disk space");
2625 return true;
2628 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW)
2630 // Check proof of work matches claimed amount
2631 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2632 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2634 return true;
2637 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2639 // These are checks that are independent of context.
2641 if (block.fChecked)
2642 return true;
2644 // Check that the header is valid (particularly PoW). This is mostly
2645 // redundant with the call in AcceptBlockHeader.
2646 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2647 return false;
2649 // Check the merkle root.
2650 if (fCheckMerkleRoot) {
2651 bool mutated;
2652 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2653 if (block.hashMerkleRoot != hashMerkleRoot2)
2654 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2656 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2657 // of transactions in a block without affecting the merkle root of a block,
2658 // while still invalidating it.
2659 if (mutated)
2660 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2663 // All potential-corruption validation must be done before we do any
2664 // transaction validation, as otherwise we may mark the header as invalid
2665 // because we receive the wrong transactions for it.
2666 // Note that witness malleability is checked in ContextualCheckBlock, so no
2667 // checks that use witness data may be performed here.
2669 // Size limits
2670 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)
2671 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2673 // First transaction must be coinbase, the rest must not be
2674 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2675 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2676 for (unsigned int i = 1; i < block.vtx.size(); i++)
2677 if (block.vtx[i]->IsCoinBase())
2678 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2680 // Check transactions
2681 for (const auto& tx : block.vtx)
2682 if (!CheckTransaction(*tx, state, false))
2683 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2684 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2686 unsigned int nSigOps = 0;
2687 for (const auto& tx : block.vtx)
2689 nSigOps += GetLegacySigOpCount(*tx);
2691 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2692 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2694 if (fCheckPOW && fCheckMerkleRoot)
2695 block.fChecked = true;
2697 return true;
2700 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2702 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2703 return true;
2705 int nHeight = pindexPrev->nHeight+1;
2706 // Don't accept any forks from the main chain prior to last checkpoint.
2707 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2708 // MapBlockIndex.
2709 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2710 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2711 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2713 return true;
2716 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2718 LOCK(cs_main);
2719 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2722 // Compute at which vout of the block's coinbase transaction the witness
2723 // commitment occurs, or -1 if not found.
2724 static int GetWitnessCommitmentIndex(const CBlock& block)
2726 int commitpos = -1;
2727 if (!block.vtx.empty()) {
2728 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2729 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) {
2730 commitpos = o;
2734 return commitpos;
2737 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2739 int commitpos = GetWitnessCommitmentIndex(block);
2740 static const std::vector<unsigned char> nonce(32, 0x00);
2741 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2742 CMutableTransaction tx(*block.vtx[0]);
2743 tx.vin[0].scriptWitness.stack.resize(1);
2744 tx.vin[0].scriptWitness.stack[0] = nonce;
2745 block.vtx[0] = MakeTransactionRef(std::move(tx));
2749 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2751 std::vector<unsigned char> commitment;
2752 int commitpos = GetWitnessCommitmentIndex(block);
2753 std::vector<unsigned char> ret(32, 0x00);
2754 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2755 if (commitpos == -1) {
2756 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2757 CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2758 CTxOut out;
2759 out.nValue = 0;
2760 out.scriptPubKey.resize(38);
2761 out.scriptPubKey[0] = OP_RETURN;
2762 out.scriptPubKey[1] = 0x24;
2763 out.scriptPubKey[2] = 0xaa;
2764 out.scriptPubKey[3] = 0x21;
2765 out.scriptPubKey[4] = 0xa9;
2766 out.scriptPubKey[5] = 0xed;
2767 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2768 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2769 CMutableTransaction tx(*block.vtx[0]);
2770 tx.vout.push_back(out);
2771 block.vtx[0] = MakeTransactionRef(std::move(tx));
2774 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2775 return commitment;
2778 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2780 assert(pindexPrev != NULL);
2781 const int nHeight = pindexPrev->nHeight + 1;
2782 // Check proof of work
2783 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2784 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2786 // Check timestamp against prev
2787 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2788 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2790 // Check timestamp
2791 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2792 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2794 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2795 // check for version 2, 3 and 4 upgrades
2796 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2797 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2798 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2799 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2800 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2802 return true;
2805 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2807 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2809 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2810 int nLockTimeFlags = 0;
2811 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2812 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2815 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2816 ? pindexPrev->GetMedianTimePast()
2817 : block.GetBlockTime();
2819 // Check that all transactions are finalized
2820 for (const auto& tx : block.vtx) {
2821 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2822 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2826 // Enforce rule that the coinbase starts with serialized block height
2827 if (nHeight >= consensusParams.BIP34Height)
2829 CScript expect = CScript() << nHeight;
2830 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2831 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2832 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2836 // Validation for witness commitments.
2837 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2838 // coinbase (where 0x0000....0000 is used instead).
2839 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2840 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2841 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2842 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2843 // multiple, the last one is used.
2844 bool fHaveWitness = false;
2845 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2846 int commitpos = GetWitnessCommitmentIndex(block);
2847 if (commitpos != -1) {
2848 bool malleated = false;
2849 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2850 // The malleation check is ignored; as the transaction tree itself
2851 // already does not permit it, it is impossible to trigger in the
2852 // witness tree.
2853 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
2854 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
2856 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
2857 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
2858 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
2860 fHaveWitness = true;
2864 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
2865 if (!fHaveWitness) {
2866 for (const auto& tx : block.vtx) {
2867 if (tx->HasWitness()) {
2868 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
2873 // After the coinbase witness nonce and commitment are verified,
2874 // we can check if the block weight passes (before we've checked the
2875 // coinbase witness, it would be possible for the weight to be too
2876 // large by filling up the coinbase witness, which doesn't change
2877 // the block hash, so we couldn't mark the block as permanently
2878 // failed).
2879 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
2880 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
2883 return true;
2886 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
2888 AssertLockHeld(cs_main);
2889 // Check for duplicate
2890 uint256 hash = block.GetHash();
2891 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2892 CBlockIndex *pindex = NULL;
2893 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2895 if (miSelf != mapBlockIndex.end()) {
2896 // Block header is already known.
2897 pindex = miSelf->second;
2898 if (ppindex)
2899 *ppindex = pindex;
2900 if (pindex->nStatus & BLOCK_FAILED_MASK)
2901 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
2902 return true;
2905 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
2906 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
2908 // Get prev block index
2909 CBlockIndex* pindexPrev = NULL;
2910 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2911 if (mi == mapBlockIndex.end())
2912 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
2913 pindexPrev = (*mi).second;
2914 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2915 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2917 assert(pindexPrev);
2918 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
2919 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2921 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
2922 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
2924 if (pindex == NULL)
2925 pindex = AddToBlockIndex(block);
2927 if (ppindex)
2928 *ppindex = pindex;
2930 CheckBlockIndex(chainparams.GetConsensus());
2932 return true;
2935 // Exposed wrapper for AcceptBlockHeader
2936 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
2939 LOCK(cs_main);
2940 for (const CBlockHeader& header : headers) {
2941 CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
2942 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
2943 return false;
2945 if (ppindex) {
2946 *ppindex = pindex;
2950 NotifyHeaderTip();
2951 return true;
2954 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
2955 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
2957 const CBlock& block = *pblock;
2959 if (fNewBlock) *fNewBlock = false;
2960 AssertLockHeld(cs_main);
2962 CBlockIndex *pindexDummy = NULL;
2963 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
2965 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
2966 return false;
2968 // Try to process all requested blocks that we don't have, but only
2969 // process an unrequested block if it's new and has enough work to
2970 // advance our tip, and isn't too many blocks ahead.
2971 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
2972 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
2973 // Blocks that are too out-of-order needlessly limit the effectiveness of
2974 // pruning, because pruning will not delete block files that contain any
2975 // blocks which are too close in height to the tip. Apply this test
2976 // regardless of whether pruning is enabled; it should generally be safe to
2977 // not process unrequested blocks.
2978 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
2980 // TODO: Decouple this function from the block download logic by removing fRequested
2981 // This requires some new chain data structure to efficiently look up if a
2982 // block is in a chain leading to a candidate for best tip, despite not
2983 // being such a candidate itself.
2985 // TODO: deal better with return value and error conditions for duplicate
2986 // and unrequested blocks.
2987 if (fAlreadyHave) return true;
2988 if (!fRequested) { // If we didn't ask for it:
2989 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
2990 if (!fHasMoreWork) return true; // Don't process less-work chains
2991 if (fTooFarAhead) return true; // Block height is too high
2993 if (fNewBlock) *fNewBlock = true;
2995 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
2996 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
2997 if (state.IsInvalid() && !state.CorruptionPossible()) {
2998 pindex->nStatus |= BLOCK_FAILED_VALID;
2999 setDirtyBlockIndex.insert(pindex);
3001 return error("%s: %s", __func__, FormatStateMessage(state));
3004 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3005 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3006 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3007 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3009 int nHeight = pindex->nHeight;
3011 // Write block to history file
3012 try {
3013 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3014 CDiskBlockPos blockPos;
3015 if (dbp != NULL)
3016 blockPos = *dbp;
3017 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3018 return error("AcceptBlock(): FindBlockPos failed");
3019 if (dbp == NULL)
3020 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3021 AbortNode(state, "Failed to write block");
3022 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3023 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3024 } catch (const std::runtime_error& e) {
3025 return AbortNode(state, std::string("System error: ") + e.what());
3028 if (fCheckForPruning)
3029 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3031 return true;
3034 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3037 CBlockIndex *pindex = NULL;
3038 if (fNewBlock) *fNewBlock = false;
3039 CValidationState state;
3040 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3041 // belt-and-suspenders.
3042 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3044 LOCK(cs_main);
3046 if (ret) {
3047 // Store to disk
3048 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3050 CheckBlockIndex(chainparams.GetConsensus());
3051 if (!ret) {
3052 GetMainSignals().BlockChecked(*pblock, state);
3053 return error("%s: AcceptBlock FAILED", __func__);
3057 NotifyHeaderTip();
3059 CValidationState state; // Only used to report errors, not invalidity - ignore it
3060 if (!ActivateBestChain(state, chainparams, pblock))
3061 return error("%s: ActivateBestChain failed", __func__);
3063 return true;
3066 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3068 AssertLockHeld(cs_main);
3069 assert(pindexPrev && pindexPrev == chainActive.Tip());
3070 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3071 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3073 CCoinsViewCache viewNew(pcoinsTip);
3074 CBlockIndex indexDummy(block);
3075 indexDummy.pprev = pindexPrev;
3076 indexDummy.nHeight = pindexPrev->nHeight + 1;
3078 // NOTE: CheckBlockHeader is called by CheckBlock
3079 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3080 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3081 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3082 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3083 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3084 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3085 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3086 return false;
3087 assert(state.IsValid());
3089 return true;
3093 * BLOCK PRUNING CODE
3096 /* Calculate the amount of disk space the block & undo files currently use */
3097 uint64_t CalculateCurrentUsage()
3099 uint64_t retval = 0;
3100 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3101 retval += file.nSize + file.nUndoSize;
3103 return retval;
3106 /* Prune a block file (modify associated database entries)*/
3107 void PruneOneBlockFile(const int fileNumber)
3109 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3110 CBlockIndex* pindex = it->second;
3111 if (pindex->nFile == fileNumber) {
3112 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3113 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3114 pindex->nFile = 0;
3115 pindex->nDataPos = 0;
3116 pindex->nUndoPos = 0;
3117 setDirtyBlockIndex.insert(pindex);
3119 // Prune from mapBlocksUnlinked -- any block we prune would have
3120 // to be downloaded again in order to consider its chain, at which
3121 // point it would be considered as a candidate for
3122 // mapBlocksUnlinked or setBlockIndexCandidates.
3123 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3124 while (range.first != range.second) {
3125 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3126 range.first++;
3127 if (_it->second == pindex) {
3128 mapBlocksUnlinked.erase(_it);
3134 vinfoBlockFile[fileNumber].SetNull();
3135 setDirtyFileInfo.insert(fileNumber);
3139 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3141 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3142 CDiskBlockPos pos(*it, 0);
3143 fs::remove(GetBlockPosFilename(pos, "blk"));
3144 fs::remove(GetBlockPosFilename(pos, "rev"));
3145 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3149 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3150 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3152 assert(fPruneMode && nManualPruneHeight > 0);
3154 LOCK2(cs_main, cs_LastBlockFile);
3155 if (chainActive.Tip() == NULL)
3156 return;
3158 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3159 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3160 int count=0;
3161 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3162 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3163 continue;
3164 PruneOneBlockFile(fileNumber);
3165 setFilesToPrune.insert(fileNumber);
3166 count++;
3168 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3171 /* This function is called from the RPC code for pruneblockchain */
3172 void PruneBlockFilesManual(int nManualPruneHeight)
3174 CValidationState state;
3175 FlushStateToDisk(state, FLUSH_STATE_NONE, nManualPruneHeight);
3178 /* Calculate the block/rev files that should be deleted to remain under target*/
3179 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3181 LOCK2(cs_main, cs_LastBlockFile);
3182 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3183 return;
3185 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3186 return;
3189 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3190 uint64_t nCurrentUsage = CalculateCurrentUsage();
3191 // We don't check to prune until after we've allocated new space for files
3192 // So we should leave a buffer under our target to account for another allocation
3193 // before the next pruning.
3194 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3195 uint64_t nBytesToPrune;
3196 int count=0;
3198 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3199 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3200 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3202 if (vinfoBlockFile[fileNumber].nSize == 0)
3203 continue;
3205 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3206 break;
3208 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3209 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3210 continue;
3212 PruneOneBlockFile(fileNumber);
3213 // Queue up the files for removal
3214 setFilesToPrune.insert(fileNumber);
3215 nCurrentUsage -= nBytesToPrune;
3216 count++;
3220 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3221 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3222 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3223 nLastBlockWeCanPrune, count);
3226 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3228 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3230 // Check for nMinDiskSpace bytes (currently 50MB)
3231 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3232 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3234 return true;
3237 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3239 if (pos.IsNull())
3240 return NULL;
3241 fs::path path = GetBlockPosFilename(pos, prefix);
3242 fs::create_directories(path.parent_path());
3243 FILE* file = fsbridge::fopen(path, "rb+");
3244 if (!file && !fReadOnly)
3245 file = fsbridge::fopen(path, "wb+");
3246 if (!file) {
3247 LogPrintf("Unable to open file %s\n", path.string());
3248 return NULL;
3250 if (pos.nPos) {
3251 if (fseek(file, pos.nPos, SEEK_SET)) {
3252 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3253 fclose(file);
3254 return NULL;
3257 return file;
3260 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3261 return OpenDiskFile(pos, "blk", fReadOnly);
3264 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3265 return OpenDiskFile(pos, "rev", fReadOnly);
3268 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3270 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3273 CBlockIndex * InsertBlockIndex(uint256 hash)
3275 if (hash.IsNull())
3276 return NULL;
3278 // Return existing
3279 BlockMap::iterator mi = mapBlockIndex.find(hash);
3280 if (mi != mapBlockIndex.end())
3281 return (*mi).second;
3283 // Create new
3284 CBlockIndex* pindexNew = new CBlockIndex();
3285 if (!pindexNew)
3286 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3287 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3288 pindexNew->phashBlock = &((*mi).first);
3290 return pindexNew;
3293 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3295 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3296 return false;
3298 boost::this_thread::interruption_point();
3300 // Calculate nChainWork
3301 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3302 vSortedByHeight.reserve(mapBlockIndex.size());
3303 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3305 CBlockIndex* pindex = item.second;
3306 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3308 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3309 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3311 CBlockIndex* pindex = item.second;
3312 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3313 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3314 // We can link the chain of blocks for which we've received transactions at some point.
3315 // Pruned nodes may have deleted the block.
3316 if (pindex->nTx > 0) {
3317 if (pindex->pprev) {
3318 if (pindex->pprev->nChainTx) {
3319 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3320 } else {
3321 pindex->nChainTx = 0;
3322 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3324 } else {
3325 pindex->nChainTx = pindex->nTx;
3328 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3329 setBlockIndexCandidates.insert(pindex);
3330 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3331 pindexBestInvalid = pindex;
3332 if (pindex->pprev)
3333 pindex->BuildSkip();
3334 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3335 pindexBestHeader = pindex;
3338 // Load block file info
3339 pblocktree->ReadLastBlockFile(nLastBlockFile);
3340 vinfoBlockFile.resize(nLastBlockFile + 1);
3341 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3342 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3343 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3345 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3346 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3347 CBlockFileInfo info;
3348 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3349 vinfoBlockFile.push_back(info);
3350 } else {
3351 break;
3355 // Check presence of blk files
3356 LogPrintf("Checking all blk files are present...\n");
3357 std::set<int> setBlkDataFiles;
3358 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3360 CBlockIndex* pindex = item.second;
3361 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3362 setBlkDataFiles.insert(pindex->nFile);
3365 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3367 CDiskBlockPos pos(*it, 0);
3368 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3369 return false;
3373 // Check whether we have ever pruned block & undo files
3374 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3375 if (fHavePruned)
3376 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3378 // Check whether we need to continue reindexing
3379 bool fReindexing = false;
3380 pblocktree->ReadReindexing(fReindexing);
3381 fReindex |= fReindexing;
3383 // Check whether we have a transaction index
3384 pblocktree->ReadFlag("txindex", fTxIndex);
3385 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3387 // Load pointer to end of best chain
3388 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3389 if (it == mapBlockIndex.end())
3390 return true;
3391 chainActive.SetTip(it->second);
3393 PruneBlockIndexCandidates();
3395 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3396 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3397 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3398 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3400 return true;
3403 CVerifyDB::CVerifyDB()
3405 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3408 CVerifyDB::~CVerifyDB()
3410 uiInterface.ShowProgress("", 100);
3413 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3415 LOCK(cs_main);
3416 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3417 return true;
3419 // Verify blocks in the best chain
3420 if (nCheckDepth <= 0)
3421 nCheckDepth = 1000000000; // suffices until the year 19000
3422 if (nCheckDepth > chainActive.Height())
3423 nCheckDepth = chainActive.Height();
3424 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3425 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3426 CCoinsViewCache coins(coinsview);
3427 CBlockIndex* pindexState = chainActive.Tip();
3428 CBlockIndex* pindexFailure = NULL;
3429 int nGoodTransactions = 0;
3430 CValidationState state;
3431 int reportDone = 0;
3432 LogPrintf("[0%%]...");
3433 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3435 boost::this_thread::interruption_point();
3436 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3437 if (reportDone < percentageDone/10) {
3438 // report every 10% step
3439 LogPrintf("[%d%%]...", percentageDone);
3440 reportDone = percentageDone/10;
3442 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3443 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3444 break;
3445 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3446 // If pruning, only go back as far as we have data.
3447 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3448 break;
3450 CBlock block;
3451 // check level 0: read from disk
3452 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3453 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3454 // check level 1: verify block validity
3455 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3456 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3457 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3458 // check level 2: verify undo validity
3459 if (nCheckLevel >= 2 && pindex) {
3460 CBlockUndo undo;
3461 CDiskBlockPos pos = pindex->GetUndoPos();
3462 if (!pos.IsNull()) {
3463 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3464 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3467 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3468 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3469 DisconnectResult res = DisconnectBlock(block, pindex, coins);
3470 if (res == DISCONNECT_FAILED) {
3471 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3473 pindexState = pindex->pprev;
3474 if (res == DISCONNECT_UNCLEAN) {
3475 nGoodTransactions = 0;
3476 pindexFailure = pindex;
3477 } else {
3478 nGoodTransactions += block.vtx.size();
3481 if (ShutdownRequested())
3482 return true;
3484 if (pindexFailure)
3485 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3487 // check level 4: try reconnecting blocks
3488 if (nCheckLevel >= 4) {
3489 CBlockIndex *pindex = pindexState;
3490 while (pindex != chainActive.Tip()) {
3491 boost::this_thread::interruption_point();
3492 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3493 pindex = chainActive.Next(pindex);
3494 CBlock block;
3495 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3496 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3497 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3498 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3502 LogPrintf("[DONE].\n");
3503 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3505 return true;
3508 bool RewindBlockIndex(const CChainParams& params)
3510 LOCK(cs_main);
3512 int nHeight = 1;
3513 while (nHeight <= chainActive.Height()) {
3514 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3515 break;
3517 nHeight++;
3520 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3521 CValidationState state;
3522 CBlockIndex* pindex = chainActive.Tip();
3523 while (chainActive.Height() >= nHeight) {
3524 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3525 // If pruning, don't try rewinding past the HAVE_DATA point;
3526 // since older blocks can't be served anyway, there's
3527 // no need to walk further, and trying to DisconnectTip()
3528 // will fail (and require a needless reindex/redownload
3529 // of the blockchain).
3530 break;
3532 if (!DisconnectTip(state, params, NULL)) {
3533 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3535 // Occasionally flush state to disk.
3536 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3537 return false;
3540 // Reduce validity flag and have-data flags.
3541 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3542 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3543 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3544 CBlockIndex* pindexIter = it->second;
3546 // Note: If we encounter an insufficiently validated block that
3547 // is on chainActive, it must be because we are a pruning node, and
3548 // this block or some successor doesn't HAVE_DATA, so we were unable to
3549 // rewind all the way. Blocks remaining on chainActive at this point
3550 // must not have their validity reduced.
3551 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3552 // Reduce validity
3553 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3554 // Remove have-data flags.
3555 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3556 // Remove storage location.
3557 pindexIter->nFile = 0;
3558 pindexIter->nDataPos = 0;
3559 pindexIter->nUndoPos = 0;
3560 // Remove various other things
3561 pindexIter->nTx = 0;
3562 pindexIter->nChainTx = 0;
3563 pindexIter->nSequenceId = 0;
3564 // Make sure it gets written.
3565 setDirtyBlockIndex.insert(pindexIter);
3566 // Update indexes
3567 setBlockIndexCandidates.erase(pindexIter);
3568 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3569 while (ret.first != ret.second) {
3570 if (ret.first->second == pindexIter) {
3571 mapBlocksUnlinked.erase(ret.first++);
3572 } else {
3573 ++ret.first;
3576 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3577 setBlockIndexCandidates.insert(pindexIter);
3581 PruneBlockIndexCandidates();
3583 CheckBlockIndex(params.GetConsensus());
3585 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3586 return false;
3589 return true;
3592 // May NOT be used after any connections are up as much
3593 // of the peer-processing logic assumes a consistent
3594 // block index state
3595 void UnloadBlockIndex()
3597 LOCK(cs_main);
3598 setBlockIndexCandidates.clear();
3599 chainActive.SetTip(NULL);
3600 pindexBestInvalid = NULL;
3601 pindexBestHeader = NULL;
3602 mempool.clear();
3603 mapBlocksUnlinked.clear();
3604 vinfoBlockFile.clear();
3605 nLastBlockFile = 0;
3606 nBlockSequenceId = 1;
3607 setDirtyBlockIndex.clear();
3608 setDirtyFileInfo.clear();
3609 versionbitscache.Clear();
3610 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3611 warningcache[b].clear();
3614 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3615 delete entry.second;
3617 mapBlockIndex.clear();
3618 fHavePruned = false;
3621 bool LoadBlockIndex(const CChainParams& chainparams)
3623 // Load block index from databases
3624 if (!fReindex && !LoadBlockIndexDB(chainparams))
3625 return false;
3626 return true;
3629 bool InitBlockIndex(const CChainParams& chainparams)
3631 LOCK(cs_main);
3633 // Check whether we're already initialized
3634 if (chainActive.Genesis() != NULL)
3635 return true;
3637 // Use the provided setting for -txindex in the new database
3638 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3639 pblocktree->WriteFlag("txindex", fTxIndex);
3640 LogPrintf("Initializing databases...\n");
3642 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3643 if (!fReindex) {
3644 try {
3645 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3646 // Start new block file
3647 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3648 CDiskBlockPos blockPos;
3649 CValidationState state;
3650 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3651 return error("LoadBlockIndex(): FindBlockPos failed");
3652 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3653 return error("LoadBlockIndex(): writing genesis block to disk failed");
3654 CBlockIndex *pindex = AddToBlockIndex(block);
3655 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3656 return error("LoadBlockIndex(): genesis block not accepted");
3657 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3658 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3659 } catch (const std::runtime_error& e) {
3660 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3664 return true;
3667 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3669 // Map of disk positions for blocks with unknown parent (only used for reindex)
3670 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3671 int64_t nStart = GetTimeMillis();
3673 int nLoaded = 0;
3674 try {
3675 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3676 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3677 uint64_t nRewind = blkdat.GetPos();
3678 while (!blkdat.eof()) {
3679 boost::this_thread::interruption_point();
3681 blkdat.SetPos(nRewind);
3682 nRewind++; // start one byte further next time, in case of failure
3683 blkdat.SetLimit(); // remove former limit
3684 unsigned int nSize = 0;
3685 try {
3686 // locate a header
3687 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3688 blkdat.FindByte(chainparams.MessageStart()[0]);
3689 nRewind = blkdat.GetPos()+1;
3690 blkdat >> FLATDATA(buf);
3691 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3692 continue;
3693 // read size
3694 blkdat >> nSize;
3695 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3696 continue;
3697 } catch (const std::exception&) {
3698 // no valid block header found; don't complain
3699 break;
3701 try {
3702 // read block
3703 uint64_t nBlockPos = blkdat.GetPos();
3704 if (dbp)
3705 dbp->nPos = nBlockPos;
3706 blkdat.SetLimit(nBlockPos + nSize);
3707 blkdat.SetPos(nBlockPos);
3708 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3709 CBlock& block = *pblock;
3710 blkdat >> block;
3711 nRewind = blkdat.GetPos();
3713 // detect out of order blocks, and store them for later
3714 uint256 hash = block.GetHash();
3715 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3716 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3717 block.hashPrevBlock.ToString());
3718 if (dbp)
3719 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3720 continue;
3723 // process in case the block isn't known yet
3724 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3725 LOCK(cs_main);
3726 CValidationState state;
3727 if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3728 nLoaded++;
3729 if (state.IsError())
3730 break;
3731 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3732 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3735 // Activate the genesis block so normal node progress can continue
3736 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3737 CValidationState state;
3738 if (!ActivateBestChain(state, chainparams)) {
3739 break;
3743 NotifyHeaderTip();
3745 // Recursively process earlier encountered successors of this block
3746 std::deque<uint256> queue;
3747 queue.push_back(hash);
3748 while (!queue.empty()) {
3749 uint256 head = queue.front();
3750 queue.pop_front();
3751 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3752 while (range.first != range.second) {
3753 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3754 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
3755 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
3757 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
3758 head.ToString());
3759 LOCK(cs_main);
3760 CValidationState dummy;
3761 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
3763 nLoaded++;
3764 queue.push_back(pblockrecursive->GetHash());
3767 range.first++;
3768 mapBlocksUnknownParent.erase(it);
3769 NotifyHeaderTip();
3772 } catch (const std::exception& e) {
3773 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3776 } catch (const std::runtime_error& e) {
3777 AbortNode(std::string("System error: ") + e.what());
3779 if (nLoaded > 0)
3780 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3781 return nLoaded > 0;
3784 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3786 if (!fCheckBlockIndex) {
3787 return;
3790 LOCK(cs_main);
3792 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3793 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3794 // iterating the block tree require that chainActive has been initialized.)
3795 if (chainActive.Height() < 0) {
3796 assert(mapBlockIndex.size() <= 1);
3797 return;
3800 // Build forward-pointing map of the entire block tree.
3801 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3802 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3803 forward.insert(std::make_pair(it->second->pprev, it->second));
3806 assert(forward.size() == mapBlockIndex.size());
3808 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3809 CBlockIndex *pindex = rangeGenesis.first->second;
3810 rangeGenesis.first++;
3811 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3813 // Iterate over the entire block tree, using depth-first search.
3814 // Along the way, remember whether there are blocks on the path from genesis
3815 // block being explored which are the first to have certain properties.
3816 size_t nNodes = 0;
3817 int nHeight = 0;
3818 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3819 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3820 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3821 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3822 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3823 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3824 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3825 while (pindex != NULL) {
3826 nNodes++;
3827 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3828 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3829 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3830 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3831 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3832 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3833 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3835 // Begin: actual consistency checks.
3836 if (pindex->pprev == NULL) {
3837 // Genesis block checks.
3838 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3839 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3841 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)
3842 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3843 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3844 if (!fHavePruned) {
3845 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3846 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3847 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3848 } else {
3849 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3850 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3852 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3853 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3854 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3855 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3856 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3857 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3858 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.
3859 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3860 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3861 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3862 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3863 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3864 if (pindexFirstInvalid == NULL) {
3865 // Checks for not-invalid blocks.
3866 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3868 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3869 if (pindexFirstInvalid == NULL) {
3870 // If this block sorts at least as good as the current tip and
3871 // is valid and we have all data for its parents, it must be in
3872 // setBlockIndexCandidates. chainActive.Tip() must also be there
3873 // even if some data has been pruned.
3874 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3875 assert(setBlockIndexCandidates.count(pindex));
3877 // If some parent is missing, then it could be that this block was in
3878 // setBlockIndexCandidates but had to be removed because of the missing data.
3879 // In this case it must be in mapBlocksUnlinked -- see test below.
3881 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3882 assert(setBlockIndexCandidates.count(pindex) == 0);
3884 // Check whether this block is in mapBlocksUnlinked.
3885 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3886 bool foundInUnlinked = false;
3887 while (rangeUnlinked.first != rangeUnlinked.second) {
3888 assert(rangeUnlinked.first->first == pindex->pprev);
3889 if (rangeUnlinked.first->second == pindex) {
3890 foundInUnlinked = true;
3891 break;
3893 rangeUnlinked.first++;
3895 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3896 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3897 assert(foundInUnlinked);
3899 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3900 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3901 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3902 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3903 assert(fHavePruned); // We must have pruned.
3904 // This block may have entered mapBlocksUnlinked if:
3905 // - it has a descendant that at some point had more work than the
3906 // tip, and
3907 // - we tried switching to that descendant but were missing
3908 // data for some intermediate block between chainActive and the
3909 // tip.
3910 // So if this block is itself better than chainActive.Tip() and it wasn't in
3911 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3912 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3913 if (pindexFirstInvalid == NULL) {
3914 assert(foundInUnlinked);
3918 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3919 // End: actual consistency checks.
3921 // Try descending into the first subnode.
3922 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3923 if (range.first != range.second) {
3924 // A subnode was found.
3925 pindex = range.first->second;
3926 nHeight++;
3927 continue;
3929 // This is a leaf node.
3930 // Move upwards until we reach a node of which we have not yet visited the last child.
3931 while (pindex) {
3932 // We are going to either move to a parent or a sibling of pindex.
3933 // If pindex was the first with a certain property, unset the corresponding variable.
3934 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3935 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3936 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3937 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3938 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3939 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3940 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3941 // Find our parent.
3942 CBlockIndex* pindexPar = pindex->pprev;
3943 // Find which child we just visited.
3944 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3945 while (rangePar.first->second != pindex) {
3946 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3947 rangePar.first++;
3949 // Proceed to the next one.
3950 rangePar.first++;
3951 if (rangePar.first != rangePar.second) {
3952 // Move to the sibling.
3953 pindex = rangePar.first->second;
3954 break;
3955 } else {
3956 // Move up further.
3957 pindex = pindexPar;
3958 nHeight--;
3959 continue;
3964 // Check that we actually traversed the entire map.
3965 assert(nNodes == forward.size());
3968 std::string CBlockFileInfo::ToString() const
3970 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));
3973 CBlockFileInfo* GetBlockFileInfo(size_t n)
3975 return &vinfoBlockFile.at(n);
3978 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
3980 LOCK(cs_main);
3981 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
3984 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
3986 LOCK(cs_main);
3987 return VersionBitsStatistics(chainActive.Tip(), params, pos);
3990 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
3992 LOCK(cs_main);
3993 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
3996 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
3998 bool LoadMempool(void)
4000 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4001 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4002 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4003 if (file.IsNull()) {
4004 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4005 return false;
4008 int64_t count = 0;
4009 int64_t skipped = 0;
4010 int64_t failed = 0;
4011 int64_t nNow = GetTime();
4013 try {
4014 uint64_t version;
4015 file >> version;
4016 if (version != MEMPOOL_DUMP_VERSION) {
4017 return false;
4019 uint64_t num;
4020 file >> num;
4021 while (num--) {
4022 CTransactionRef tx;
4023 int64_t nTime;
4024 int64_t nFeeDelta;
4025 file >> tx;
4026 file >> nTime;
4027 file >> nFeeDelta;
4029 CAmount amountdelta = nFeeDelta;
4030 if (amountdelta) {
4031 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4033 CValidationState state;
4034 if (nTime + nExpiryTimeout > nNow) {
4035 LOCK(cs_main);
4036 AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
4037 if (state.IsValid()) {
4038 ++count;
4039 } else {
4040 ++failed;
4042 } else {
4043 ++skipped;
4045 if (ShutdownRequested())
4046 return false;
4048 std::map<uint256, CAmount> mapDeltas;
4049 file >> mapDeltas;
4051 for (const auto& i : mapDeltas) {
4052 mempool.PrioritiseTransaction(i.first, i.second);
4054 } catch (const std::exception& e) {
4055 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4056 return false;
4059 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4060 return true;
4063 void DumpMempool(void)
4065 int64_t start = GetTimeMicros();
4067 std::map<uint256, CAmount> mapDeltas;
4068 std::vector<TxMempoolInfo> vinfo;
4071 LOCK(mempool.cs);
4072 for (const auto &i : mempool.mapDeltas) {
4073 mapDeltas[i.first] = i.second;
4075 vinfo = mempool.infoAll();
4078 int64_t mid = GetTimeMicros();
4080 try {
4081 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4082 if (!filestr) {
4083 return;
4086 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4088 uint64_t version = MEMPOOL_DUMP_VERSION;
4089 file << version;
4091 file << (uint64_t)vinfo.size();
4092 for (const auto& i : vinfo) {
4093 file << *(i.tx);
4094 file << (int64_t)i.nTime;
4095 file << (int64_t)i.nFeeDelta;
4096 mapDeltas.erase(i.tx->GetHash());
4099 file << mapDeltas;
4100 FileCommit(file.Get());
4101 file.fclose();
4102 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4103 int64_t last = GetTimeMicros();
4104 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4105 } catch (const std::exception& e) {
4106 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4110 //! Guess how far we are in the verification process at the given block index
4111 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4112 if (pindex == NULL)
4113 return 0.0;
4115 int64_t nNow = time(NULL);
4117 double fTxTotal;
4119 if (pindex->nChainTx <= data.nTxCount) {
4120 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4121 } else {
4122 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4125 return pindex->nChainTx / fTxTotal;
4128 class CMainCleanup
4130 public:
4131 CMainCleanup() {}
4132 ~CMainCleanup() {
4133 // block headers
4134 BlockMap::iterator it1 = mapBlockIndex.begin();
4135 for (; it1 != mapBlockIndex.end(); it1++)
4136 delete (*it1).second;
4137 mapBlockIndex.clear();
4139 } instance_of_cmaincleanup;