[trivial] Add end of namespace comments
[bitcoinplatinum.git] / src / validation.cpp
blob3198a7529779f20e2d13bdd47816a3dbd4b1630f
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/validation.h"
16 #include "fs.h"
17 #include "hash.h"
18 #include "init.h"
19 #include "policy/fees.h"
20 #include "policy/policy.h"
21 #include "pow.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "random.h"
25 #include "script/script.h"
26 #include "script/sigcache.h"
27 #include "script/standard.h"
28 #include "timedata.h"
29 #include "tinyformat.h"
30 #include "txdb.h"
31 #include "txmempool.h"
32 #include "ui_interface.h"
33 #include "undo.h"
34 #include "util.h"
35 #include "utilmoneystr.h"
36 #include "utilstrencodings.h"
37 #include "validationinterface.h"
38 #include "versionbits.h"
39 #include "warnings.h"
41 #include <atomic>
42 #include <sstream>
44 #include <boost/algorithm/string/replace.hpp>
45 #include <boost/algorithm/string/join.hpp>
46 #include <boost/math/distributions/poisson.hpp>
47 #include <boost/thread.hpp>
49 #if defined(NDEBUG)
50 # error "Bitcoin cannot be compiled without assertions."
51 #endif
53 /**
54 * Global state
57 CCriticalSection cs_main;
59 BlockMap mapBlockIndex;
60 CChain chainActive;
61 CBlockIndex *pindexBestHeader = NULL;
62 CWaitableCriticalSection csBestBlock;
63 CConditionVariable cvBlockChange;
64 int nScriptCheckThreads = 0;
65 std::atomic_bool fImporting(false);
66 bool fReindex = false;
67 bool fTxIndex = false;
68 bool fHavePruned = false;
69 bool fPruneMode = false;
70 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
71 bool fRequireStandard = true;
72 bool fCheckBlockIndex = false;
73 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
74 size_t nCoinCacheUsage = 5000 * 300;
75 uint64_t nPruneTarget = 0;
76 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
77 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
79 uint256 hashAssumeValid;
81 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
82 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
84 CBlockPolicyEstimator feeEstimator;
85 CTxMemPool mempool(&feeEstimator);
87 static void CheckBlockIndex(const Consensus::Params& consensusParams);
89 /** Constant stuff for coinbase transactions we create: */
90 CScript COINBASE_FLAGS;
92 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
94 // Internal stuff
95 namespace {
97 struct CBlockIndexWorkComparator
99 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
100 // First sort by most total work, ...
101 if (pa->nChainWork > pb->nChainWork) return false;
102 if (pa->nChainWork < pb->nChainWork) return true;
104 // ... then by earliest time received, ...
105 if (pa->nSequenceId < pb->nSequenceId) return false;
106 if (pa->nSequenceId > pb->nSequenceId) return true;
108 // Use pointer address as tie breaker (should only happen with blocks
109 // loaded from disk, as those all have id 0).
110 if (pa < pb) return false;
111 if (pa > pb) return true;
113 // Identical blocks.
114 return false;
118 CBlockIndex *pindexBestInvalid;
121 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
122 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
123 * missing the data for the block.
125 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
126 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
127 * Pruned nodes may have entries where B is missing data.
129 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
131 CCriticalSection cs_LastBlockFile;
132 std::vector<CBlockFileInfo> vinfoBlockFile;
133 int nLastBlockFile = 0;
134 /** Global flag to indicate we should check to see if there are
135 * block/undo files that should be deleted. Set on startup
136 * or if we allocate more file space when we're in prune mode
138 bool fCheckForPruning = false;
141 * Every received block is assigned a unique and increasing identifier, so we
142 * know which one to give priority in case of a fork.
144 CCriticalSection cs_nBlockSequenceId;
145 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
146 int32_t nBlockSequenceId = 1;
147 /** Decreasing counter (used by subsequent preciousblock calls). */
148 int32_t nBlockReverseSequenceId = -1;
149 /** chainwork for the last block that preciousblock has been applied to. */
150 arith_uint256 nLastPreciousChainwork = 0;
152 /** Dirty block index entries. */
153 std::set<CBlockIndex*> setDirtyBlockIndex;
155 /** Dirty block file entries. */
156 std::set<int> setDirtyFileInfo;
157 } // anon namespace
159 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
161 // Find the first block the caller has in the main chain
162 BOOST_FOREACH(const uint256& hash, locator.vHave) {
163 BlockMap::iterator mi = mapBlockIndex.find(hash);
164 if (mi != mapBlockIndex.end())
166 CBlockIndex* pindex = (*mi).second;
167 if (chain.Contains(pindex))
168 return pindex;
169 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
170 return chain.Tip();
174 return chain.Genesis();
177 CCoinsViewCache *pcoinsTip = NULL;
178 CBlockTreeDB *pblocktree = NULL;
180 enum FlushStateMode {
181 FLUSH_STATE_NONE,
182 FLUSH_STATE_IF_NEEDED,
183 FLUSH_STATE_PERIODIC,
184 FLUSH_STATE_ALWAYS
187 // See definition for documentation
188 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
189 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
191 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
193 if (tx.nLockTime == 0)
194 return true;
195 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
196 return true;
197 for (const auto& txin : tx.vin) {
198 if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
199 return false;
201 return true;
204 bool CheckFinalTx(const CTransaction &tx, int flags)
206 AssertLockHeld(cs_main);
208 // By convention a negative value for flags indicates that the
209 // current network-enforced consensus rules should be used. In
210 // a future soft-fork scenario that would mean checking which
211 // rules would be enforced for the next block and setting the
212 // appropriate flags. At the present time no soft-forks are
213 // scheduled, so no flags are set.
214 flags = std::max(flags, 0);
216 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
217 // nLockTime because when IsFinalTx() is called within
218 // CBlock::AcceptBlock(), the height of the block *being*
219 // evaluated is what is used. Thus if we want to know if a
220 // transaction can be part of the *next* block, we need to call
221 // IsFinalTx() with one more than chainActive.Height().
222 const int nBlockHeight = chainActive.Height() + 1;
224 // BIP113 will require that time-locked transactions have nLockTime set to
225 // less than the median time of the previous block they're contained in.
226 // When the next block is created its previous block will be the current
227 // chain tip, so we use that to calculate the median time passed to
228 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
229 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
230 ? chainActive.Tip()->GetMedianTimePast()
231 : GetAdjustedTime();
233 return IsFinalTx(tx, nBlockHeight, nBlockTime);
237 * Calculates the block height and previous block's median time past at
238 * which the transaction will be considered final in the context of BIP 68.
239 * Also removes from the vector of input heights any entries which did not
240 * correspond to sequence locked inputs as they do not affect the calculation.
242 static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
244 assert(prevHeights->size() == tx.vin.size());
246 // Will be set to the equivalent height- and time-based nLockTime
247 // values that would be necessary to satisfy all relative lock-
248 // time constraints given our view of block chain history.
249 // The semantics of nLockTime are the last invalid height/time, so
250 // use -1 to have the effect of any height or time being valid.
251 int nMinHeight = -1;
252 int64_t nMinTime = -1;
254 // tx.nVersion is signed integer so requires cast to unsigned otherwise
255 // we would be doing a signed comparison and half the range of nVersion
256 // wouldn't support BIP 68.
257 bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
258 && flags & LOCKTIME_VERIFY_SEQUENCE;
260 // Do not enforce sequence numbers as a relative lock time
261 // unless we have been instructed to
262 if (!fEnforceBIP68) {
263 return std::make_pair(nMinHeight, nMinTime);
266 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
267 const CTxIn& txin = tx.vin[txinIndex];
269 // Sequence numbers with the most significant bit set are not
270 // treated as relative lock-times, nor are they given any
271 // consensus-enforced meaning at this point.
272 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
273 // The height of this input is not relevant for sequence locks
274 (*prevHeights)[txinIndex] = 0;
275 continue;
278 int nCoinHeight = (*prevHeights)[txinIndex];
280 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
281 int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
282 // NOTE: Subtract 1 to maintain nLockTime semantics
283 // BIP 68 relative lock times have the semantics of calculating
284 // the first block or time at which the transaction would be
285 // valid. When calculating the effective block time or height
286 // for the entire transaction, we switch to using the
287 // semantics of nLockTime which is the last invalid block
288 // time or height. Thus we subtract 1 from the calculated
289 // time or height.
291 // Time-based relative lock-times are measured from the
292 // smallest allowed timestamp of the block containing the
293 // txout being spent, which is the median time past of the
294 // block prior.
295 nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
296 } else {
297 nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
301 return std::make_pair(nMinHeight, nMinTime);
304 static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
306 assert(block.pprev);
307 int64_t nBlockTime = block.pprev->GetMedianTimePast();
308 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
309 return false;
311 return true;
314 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
316 return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
319 bool TestLockPointValidity(const LockPoints* lp)
321 AssertLockHeld(cs_main);
322 assert(lp);
323 // If there are relative lock times then the maxInputBlock will be set
324 // If there are no relative lock times, the LockPoints don't depend on the chain
325 if (lp->maxInputBlock) {
326 // Check whether chainActive is an extension of the block at which the LockPoints
327 // calculation was valid. If not LockPoints are no longer valid
328 if (!chainActive.Contains(lp->maxInputBlock)) {
329 return false;
333 // LockPoints still valid
334 return true;
337 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
339 AssertLockHeld(cs_main);
340 AssertLockHeld(mempool.cs);
342 CBlockIndex* tip = chainActive.Tip();
343 CBlockIndex index;
344 index.pprev = tip;
345 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
346 // height based locks because when SequenceLocks() is called within
347 // ConnectBlock(), the height of the block *being*
348 // evaluated is what is used.
349 // Thus if we want to know if a transaction can be part of the
350 // *next* block, we need to use one more than chainActive.Height()
351 index.nHeight = tip->nHeight + 1;
353 std::pair<int, int64_t> lockPair;
354 if (useExistingLockPoints) {
355 assert(lp);
356 lockPair.first = lp->height;
357 lockPair.second = lp->time;
359 else {
360 // pcoinsTip contains the UTXO set for chainActive.Tip()
361 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
362 std::vector<int> prevheights;
363 prevheights.resize(tx.vin.size());
364 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
365 const CTxIn& txin = tx.vin[txinIndex];
366 CCoins coins;
367 if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
368 return error("%s: Missing input", __func__);
370 if (coins.nHeight == MEMPOOL_HEIGHT) {
371 // Assume all mempool transaction confirm in the next block
372 prevheights[txinIndex] = tip->nHeight + 1;
373 } else {
374 prevheights[txinIndex] = coins.nHeight;
377 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
378 if (lp) {
379 lp->height = lockPair.first;
380 lp->time = lockPair.second;
381 // Also store the hash of the block with the highest height of
382 // all the blocks which have sequence locked prevouts.
383 // This hash needs to still be on the chain
384 // for these LockPoint calculations to be valid
385 // Note: It is impossible to correctly calculate a maxInputBlock
386 // if any of the sequence locked inputs depend on unconfirmed txs,
387 // except in the special case where the relative lock time/height
388 // is 0, which is equivalent to no sequence lock. Since we assume
389 // input height of tip+1 for mempool txs and test the resulting
390 // lockPair from CalculateSequenceLocks against tip+1. We know
391 // EvaluateSequenceLocks will fail if there was a non-zero sequence
392 // lock on a mempool input, so we can use the return value of
393 // CheckSequenceLocks to indicate the LockPoints validity
394 int maxInputHeight = 0;
395 BOOST_FOREACH(int height, prevheights) {
396 // Can ignore mempool inputs since we'll fail if they had non-zero locks
397 if (height != tip->nHeight+1) {
398 maxInputHeight = std::max(maxInputHeight, height);
401 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
404 return EvaluateSequenceLocks(index, lockPair);
408 unsigned int GetLegacySigOpCount(const CTransaction& tx)
410 unsigned int nSigOps = 0;
411 for (const auto& txin : tx.vin)
413 nSigOps += txin.scriptSig.GetSigOpCount(false);
415 for (const auto& txout : tx.vout)
417 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
419 return nSigOps;
422 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
424 if (tx.IsCoinBase())
425 return 0;
427 unsigned int nSigOps = 0;
428 for (unsigned int i = 0; i < tx.vin.size(); i++)
430 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
431 if (prevout.scriptPubKey.IsPayToScriptHash())
432 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
434 return nSigOps;
437 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
439 int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
441 if (tx.IsCoinBase())
442 return nSigOps;
444 if (flags & SCRIPT_VERIFY_P2SH) {
445 nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
448 for (unsigned int i = 0; i < tx.vin.size(); i++)
450 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
451 nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
453 return nSigOps;
460 bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)
462 // Basic checks that don't depend on any context
463 if (tx.vin.empty())
464 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
465 if (tx.vout.empty())
466 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
467 // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
468 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
469 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
471 // Check for negative or overflow output values
472 CAmount nValueOut = 0;
473 for (const auto& txout : tx.vout)
475 if (txout.nValue < 0)
476 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
477 if (txout.nValue > MAX_MONEY)
478 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
479 nValueOut += txout.nValue;
480 if (!MoneyRange(nValueOut))
481 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
484 // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
485 if (fCheckDuplicateInputs) {
486 std::set<COutPoint> vInOutPoints;
487 for (const auto& txin : tx.vin)
489 if (!vInOutPoints.insert(txin.prevout).second)
490 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
494 if (tx.IsCoinBase())
496 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
497 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
499 else
501 for (const auto& txin : tx.vin)
502 if (txin.prevout.IsNull())
503 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
506 return true;
509 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
510 int expired = pool.Expire(GetTime() - age);
511 if (expired != 0) {
512 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
515 std::vector<uint256> vNoSpendsRemaining;
516 pool.TrimToSize(limit, &vNoSpendsRemaining);
517 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
518 pcoinsTip->Uncache(removed);
521 /** Convert CValidationState to a human-readable message for logging */
522 std::string FormatStateMessage(const CValidationState &state)
524 return strprintf("%s%s (code %i)",
525 state.GetRejectReason(),
526 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
527 state.GetRejectCode());
530 static bool IsCurrentForFeeEstimation()
532 AssertLockHeld(cs_main);
533 if (IsInitialBlockDownload())
534 return false;
535 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
536 return false;
537 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
538 return false;
539 return true;
542 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
543 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
544 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
546 const CTransaction& tx = *ptx;
547 const uint256 hash = tx.GetHash();
548 AssertLockHeld(cs_main);
549 if (pfMissingInputs)
550 *pfMissingInputs = false;
552 if (!CheckTransaction(tx, state))
553 return false; // state filled in by CheckTransaction
555 // Coinbase is only valid in a block, not as a loose transaction
556 if (tx.IsCoinBase())
557 return state.DoS(100, false, REJECT_INVALID, "coinbase");
559 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
560 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus());
561 if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
562 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
565 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
566 std::string reason;
567 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
568 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
570 // Only accept nLockTime-using transactions that can be mined in the next
571 // block; we don't want our mempool filled up with transactions that can't
572 // be mined yet.
573 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
574 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
576 // is it already in the memory pool?
577 if (pool.exists(hash))
578 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
580 // Check for conflicts with in-memory transactions
581 std::set<uint256> setConflicts;
583 LOCK(pool.cs); // protect pool.mapNextTx
584 BOOST_FOREACH(const CTxIn &txin, tx.vin)
586 auto itConflicting = pool.mapNextTx.find(txin.prevout);
587 if (itConflicting != pool.mapNextTx.end())
589 const CTransaction *ptxConflicting = itConflicting->second;
590 if (!setConflicts.count(ptxConflicting->GetHash()))
592 // Allow opt-out of transaction replacement by setting
593 // nSequence >= maxint-1 on all inputs.
595 // maxint-1 is picked to still allow use of nLockTime by
596 // non-replaceable transactions. All inputs rather than just one
597 // is for the sake of multi-party protocols, where we don't
598 // want a single party to be able to disable replacement.
600 // The opt-out ignores descendants as anyone relying on
601 // first-seen mempool behavior should be checking all
602 // unconfirmed ancestors anyway; doing otherwise is hopelessly
603 // insecure.
604 bool fReplacementOptOut = true;
605 if (fEnableReplacement)
607 BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
609 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
611 fReplacementOptOut = false;
612 break;
616 if (fReplacementOptOut)
617 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
619 setConflicts.insert(ptxConflicting->GetHash());
626 CCoinsView dummy;
627 CCoinsViewCache view(&dummy);
629 CAmount nValueIn = 0;
630 LockPoints lp;
632 LOCK(pool.cs);
633 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
634 view.SetBackend(viewMemPool);
636 // do we already have it?
637 bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
638 if (view.HaveCoins(hash)) {
639 if (!fHadTxInCache)
640 vHashTxnToUncache.push_back(hash);
641 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
644 // do all inputs exist?
645 // Note that this does not check for the presence of actual outputs (see the next check for that),
646 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
647 BOOST_FOREACH(const CTxIn txin, tx.vin) {
648 if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
649 vHashTxnToUncache.push_back(txin.prevout.hash);
650 if (!view.HaveCoins(txin.prevout.hash)) {
651 if (pfMissingInputs)
652 *pfMissingInputs = true;
653 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
657 // are the actual inputs available?
658 if (!view.HaveInputs(tx))
659 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
661 // Bring the best block into scope
662 view.GetBestBlock();
664 nValueIn = view.GetValueIn(tx);
666 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
667 view.SetBackend(dummy);
669 // Only accept BIP68 sequence locked transactions that can be mined in the next
670 // block; we don't want our mempool filled up with transactions that can't
671 // be mined yet.
672 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
673 // CoinsViewCache instead of create its own
674 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
675 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
678 // Check for non-standard pay-to-script-hash in inputs
679 if (fRequireStandard && !AreInputsStandard(tx, view))
680 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
682 // Check for non-standard witness in P2WSH
683 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
684 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
686 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
688 CAmount nValueOut = tx.GetValueOut();
689 CAmount nFees = nValueIn-nValueOut;
690 // nModifiedFees includes any fee deltas from PrioritiseTransaction
691 CAmount nModifiedFees = nFees;
692 pool.ApplyDelta(hash, nModifiedFees);
694 // Keep track of transactions that spend a coinbase, which we re-scan
695 // during reorgs to ensure COINBASE_MATURITY is still met.
696 bool fSpendsCoinbase = false;
697 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
698 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
699 if (coins->IsCoinBase()) {
700 fSpendsCoinbase = true;
701 break;
705 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
706 fSpendsCoinbase, nSigOpsCost, lp);
707 unsigned int nSize = entry.GetTxSize();
709 // Check that the transaction doesn't have an excessive number of
710 // sigops, making it impossible to mine. Since the coinbase transaction
711 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
712 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
713 // merely non-standard transaction.
714 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
715 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
716 strprintf("%d", nSigOpsCost));
718 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
719 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
720 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
723 // No transactions are allowed below minRelayTxFee except from disconnected blocks
724 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
725 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
728 if (nAbsurdFee && nFees > nAbsurdFee)
729 return state.Invalid(false,
730 REJECT_HIGHFEE, "absurdly-high-fee",
731 strprintf("%d > %d", nFees, nAbsurdFee));
733 // Calculate in-mempool ancestors, up to a limit.
734 CTxMemPool::setEntries setAncestors;
735 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
736 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
737 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
738 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
739 std::string errString;
740 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
741 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
744 // A transaction that spends outputs that would be replaced by it is invalid. Now
745 // that we have the set of all ancestors we can detect this
746 // pathological case by making sure setConflicts and setAncestors don't
747 // intersect.
748 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
750 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
751 if (setConflicts.count(hashAncestor))
753 return state.DoS(10, false,
754 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
755 strprintf("%s spends conflicting transaction %s",
756 hash.ToString(),
757 hashAncestor.ToString()));
761 // Check if it's economically rational to mine this transaction rather
762 // than the ones it replaces.
763 CAmount nConflictingFees = 0;
764 size_t nConflictingSize = 0;
765 uint64_t nConflictingCount = 0;
766 CTxMemPool::setEntries allConflicting;
768 // If we don't hold the lock allConflicting might be incomplete; the
769 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
770 // mempool consistency for us.
771 LOCK(pool.cs);
772 const bool fReplacementTransaction = setConflicts.size();
773 if (fReplacementTransaction)
775 CFeeRate newFeeRate(nModifiedFees, nSize);
776 std::set<uint256> setConflictsParents;
777 const int maxDescendantsToVisit = 100;
778 CTxMemPool::setEntries setIterConflicting;
779 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
781 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
782 if (mi == pool.mapTx.end())
783 continue;
785 // Save these to avoid repeated lookups
786 setIterConflicting.insert(mi);
788 // Don't allow the replacement to reduce the feerate of the
789 // mempool.
791 // We usually don't want to accept replacements with lower
792 // feerates than what they replaced as that would lower the
793 // feerate of the next block. Requiring that the feerate always
794 // be increased is also an easy-to-reason about way to prevent
795 // DoS attacks via replacements.
797 // The mining code doesn't (currently) take children into
798 // account (CPFP) so we only consider the feerates of
799 // transactions being directly replaced, not their indirect
800 // descendants. While that does mean high feerate children are
801 // ignored when deciding whether or not to replace, we do
802 // require the replacement to pay more overall fees too,
803 // mitigating most cases.
804 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
805 if (newFeeRate <= oldFeeRate)
807 return state.DoS(0, false,
808 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
809 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
810 hash.ToString(),
811 newFeeRate.ToString(),
812 oldFeeRate.ToString()));
815 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
817 setConflictsParents.insert(txin.prevout.hash);
820 nConflictingCount += mi->GetCountWithDescendants();
822 // This potentially overestimates the number of actual descendants
823 // but we just want to be conservative to avoid doing too much
824 // work.
825 if (nConflictingCount <= maxDescendantsToVisit) {
826 // If not too many to replace, then calculate the set of
827 // transactions that would have to be evicted
828 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
829 pool.CalculateDescendants(it, allConflicting);
831 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
832 nConflictingFees += it->GetModifiedFee();
833 nConflictingSize += it->GetTxSize();
835 } else {
836 return state.DoS(0, false,
837 REJECT_NONSTANDARD, "too many potential replacements", false,
838 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
839 hash.ToString(),
840 nConflictingCount,
841 maxDescendantsToVisit));
844 for (unsigned int j = 0; j < tx.vin.size(); j++)
846 // We don't want to accept replacements that require low
847 // feerate junk to be mined first. Ideally we'd keep track of
848 // the ancestor feerates and make the decision based on that,
849 // but for now requiring all new inputs to be confirmed works.
850 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
852 // Rather than check the UTXO set - potentially expensive -
853 // it's cheaper to just check if the new input refers to a
854 // tx that's in the mempool.
855 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
856 return state.DoS(0, false,
857 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
858 strprintf("replacement %s adds unconfirmed input, idx %d",
859 hash.ToString(), j));
863 // The replacement must pay greater fees than the transactions it
864 // replaces - if we did the bandwidth used by those conflicting
865 // transactions would not be paid for.
866 if (nModifiedFees < nConflictingFees)
868 return state.DoS(0, false,
869 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
870 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
871 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
874 // Finally in addition to paying more fees than the conflicts the
875 // new transaction must pay for its own bandwidth.
876 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
877 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
879 return state.DoS(0, false,
880 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
881 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
882 hash.ToString(),
883 FormatMoney(nDeltaFees),
884 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
888 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
889 if (!Params().RequireStandard()) {
890 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
893 // Check against previous transactions
894 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
895 PrecomputedTransactionData txdata(tx);
896 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
897 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
898 // need to turn both off, and compare against just turning off CLEANSTACK
899 // to see if the failure is specifically due to witness validation.
900 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
901 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
902 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
903 // Only the witness is missing, so the transaction itself may be fine.
904 state.SetCorruptionPossible();
906 return false; // state filled in by CheckInputs
909 // Check again against just the consensus-critical mandatory script
910 // verification flags, in case of bugs in the standard flags that cause
911 // transactions to pass as valid when they're actually invalid. For
912 // instance the STRICTENC flag was incorrectly allowing certain
913 // CHECKSIG NOT scripts to pass, even though they were invalid.
915 // There is a similar check in CreateNewBlock() to prevent creating
916 // invalid blocks, however allowing such transactions into the mempool
917 // can be exploited as a DoS attack.
918 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
920 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
921 __func__, hash.ToString(), FormatStateMessage(state));
924 // Remove conflicting transactions from the mempool
925 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
927 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
928 it->GetTx().GetHash().ToString(),
929 hash.ToString(),
930 FormatMoney(nModifiedFees - nConflictingFees),
931 (int)nSize - (int)nConflictingSize);
932 if (plTxnReplaced)
933 plTxnReplaced->push_back(it->GetSharedTx());
935 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
937 // This transaction should only count for fee estimation if it isn't a
938 // BIP 125 replacement transaction (may not be widely supported), the
939 // node is not behind, and the transaction is not dependent on any other
940 // transactions in the mempool.
941 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
943 // Store transaction in memory
944 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
946 // trim mempool and check if tx was trimmed
947 if (!fOverrideMempoolLimit) {
948 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
949 if (!pool.exists(hash))
950 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
954 GetMainSignals().TransactionAddedToMempool(ptx);
956 return true;
959 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
960 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
961 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
963 std::vector<uint256> vHashTxToUncache;
964 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
965 if (!res) {
966 BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
967 pcoinsTip->Uncache(hashTx);
969 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
970 CValidationState stateDummy;
971 FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
972 return res;
975 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
976 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
977 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
979 return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
982 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
983 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
985 CBlockIndex *pindexSlow = NULL;
987 LOCK(cs_main);
989 CTransactionRef ptx = mempool.get(hash);
990 if (ptx)
992 txOut = ptx;
993 return true;
996 if (fTxIndex) {
997 CDiskTxPos postx;
998 if (pblocktree->ReadTxIndex(hash, postx)) {
999 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1000 if (file.IsNull())
1001 return error("%s: OpenBlockFile failed", __func__);
1002 CBlockHeader header;
1003 try {
1004 file >> header;
1005 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1006 file >> txOut;
1007 } catch (const std::exception& e) {
1008 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1010 hashBlock = header.GetHash();
1011 if (txOut->GetHash() != hash)
1012 return error("%s: txid mismatch", __func__);
1013 return true;
1017 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1018 int nHeight = -1;
1020 const CCoinsViewCache& view = *pcoinsTip;
1021 const CCoins* coins = view.AccessCoins(hash);
1022 if (coins)
1023 nHeight = coins->nHeight;
1025 if (nHeight > 0)
1026 pindexSlow = chainActive[nHeight];
1029 if (pindexSlow) {
1030 CBlock block;
1031 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1032 for (const auto& tx : block.vtx) {
1033 if (tx->GetHash() == hash) {
1034 txOut = tx;
1035 hashBlock = pindexSlow->GetBlockHash();
1036 return true;
1042 return false;
1050 //////////////////////////////////////////////////////////////////////////////
1052 // CBlock and CBlockIndex
1055 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1057 // Open history file to append
1058 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1059 if (fileout.IsNull())
1060 return error("WriteBlockToDisk: OpenBlockFile failed");
1062 // Write index header
1063 unsigned int nSize = GetSerializeSize(fileout, block);
1064 fileout << FLATDATA(messageStart) << nSize;
1066 // Write block
1067 long fileOutPos = ftell(fileout.Get());
1068 if (fileOutPos < 0)
1069 return error("WriteBlockToDisk: ftell failed");
1070 pos.nPos = (unsigned int)fileOutPos;
1071 fileout << block;
1073 return true;
1076 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1078 block.SetNull();
1080 // Open history file to read
1081 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1082 if (filein.IsNull())
1083 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1085 // Read block
1086 try {
1087 filein >> block;
1089 catch (const std::exception& e) {
1090 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1093 // Check the header
1094 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1095 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1097 return true;
1100 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1102 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1103 return false;
1104 if (block.GetHash() != pindex->GetBlockHash())
1105 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1106 pindex->ToString(), pindex->GetBlockPos().ToString());
1107 return true;
1110 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1112 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1113 // Force block reward to zero when right shift is undefined.
1114 if (halvings >= 64)
1115 return 0;
1117 CAmount nSubsidy = 50 * COIN;
1118 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1119 nSubsidy >>= halvings;
1120 return nSubsidy;
1123 bool IsInitialBlockDownload()
1125 const CChainParams& chainParams = Params();
1127 // Once this function has returned false, it must remain false.
1128 static std::atomic<bool> latchToFalse{false};
1129 // Optimization: pre-test latch before taking the lock.
1130 if (latchToFalse.load(std::memory_order_relaxed))
1131 return false;
1133 LOCK(cs_main);
1134 if (latchToFalse.load(std::memory_order_relaxed))
1135 return false;
1136 if (fImporting || fReindex)
1137 return true;
1138 if (chainActive.Tip() == NULL)
1139 return true;
1140 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1141 return true;
1142 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1143 return true;
1144 latchToFalse.store(true, std::memory_order_relaxed);
1145 return false;
1148 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1150 static void AlertNotify(const std::string& strMessage)
1152 uiInterface.NotifyAlertChanged();
1153 std::string strCmd = GetArg("-alertnotify", "");
1154 if (strCmd.empty()) return;
1156 // Alert text should be plain ascii coming from a trusted source, but to
1157 // be safe we first strip anything not in safeChars, then add single quotes around
1158 // the whole string before passing it to the shell:
1159 std::string singleQuote("'");
1160 std::string safeStatus = SanitizeString(strMessage);
1161 safeStatus = singleQuote+safeStatus+singleQuote;
1162 boost::replace_all(strCmd, "%s", safeStatus);
1164 boost::thread t(runCommand, strCmd); // thread runs free
1167 void CheckForkWarningConditions()
1169 AssertLockHeld(cs_main);
1170 // Before we get past initial download, we cannot reliably alert about forks
1171 // (we assume we don't get stuck on a fork before finishing our initial sync)
1172 if (IsInitialBlockDownload())
1173 return;
1175 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1176 // of our head, drop it
1177 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1178 pindexBestForkTip = NULL;
1180 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1182 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1184 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1185 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1186 AlertNotify(warning);
1188 if (pindexBestForkTip && pindexBestForkBase)
1190 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__,
1191 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1192 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1193 SetfLargeWorkForkFound(true);
1195 else
1197 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1198 SetfLargeWorkInvalidChainFound(true);
1201 else
1203 SetfLargeWorkForkFound(false);
1204 SetfLargeWorkInvalidChainFound(false);
1208 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1210 AssertLockHeld(cs_main);
1211 // If we are on a fork that is sufficiently large, set a warning flag
1212 CBlockIndex* pfork = pindexNewForkTip;
1213 CBlockIndex* plonger = chainActive.Tip();
1214 while (pfork && pfork != plonger)
1216 while (plonger && plonger->nHeight > pfork->nHeight)
1217 plonger = plonger->pprev;
1218 if (pfork == plonger)
1219 break;
1220 pfork = pfork->pprev;
1223 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1224 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1225 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1226 // hash rate operating on the fork.
1227 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1228 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1229 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1230 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1231 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1232 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1234 pindexBestForkTip = pindexNewForkTip;
1235 pindexBestForkBase = pfork;
1238 CheckForkWarningConditions();
1241 void static InvalidChainFound(CBlockIndex* pindexNew)
1243 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1244 pindexBestInvalid = pindexNew;
1246 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1247 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1248 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1249 pindexNew->GetBlockTime()));
1250 CBlockIndex *tip = chainActive.Tip();
1251 assert (tip);
1252 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1253 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1254 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1255 CheckForkWarningConditions();
1258 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1259 if (!state.CorruptionPossible()) {
1260 pindex->nStatus |= BLOCK_FAILED_VALID;
1261 setDirtyBlockIndex.insert(pindex);
1262 setBlockIndexCandidates.erase(pindex);
1263 InvalidChainFound(pindex);
1267 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1269 // mark inputs spent
1270 if (!tx.IsCoinBase()) {
1271 txundo.vprevout.reserve(tx.vin.size());
1272 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1273 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1274 unsigned nPos = txin.prevout.n;
1276 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1277 assert(false);
1278 // mark an outpoint spent, and construct undo information
1279 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1280 coins->Spend(nPos);
1281 if (coins->vout.size() == 0) {
1282 CTxInUndo& undo = txundo.vprevout.back();
1283 undo.nHeight = coins->nHeight;
1284 undo.fCoinBase = coins->fCoinBase;
1285 undo.nVersion = coins->nVersion;
1289 // add outputs
1290 inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1293 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1295 CTxUndo txundo;
1296 UpdateCoins(tx, inputs, txundo, nHeight);
1299 bool CScriptCheck::operator()() {
1300 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1301 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1302 if (!VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error)) {
1303 return false;
1305 return true;
1308 int GetSpendHeight(const CCoinsViewCache& inputs)
1310 LOCK(cs_main);
1311 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1312 return pindexPrev->nHeight + 1;
1315 namespace Consensus {
1316 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1318 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1319 // for an attacker to attempt to split the network.
1320 if (!inputs.HaveInputs(tx))
1321 return state.Invalid(false, 0, "", "Inputs unavailable");
1323 CAmount nValueIn = 0;
1324 CAmount nFees = 0;
1325 for (unsigned int i = 0; i < tx.vin.size(); i++)
1327 const COutPoint &prevout = tx.vin[i].prevout;
1328 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1329 assert(coins);
1331 // If prev is coinbase, check that it's matured
1332 if (coins->IsCoinBase()) {
1333 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1334 return state.Invalid(false,
1335 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1336 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1339 // Check for negative or overflow input values
1340 nValueIn += coins->vout[prevout.n].nValue;
1341 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1342 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1346 if (nValueIn < tx.GetValueOut())
1347 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1348 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1350 // Tally transaction fees
1351 CAmount nTxFee = nValueIn - tx.GetValueOut();
1352 if (nTxFee < 0)
1353 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1354 nFees += nTxFee;
1355 if (!MoneyRange(nFees))
1356 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1357 return true;
1359 }// namespace Consensus
1361 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1363 if (!tx.IsCoinBase())
1365 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1366 return false;
1368 if (pvChecks)
1369 pvChecks->reserve(tx.vin.size());
1371 // The first loop above does all the inexpensive checks.
1372 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1373 // Helps prevent CPU exhaustion attacks.
1375 // Skip script verification when connecting blocks under the
1376 // assumevalid block. Assuming the assumevalid block is valid this
1377 // is safe because block merkle hashes are still computed and checked,
1378 // Of course, if an assumed valid block is invalid due to false scriptSigs
1379 // this optimization would allow an invalid chain to be accepted.
1380 if (fScriptChecks) {
1381 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1382 const COutPoint &prevout = tx.vin[i].prevout;
1383 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1384 assert(coins);
1386 // Verify signature
1387 CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1388 if (pvChecks) {
1389 pvChecks->push_back(CScriptCheck());
1390 check.swap(pvChecks->back());
1391 } else if (!check()) {
1392 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1393 // Check whether the failure was caused by a
1394 // non-mandatory script verification check, such as
1395 // non-standard DER encodings or non-null dummy
1396 // arguments; if so, don't trigger DoS protection to
1397 // avoid splitting the network between upgraded and
1398 // non-upgraded nodes.
1399 CScriptCheck check2(*coins, tx, i,
1400 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1401 if (check2())
1402 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1404 // Failures of other flags indicate a transaction that is
1405 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1406 // such nodes as they are not following the protocol. That
1407 // said during an upgrade careful thought should be taken
1408 // as to the correct behavior - we may want to continue
1409 // peering with non-upgraded nodes even after soft-fork
1410 // super-majority signaling has occurred.
1411 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1417 return true;
1420 namespace {
1422 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1424 // Open history file to append
1425 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1426 if (fileout.IsNull())
1427 return error("%s: OpenUndoFile failed", __func__);
1429 // Write index header
1430 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1431 fileout << FLATDATA(messageStart) << nSize;
1433 // Write undo data
1434 long fileOutPos = ftell(fileout.Get());
1435 if (fileOutPos < 0)
1436 return error("%s: ftell failed", __func__);
1437 pos.nPos = (unsigned int)fileOutPos;
1438 fileout << blockundo;
1440 // calculate & write checksum
1441 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1442 hasher << hashBlock;
1443 hasher << blockundo;
1444 fileout << hasher.GetHash();
1446 return true;
1449 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1451 // Open history file to read
1452 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1453 if (filein.IsNull())
1454 return error("%s: OpenUndoFile failed", __func__);
1456 // Read block
1457 uint256 hashChecksum;
1458 try {
1459 filein >> blockundo;
1460 filein >> hashChecksum;
1462 catch (const std::exception& e) {
1463 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1466 // Verify checksum
1467 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1468 hasher << hashBlock;
1469 hasher << blockundo;
1470 if (hashChecksum != hasher.GetHash())
1471 return error("%s: Checksum mismatch", __func__);
1473 return true;
1476 /** Abort with a message */
1477 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1479 SetMiscWarning(strMessage);
1480 LogPrintf("*** %s\n", strMessage);
1481 uiInterface.ThreadSafeMessageBox(
1482 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1483 "", CClientUIInterface::MSG_ERROR);
1484 StartShutdown();
1485 return false;
1488 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1490 AbortNode(strMessage, userMessage);
1491 return state.Error(strMessage);
1494 } // namespace
1497 * Apply the undo operation of a CTxInUndo to the given chain state.
1498 * @param undo The undo object.
1499 * @param view The coins view to which to apply the changes.
1500 * @param out The out point that corresponds to the tx input.
1501 * @return True on success.
1503 bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1505 bool fClean = true;
1507 CCoinsModifier coins = view.ModifyCoins(out.hash);
1508 if (undo.nHeight != 0) {
1509 // undo data contains height: this is the last output of the prevout tx being spent
1510 if (!coins->IsPruned())
1511 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1512 coins->Clear();
1513 coins->fCoinBase = undo.fCoinBase;
1514 coins->nHeight = undo.nHeight;
1515 coins->nVersion = undo.nVersion;
1516 } else {
1517 if (coins->IsPruned())
1518 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1520 if (coins->IsAvailable(out.n))
1521 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1522 if (coins->vout.size() < out.n+1)
1523 coins->vout.resize(out.n+1);
1524 coins->vout[out.n] = undo.txout;
1526 return fClean;
1529 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1530 * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
1531 * will be true if no problems were found. Otherwise, the return value will be false in case
1532 * of problems. Note that in any case, coins may be modified. */
1533 static bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean = NULL)
1535 assert(pindex->GetBlockHash() == view.GetBestBlock());
1537 if (pfClean)
1538 *pfClean = false;
1540 bool fClean = true;
1542 CBlockUndo blockUndo;
1543 CDiskBlockPos pos = pindex->GetUndoPos();
1544 if (pos.IsNull())
1545 return error("DisconnectBlock(): no undo data available");
1546 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1547 return error("DisconnectBlock(): failure reading undo data");
1549 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1550 return error("DisconnectBlock(): block and undo data inconsistent");
1552 // undo transactions in reverse order
1553 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1554 const CTransaction &tx = *(block.vtx[i]);
1555 uint256 hash = tx.GetHash();
1557 // Check that all outputs are available and match the outputs in the block itself
1558 // exactly.
1560 CCoinsModifier outs = view.ModifyCoins(hash);
1561 outs->ClearUnspendable();
1563 CCoins outsBlock(tx, pindex->nHeight);
1564 // The CCoins serialization does not serialize negative numbers.
1565 // No network rules currently depend on the version here, so an inconsistency is harmless
1566 // but it must be corrected before txout nversion ever influences a network rule.
1567 if (outsBlock.nVersion < 0)
1568 outs->nVersion = outsBlock.nVersion;
1569 if (*outs != outsBlock)
1570 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1572 // remove outputs
1573 outs->Clear();
1576 // restore inputs
1577 if (i > 0) { // not coinbases
1578 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1579 if (txundo.vprevout.size() != tx.vin.size())
1580 return error("DisconnectBlock(): transaction and undo data inconsistent");
1581 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1582 const COutPoint &out = tx.vin[j].prevout;
1583 const CTxInUndo &undo = txundo.vprevout[j];
1584 if (!ApplyTxInUndo(undo, view, out))
1585 fClean = false;
1590 // move best block pointer to prevout block
1591 view.SetBestBlock(pindex->pprev->GetBlockHash());
1593 if (pfClean) {
1594 *pfClean = fClean;
1595 return true;
1598 return fClean;
1601 void static FlushBlockFile(bool fFinalize = false)
1603 LOCK(cs_LastBlockFile);
1605 CDiskBlockPos posOld(nLastBlockFile, 0);
1607 FILE *fileOld = OpenBlockFile(posOld);
1608 if (fileOld) {
1609 if (fFinalize)
1610 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1611 FileCommit(fileOld);
1612 fclose(fileOld);
1615 fileOld = OpenUndoFile(posOld);
1616 if (fileOld) {
1617 if (fFinalize)
1618 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1619 FileCommit(fileOld);
1620 fclose(fileOld);
1624 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1626 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1628 void ThreadScriptCheck() {
1629 RenameThread("bitcoin-scriptch");
1630 scriptcheckqueue.Thread();
1633 // Protected by cs_main
1634 VersionBitsCache versionbitscache;
1636 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1638 LOCK(cs_main);
1639 int32_t nVersion = VERSIONBITS_TOP_BITS;
1641 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1642 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1643 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1644 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1648 return nVersion;
1652 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1654 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1656 private:
1657 int bit;
1659 public:
1660 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1662 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1663 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1664 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1665 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1667 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1669 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1670 ((pindex->nVersion >> bit) & 1) != 0 &&
1671 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1675 // Protected by cs_main
1676 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1678 static int64_t nTimeCheck = 0;
1679 static int64_t nTimeForks = 0;
1680 static int64_t nTimeVerify = 0;
1681 static int64_t nTimeConnect = 0;
1682 static int64_t nTimeIndex = 0;
1683 static int64_t nTimeCallbacks = 0;
1684 static int64_t nTimeTotal = 0;
1686 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1687 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1688 * can fail if those validity checks fail (among other reasons). */
1689 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1690 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1692 AssertLockHeld(cs_main);
1693 assert(pindex);
1694 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1695 assert((pindex->phashBlock == NULL) ||
1696 (*pindex->phashBlock == block.GetHash()));
1697 int64_t nTimeStart = GetTimeMicros();
1699 // Check it again in case a previous version let a bad block in
1700 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1701 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1703 // verify that the view's current state corresponds to the previous block
1704 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1705 assert(hashPrevBlock == view.GetBestBlock());
1707 // Special case for the genesis block, skipping connection of its transactions
1708 // (its coinbase is unspendable)
1709 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1710 if (!fJustCheck)
1711 view.SetBestBlock(pindex->GetBlockHash());
1712 return true;
1715 bool fScriptChecks = true;
1716 if (!hashAssumeValid.IsNull()) {
1717 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1718 // A suitable default value is included with the software and updated from time to time. Because validity
1719 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1720 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1721 // effectively caching the result of part of the verification.
1722 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1723 if (it != mapBlockIndex.end()) {
1724 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1725 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1726 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1727 // This block is a member of the assumed verified chain and an ancestor of the best header.
1728 // The equivalent time check discourages hash power from extorting the network via DOS attack
1729 // into accepting an invalid block through telling users they must manually set assumevalid.
1730 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1731 // it hard to hide the implication of the demand. This also avoids having release candidates
1732 // that are hardly doing any signature verification at all in testing without having to
1733 // artificially set the default assumed verified block further back.
1734 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1735 // least as good as the expected chain.
1736 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1741 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1742 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1744 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1745 // unless those are already completely spent.
1746 // If such overwrites are allowed, coinbases and transactions depending upon those
1747 // can be duplicated to remove the ability to spend the first instance -- even after
1748 // being sent to another address.
1749 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1750 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1751 // already refuses previously-known transaction ids entirely.
1752 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1753 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1754 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1755 // initial block download.
1756 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1757 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1758 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1760 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1761 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1762 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1763 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1764 // duplicate transactions descending from the known pairs either.
1765 // 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.
1766 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1767 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1768 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1770 if (fEnforceBIP30) {
1771 for (const auto& tx : block.vtx) {
1772 const CCoins* coins = view.AccessCoins(tx->GetHash());
1773 if (coins && !coins->IsPruned())
1774 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1775 REJECT_INVALID, "bad-txns-BIP30");
1779 // BIP16 didn't become active until Apr 1 2012
1780 int64_t nBIP16SwitchTime = 1333238400;
1781 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1783 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1785 // Start enforcing the DERSIG (BIP66) rule
1786 if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
1787 flags |= SCRIPT_VERIFY_DERSIG;
1790 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1791 if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
1792 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1795 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1796 int nLockTimeFlags = 0;
1797 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1798 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1799 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1802 // Start enforcing WITNESS rules using versionbits logic.
1803 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) {
1804 flags |= SCRIPT_VERIFY_WITNESS;
1805 flags |= SCRIPT_VERIFY_NULLDUMMY;
1808 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1809 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1811 CBlockUndo blockundo;
1813 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1815 std::vector<int> prevheights;
1816 CAmount nFees = 0;
1817 int nInputs = 0;
1818 int64_t nSigOpsCost = 0;
1819 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1820 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1821 vPos.reserve(block.vtx.size());
1822 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1823 std::vector<PrecomputedTransactionData> txdata;
1824 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1825 for (unsigned int i = 0; i < block.vtx.size(); i++)
1827 const CTransaction &tx = *(block.vtx[i]);
1829 nInputs += tx.vin.size();
1831 if (!tx.IsCoinBase())
1833 if (!view.HaveInputs(tx))
1834 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1835 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1837 // Check that transaction is BIP68 final
1838 // BIP68 lock checks (as opposed to nLockTime checks) must
1839 // be in ConnectBlock because they require the UTXO set
1840 prevheights.resize(tx.vin.size());
1841 for (size_t j = 0; j < tx.vin.size(); j++) {
1842 prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
1845 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1846 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1847 REJECT_INVALID, "bad-txns-nonfinal");
1851 // GetTransactionSigOpCost counts 3 types of sigops:
1852 // * legacy (always)
1853 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1854 // * witness (when witness enabled in flags and excludes coinbase)
1855 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1856 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1857 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1858 REJECT_INVALID, "bad-blk-sigops");
1860 txdata.emplace_back(tx);
1861 if (!tx.IsCoinBase())
1863 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1865 std::vector<CScriptCheck> vChecks;
1866 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1867 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1868 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1869 tx.GetHash().ToString(), FormatStateMessage(state));
1870 control.Add(vChecks);
1873 CTxUndo undoDummy;
1874 if (i > 0) {
1875 blockundo.vtxundo.push_back(CTxUndo());
1877 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1879 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1880 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1882 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1883 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);
1885 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1886 if (block.vtx[0]->GetValueOut() > blockReward)
1887 return state.DoS(100,
1888 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1889 block.vtx[0]->GetValueOut(), blockReward),
1890 REJECT_INVALID, "bad-cb-amount");
1892 if (!control.Wait())
1893 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1894 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1895 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);
1897 if (fJustCheck)
1898 return true;
1900 // Write undo information to disk
1901 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1903 if (pindex->GetUndoPos().IsNull()) {
1904 CDiskBlockPos _pos;
1905 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1906 return error("ConnectBlock(): FindUndoPos failed");
1907 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1908 return AbortNode(state, "Failed to write undo data");
1910 // update nUndoPos in block index
1911 pindex->nUndoPos = _pos.nPos;
1912 pindex->nStatus |= BLOCK_HAVE_UNDO;
1915 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1916 setDirtyBlockIndex.insert(pindex);
1919 if (fTxIndex)
1920 if (!pblocktree->WriteTxIndex(vPos))
1921 return AbortNode(state, "Failed to write transaction index");
1923 // add this block to the view's block chain
1924 view.SetBestBlock(pindex->GetBlockHash());
1926 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1927 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1929 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1930 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1932 return true;
1936 * Update the on-disk chain state.
1937 * The caches and indexes are flushed depending on the mode we're called with
1938 * if they're too large, if it's been a while since the last write,
1939 * or always and in all cases if we're in prune mode and are deleting files.
1941 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1942 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1943 const CChainParams& chainparams = Params();
1944 LOCK2(cs_main, cs_LastBlockFile);
1945 static int64_t nLastWrite = 0;
1946 static int64_t nLastFlush = 0;
1947 static int64_t nLastSetChain = 0;
1948 std::set<int> setFilesToPrune;
1949 bool fFlushForPrune = false;
1950 try {
1951 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1952 if (nManualPruneHeight > 0) {
1953 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1954 } else {
1955 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1956 fCheckForPruning = false;
1958 if (!setFilesToPrune.empty()) {
1959 fFlushForPrune = true;
1960 if (!fHavePruned) {
1961 pblocktree->WriteFlag("prunedblockfiles", true);
1962 fHavePruned = true;
1966 int64_t nNow = GetTimeMicros();
1967 // Avoid writing/flushing immediately after startup.
1968 if (nLastWrite == 0) {
1969 nLastWrite = nNow;
1971 if (nLastFlush == 0) {
1972 nLastFlush = nNow;
1974 if (nLastSetChain == 0) {
1975 nLastSetChain = nNow;
1977 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
1978 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
1979 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
1980 // The cache is large and we're within 10% and 200 MiB or 50% and 50MiB of the limit, but we have time now (not in the middle of a block processing).
1981 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::min(std::max(nTotalSpace / 2, nTotalSpace - MIN_BLOCK_COINSDB_USAGE * 1024 * 1024),
1982 std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024));
1983 // The cache is over the limit, we have to write now.
1984 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
1985 // 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.
1986 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1987 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1988 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1989 // Combine all conditions that result in a full cache flush.
1990 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1991 // Write blocks and block index to disk.
1992 if (fDoFullFlush || fPeriodicWrite) {
1993 // Depend on nMinDiskSpace to ensure we can write block index
1994 if (!CheckDiskSpace(0))
1995 return state.Error("out of disk space");
1996 // First make sure all block and undo data is flushed to disk.
1997 FlushBlockFile();
1998 // Then update all block file information (which may refer to block and undo files).
2000 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2001 vFiles.reserve(setDirtyFileInfo.size());
2002 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2003 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2004 setDirtyFileInfo.erase(it++);
2006 std::vector<const CBlockIndex*> vBlocks;
2007 vBlocks.reserve(setDirtyBlockIndex.size());
2008 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2009 vBlocks.push_back(*it);
2010 setDirtyBlockIndex.erase(it++);
2012 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2013 return AbortNode(state, "Failed to write to block index database");
2016 // Finally remove any pruned files
2017 if (fFlushForPrune)
2018 UnlinkPrunedFiles(setFilesToPrune);
2019 nLastWrite = nNow;
2021 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2022 if (fDoFullFlush) {
2023 // Typical CCoins structures on disk are around 128 bytes in size.
2024 // Pushing a new one to the database can cause it to be written
2025 // twice (once in the log, and once in the tables). This is already
2026 // an overestimation, as most will delete an existing entry or
2027 // overwrite one. Still, use a conservative safety factor of 2.
2028 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2029 return state.Error("out of disk space");
2030 // Flush the chainstate (which may refer to block index entries).
2031 if (!pcoinsTip->Flush())
2032 return AbortNode(state, "Failed to write to coin database");
2033 nLastFlush = nNow;
2035 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2036 // Update best block in wallet (so we can detect restored wallets).
2037 GetMainSignals().SetBestChain(chainActive.GetLocator());
2038 nLastSetChain = nNow;
2040 } catch (const std::runtime_error& e) {
2041 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2043 return true;
2046 void FlushStateToDisk() {
2047 CValidationState state;
2048 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2051 void PruneAndFlush() {
2052 CValidationState state;
2053 fCheckForPruning = true;
2054 FlushStateToDisk(state, FLUSH_STATE_NONE);
2057 /** Update chainActive and related internal data structures. */
2058 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2059 chainActive.SetTip(pindexNew);
2061 // New best block
2062 mempool.AddTransactionsUpdated(1);
2064 cvBlockChange.notify_all();
2066 static bool fWarned = false;
2067 std::vector<std::string> warningMessages;
2068 if (!IsInitialBlockDownload())
2070 int nUpgraded = 0;
2071 const CBlockIndex* pindex = chainActive.Tip();
2072 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2073 WarningBitsConditionChecker checker(bit);
2074 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2075 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2076 if (state == THRESHOLD_ACTIVE) {
2077 std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2078 SetMiscWarning(strWarning);
2079 if (!fWarned) {
2080 AlertNotify(strWarning);
2081 fWarned = true;
2083 } else {
2084 warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
2088 // Check the version of the last 100 blocks to see if we need to upgrade:
2089 for (int i = 0; i < 100 && pindex != NULL; i++)
2091 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2092 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2093 ++nUpgraded;
2094 pindex = pindex->pprev;
2096 if (nUpgraded > 0)
2097 warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
2098 if (nUpgraded > 100/2)
2100 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2101 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2102 SetMiscWarning(strWarning);
2103 if (!fWarned) {
2104 AlertNotify(strWarning);
2105 fWarned = true;
2109 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
2110 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2111 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2112 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2113 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2114 if (!warningMessages.empty())
2115 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2116 LogPrintf("\n");
2120 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
2121 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
2123 CBlockIndex *pindexDelete = chainActive.Tip();
2124 assert(pindexDelete);
2125 // Read block from disk.
2126 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2127 CBlock& block = *pblock;
2128 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2129 return AbortNode(state, "Failed to read block");
2130 // Apply the block atomically to the chain state.
2131 int64_t nStart = GetTimeMicros();
2133 CCoinsViewCache view(pcoinsTip);
2134 if (!DisconnectBlock(block, state, pindexDelete, view))
2135 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2136 bool flushed = view.Flush();
2137 assert(flushed);
2139 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2140 // Write the chain state to disk, if necessary.
2141 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2142 return false;
2144 if (!fBare) {
2145 // Resurrect mempool transactions from the disconnected block.
2146 std::vector<uint256> vHashUpdate;
2147 for (const auto& it : block.vtx) {
2148 const CTransaction& tx = *it;
2149 // ignore validation errors in resurrected transactions
2150 CValidationState stateDummy;
2151 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
2152 mempool.removeRecursive(tx, MemPoolRemovalReason::REORG);
2153 } else if (mempool.exists(tx.GetHash())) {
2154 vHashUpdate.push_back(tx.GetHash());
2157 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2158 // no in-mempool children, which is generally not true when adding
2159 // previously-confirmed transactions back to the mempool.
2160 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2161 // block that were added back and cleans up the mempool state.
2162 mempool.UpdateTransactionsFromBlock(vHashUpdate);
2165 // Update chainActive and related variables.
2166 UpdateTip(pindexDelete->pprev, chainparams);
2167 // Let wallets know transactions went from 1-confirmed to
2168 // 0-confirmed or conflicted:
2169 GetMainSignals().BlockDisconnected(pblock);
2170 return true;
2173 static int64_t nTimeReadFromDisk = 0;
2174 static int64_t nTimeConnectTotal = 0;
2175 static int64_t nTimeFlush = 0;
2176 static int64_t nTimeChainState = 0;
2177 static int64_t nTimePostConnect = 0;
2179 struct PerBlockConnectTrace {
2180 CBlockIndex* pindex = NULL;
2181 std::shared_ptr<const CBlock> pblock;
2182 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2183 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2186 * Used to track blocks whose transactions were applied to the UTXO state as a
2187 * part of a single ActivateBestChainStep call.
2189 * This class also tracks transactions that are removed from the mempool as
2190 * conflicts (per block) and can be used to pass all those transactions
2191 * through SyncTransaction.
2193 * This class assumes (and asserts) that the conflicted transactions for a given
2194 * block are added via mempool callbacks prior to the BlockConnected() associated
2195 * with those transactions. If any transactions are marked conflicted, it is
2196 * assumed that an associated block will always be added.
2198 * This class is single-use, once you call GetBlocksConnected() you have to throw
2199 * it away and make a new one.
2201 class ConnectTrace {
2202 private:
2203 std::vector<PerBlockConnectTrace> blocksConnected;
2204 CTxMemPool &pool;
2206 public:
2207 ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2208 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2211 ~ConnectTrace() {
2212 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2215 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2216 assert(!blocksConnected.back().pindex);
2217 assert(pindex);
2218 assert(pblock);
2219 blocksConnected.back().pindex = pindex;
2220 blocksConnected.back().pblock = std::move(pblock);
2221 blocksConnected.emplace_back();
2224 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2225 // We always keep one extra block at the end of our list because
2226 // blocks are added after all the conflicted transactions have
2227 // been filled in. Thus, the last entry should always be an empty
2228 // one waiting for the transactions from the next block. We pop
2229 // the last entry here to make sure the list we return is sane.
2230 assert(!blocksConnected.back().pindex);
2231 assert(blocksConnected.back().conflictedTxs->empty());
2232 blocksConnected.pop_back();
2233 return blocksConnected;
2236 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2237 assert(!blocksConnected.back().pindex);
2238 if (reason == MemPoolRemovalReason::CONFLICT) {
2239 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2245 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2246 * corresponding to pindexNew, to bypass loading it again from disk.
2248 * The block is added to connectTrace if connection succeeds.
2250 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2252 assert(pindexNew->pprev == chainActive.Tip());
2253 // Read block from disk.
2254 int64_t nTime1 = GetTimeMicros();
2255 std::shared_ptr<const CBlock> pthisBlock;
2256 if (!pblock) {
2257 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2258 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2259 return AbortNode(state, "Failed to read block");
2260 pthisBlock = pblockNew;
2261 } else {
2262 pthisBlock = pblock;
2264 const CBlock& blockConnecting = *pthisBlock;
2265 // Apply the block atomically to the chain state.
2266 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2267 int64_t nTime3;
2268 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2270 CCoinsViewCache view(pcoinsTip);
2271 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2272 GetMainSignals().BlockChecked(blockConnecting, state);
2273 if (!rv) {
2274 if (state.IsInvalid())
2275 InvalidBlockFound(pindexNew, state);
2276 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2278 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2279 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2280 bool flushed = view.Flush();
2281 assert(flushed);
2283 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2284 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2285 // Write the chain state to disk, if necessary.
2286 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2287 return false;
2288 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2289 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2290 // Remove conflicting transactions from the mempool.;
2291 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2292 // Update chainActive & related variables.
2293 UpdateTip(pindexNew, chainparams);
2295 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2296 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2297 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2299 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2300 return true;
2304 * Return the tip of the chain with the most work in it, that isn't
2305 * known to be invalid (it's however far from certain to be valid).
2307 static CBlockIndex* FindMostWorkChain() {
2308 do {
2309 CBlockIndex *pindexNew = NULL;
2311 // Find the best candidate header.
2313 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2314 if (it == setBlockIndexCandidates.rend())
2315 return NULL;
2316 pindexNew = *it;
2319 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2320 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2321 CBlockIndex *pindexTest = pindexNew;
2322 bool fInvalidAncestor = false;
2323 while (pindexTest && !chainActive.Contains(pindexTest)) {
2324 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2326 // Pruned nodes may have entries in setBlockIndexCandidates for
2327 // which block files have been deleted. Remove those as candidates
2328 // for the most work chain if we come across them; we can't switch
2329 // to a chain unless we have all the non-active-chain parent blocks.
2330 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2331 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2332 if (fFailedChain || fMissingData) {
2333 // Candidate chain is not usable (either invalid or missing data)
2334 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2335 pindexBestInvalid = pindexNew;
2336 CBlockIndex *pindexFailed = pindexNew;
2337 // Remove the entire chain from the set.
2338 while (pindexTest != pindexFailed) {
2339 if (fFailedChain) {
2340 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2341 } else if (fMissingData) {
2342 // If we're missing data, then add back to mapBlocksUnlinked,
2343 // so that if the block arrives in the future we can try adding
2344 // to setBlockIndexCandidates again.
2345 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2347 setBlockIndexCandidates.erase(pindexFailed);
2348 pindexFailed = pindexFailed->pprev;
2350 setBlockIndexCandidates.erase(pindexTest);
2351 fInvalidAncestor = true;
2352 break;
2354 pindexTest = pindexTest->pprev;
2356 if (!fInvalidAncestor)
2357 return pindexNew;
2358 } while(true);
2361 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2362 static void PruneBlockIndexCandidates() {
2363 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2364 // reorganization to a better block fails.
2365 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2366 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2367 setBlockIndexCandidates.erase(it++);
2369 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2370 assert(!setBlockIndexCandidates.empty());
2374 * Try to make some progress towards making pindexMostWork the active block.
2375 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2377 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2379 AssertLockHeld(cs_main);
2380 const CBlockIndex *pindexOldTip = chainActive.Tip();
2381 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2383 // Disconnect active blocks which are no longer in the best chain.
2384 bool fBlocksDisconnected = false;
2385 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2386 if (!DisconnectTip(state, chainparams))
2387 return false;
2388 fBlocksDisconnected = true;
2391 // Build list of new blocks to connect.
2392 std::vector<CBlockIndex*> vpindexToConnect;
2393 bool fContinue = true;
2394 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2395 while (fContinue && nHeight != pindexMostWork->nHeight) {
2396 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2397 // a few blocks along the way.
2398 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2399 vpindexToConnect.clear();
2400 vpindexToConnect.reserve(nTargetHeight - nHeight);
2401 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2402 while (pindexIter && pindexIter->nHeight != nHeight) {
2403 vpindexToConnect.push_back(pindexIter);
2404 pindexIter = pindexIter->pprev;
2406 nHeight = nTargetHeight;
2408 // Connect new blocks.
2409 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2410 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2411 if (state.IsInvalid()) {
2412 // The block violates a consensus rule.
2413 if (!state.CorruptionPossible())
2414 InvalidChainFound(vpindexToConnect.back());
2415 state = CValidationState();
2416 fInvalidFound = true;
2417 fContinue = false;
2418 break;
2419 } else {
2420 // A system error occurred (disk space, database error, ...).
2421 return false;
2423 } else {
2424 PruneBlockIndexCandidates();
2425 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2426 // We're in a better position than we were. Return temporarily to release the lock.
2427 fContinue = false;
2428 break;
2434 if (fBlocksDisconnected) {
2435 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2436 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2438 mempool.check(pcoinsTip);
2440 // Callbacks/notifications for a new best chain.
2441 if (fInvalidFound)
2442 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2443 else
2444 CheckForkWarningConditions();
2446 return true;
2449 static void NotifyHeaderTip() {
2450 bool fNotify = false;
2451 bool fInitialBlockDownload = false;
2452 static CBlockIndex* pindexHeaderOld = NULL;
2453 CBlockIndex* pindexHeader = NULL;
2455 LOCK(cs_main);
2456 pindexHeader = pindexBestHeader;
2458 if (pindexHeader != pindexHeaderOld) {
2459 fNotify = true;
2460 fInitialBlockDownload = IsInitialBlockDownload();
2461 pindexHeaderOld = pindexHeader;
2464 // Send block tip changed notifications without cs_main
2465 if (fNotify) {
2466 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2471 * Make the best chain active, in multiple steps. The result is either failure
2472 * or an activated best chain. pblock is either NULL or a pointer to a block
2473 * that is already loaded (to avoid loading it again from disk).
2475 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2476 // Note that while we're often called here from ProcessNewBlock, this is
2477 // far from a guarantee. Things in the P2P/RPC will often end up calling
2478 // us in the middle of ProcessNewBlock - do not assume pblock is set
2479 // sanely for performance or correctness!
2481 CBlockIndex *pindexMostWork = NULL;
2482 CBlockIndex *pindexNewTip = NULL;
2483 do {
2484 boost::this_thread::interruption_point();
2485 if (ShutdownRequested())
2486 break;
2488 const CBlockIndex *pindexFork;
2489 bool fInitialDownload;
2491 LOCK(cs_main);
2492 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2494 CBlockIndex *pindexOldTip = chainActive.Tip();
2495 if (pindexMostWork == NULL) {
2496 pindexMostWork = FindMostWorkChain();
2499 // Whether we have anything to do at all.
2500 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2501 return true;
2503 bool fInvalidFound = false;
2504 std::shared_ptr<const CBlock> nullBlockPtr;
2505 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2506 return false;
2508 if (fInvalidFound) {
2509 // Wipe cache, we may need another branch now.
2510 pindexMostWork = NULL;
2512 pindexNewTip = chainActive.Tip();
2513 pindexFork = chainActive.FindFork(pindexOldTip);
2514 fInitialDownload = IsInitialBlockDownload();
2516 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2517 assert(trace.pblock && trace.pindex);
2518 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
2521 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2523 // Notifications/callbacks that can run without cs_main
2525 // Notify external listeners about the new tip.
2526 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2528 // Always notify the UI if a new block tip was connected
2529 if (pindexFork != pindexNewTip) {
2530 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2532 } while (pindexNewTip != pindexMostWork);
2533 CheckBlockIndex(chainparams.GetConsensus());
2535 // Write changes periodically to disk, after relay.
2536 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2537 return false;
2540 return true;
2544 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2547 LOCK(cs_main);
2548 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2549 // Nothing to do, this block is not at the tip.
2550 return true;
2552 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2553 // The chain has been extended since the last call, reset the counter.
2554 nBlockReverseSequenceId = -1;
2556 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2557 setBlockIndexCandidates.erase(pindex);
2558 pindex->nSequenceId = nBlockReverseSequenceId;
2559 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2560 // We can't keep reducing the counter if somebody really wants to
2561 // call preciousblock 2**31-1 times on the same set of tips...
2562 nBlockReverseSequenceId--;
2564 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2565 setBlockIndexCandidates.insert(pindex);
2566 PruneBlockIndexCandidates();
2570 return ActivateBestChain(state, params);
2573 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2575 AssertLockHeld(cs_main);
2577 // Mark the block itself as invalid.
2578 pindex->nStatus |= BLOCK_FAILED_VALID;
2579 setDirtyBlockIndex.insert(pindex);
2580 setBlockIndexCandidates.erase(pindex);
2582 while (chainActive.Contains(pindex)) {
2583 CBlockIndex *pindexWalk = chainActive.Tip();
2584 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2585 setDirtyBlockIndex.insert(pindexWalk);
2586 setBlockIndexCandidates.erase(pindexWalk);
2587 // ActivateBestChain considers blocks already in chainActive
2588 // unconditionally valid already, so force disconnect away from it.
2589 if (!DisconnectTip(state, chainparams)) {
2590 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2591 return false;
2595 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2597 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2598 // add it again.
2599 BlockMap::iterator it = mapBlockIndex.begin();
2600 while (it != mapBlockIndex.end()) {
2601 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2602 setBlockIndexCandidates.insert(it->second);
2604 it++;
2607 InvalidChainFound(pindex);
2608 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2609 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2610 return true;
2613 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2614 AssertLockHeld(cs_main);
2616 int nHeight = pindex->nHeight;
2618 // Remove the invalidity flag from this block and all its descendants.
2619 BlockMap::iterator it = mapBlockIndex.begin();
2620 while (it != mapBlockIndex.end()) {
2621 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2622 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2623 setDirtyBlockIndex.insert(it->second);
2624 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2625 setBlockIndexCandidates.insert(it->second);
2627 if (it->second == pindexBestInvalid) {
2628 // Reset invalid block marker if it was pointing to one of those.
2629 pindexBestInvalid = NULL;
2632 it++;
2635 // Remove the invalidity flag from all ancestors too.
2636 while (pindex != NULL) {
2637 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2638 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2639 setDirtyBlockIndex.insert(pindex);
2641 pindex = pindex->pprev;
2643 return true;
2646 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2648 // Check for duplicate
2649 uint256 hash = block.GetHash();
2650 BlockMap::iterator it = mapBlockIndex.find(hash);
2651 if (it != mapBlockIndex.end())
2652 return it->second;
2654 // Construct new block index object
2655 CBlockIndex* pindexNew = new CBlockIndex(block);
2656 assert(pindexNew);
2657 // We assign the sequence id to blocks only when the full data is available,
2658 // to avoid miners withholding blocks but broadcasting headers, to get a
2659 // competitive advantage.
2660 pindexNew->nSequenceId = 0;
2661 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2662 pindexNew->phashBlock = &((*mi).first);
2663 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2664 if (miPrev != mapBlockIndex.end())
2666 pindexNew->pprev = (*miPrev).second;
2667 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2668 pindexNew->BuildSkip();
2670 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2671 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2672 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2673 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2674 pindexBestHeader = pindexNew;
2676 setDirtyBlockIndex.insert(pindexNew);
2678 return pindexNew;
2681 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2682 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2684 pindexNew->nTx = block.vtx.size();
2685 pindexNew->nChainTx = 0;
2686 pindexNew->nFile = pos.nFile;
2687 pindexNew->nDataPos = pos.nPos;
2688 pindexNew->nUndoPos = 0;
2689 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2690 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2691 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2693 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2694 setDirtyBlockIndex.insert(pindexNew);
2696 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2697 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2698 std::deque<CBlockIndex*> queue;
2699 queue.push_back(pindexNew);
2701 // Recursively process any descendant blocks that now may be eligible to be connected.
2702 while (!queue.empty()) {
2703 CBlockIndex *pindex = queue.front();
2704 queue.pop_front();
2705 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2707 LOCK(cs_nBlockSequenceId);
2708 pindex->nSequenceId = nBlockSequenceId++;
2710 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2711 setBlockIndexCandidates.insert(pindex);
2713 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2714 while (range.first != range.second) {
2715 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2716 queue.push_back(it->second);
2717 range.first++;
2718 mapBlocksUnlinked.erase(it);
2721 } else {
2722 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2723 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2727 return true;
2730 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2732 LOCK(cs_LastBlockFile);
2734 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2735 if (vinfoBlockFile.size() <= nFile) {
2736 vinfoBlockFile.resize(nFile + 1);
2739 if (!fKnown) {
2740 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2741 nFile++;
2742 if (vinfoBlockFile.size() <= nFile) {
2743 vinfoBlockFile.resize(nFile + 1);
2746 pos.nFile = nFile;
2747 pos.nPos = vinfoBlockFile[nFile].nSize;
2750 if ((int)nFile != nLastBlockFile) {
2751 if (!fKnown) {
2752 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2754 FlushBlockFile(!fKnown);
2755 nLastBlockFile = nFile;
2758 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2759 if (fKnown)
2760 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2761 else
2762 vinfoBlockFile[nFile].nSize += nAddSize;
2764 if (!fKnown) {
2765 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2766 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2767 if (nNewChunks > nOldChunks) {
2768 if (fPruneMode)
2769 fCheckForPruning = true;
2770 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2771 FILE *file = OpenBlockFile(pos);
2772 if (file) {
2773 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2774 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2775 fclose(file);
2778 else
2779 return state.Error("out of disk space");
2783 setDirtyFileInfo.insert(nFile);
2784 return true;
2787 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2789 pos.nFile = nFile;
2791 LOCK(cs_LastBlockFile);
2793 unsigned int nNewSize;
2794 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2795 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2796 setDirtyFileInfo.insert(nFile);
2798 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2799 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2800 if (nNewChunks > nOldChunks) {
2801 if (fPruneMode)
2802 fCheckForPruning = true;
2803 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2804 FILE *file = OpenUndoFile(pos);
2805 if (file) {
2806 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2807 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2808 fclose(file);
2811 else
2812 return state.Error("out of disk space");
2815 return true;
2818 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW)
2820 // Check proof of work matches claimed amount
2821 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2822 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2824 return true;
2827 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2829 // These are checks that are independent of context.
2831 if (block.fChecked)
2832 return true;
2834 // Check that the header is valid (particularly PoW). This is mostly
2835 // redundant with the call in AcceptBlockHeader.
2836 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2837 return false;
2839 // Check the merkle root.
2840 if (fCheckMerkleRoot) {
2841 bool mutated;
2842 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2843 if (block.hashMerkleRoot != hashMerkleRoot2)
2844 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2846 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2847 // of transactions in a block without affecting the merkle root of a block,
2848 // while still invalidating it.
2849 if (mutated)
2850 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2853 // All potential-corruption validation must be done before we do any
2854 // transaction validation, as otherwise we may mark the header as invalid
2855 // because we receive the wrong transactions for it.
2856 // Note that witness malleability is checked in ContextualCheckBlock, so no
2857 // checks that use witness data may be performed here.
2859 // Size limits
2860 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)
2861 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2863 // First transaction must be coinbase, the rest must not be
2864 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2865 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2866 for (unsigned int i = 1; i < block.vtx.size(); i++)
2867 if (block.vtx[i]->IsCoinBase())
2868 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2870 // Check transactions
2871 for (const auto& tx : block.vtx)
2872 if (!CheckTransaction(*tx, state, false))
2873 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2874 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2876 unsigned int nSigOps = 0;
2877 for (const auto& tx : block.vtx)
2879 nSigOps += GetLegacySigOpCount(*tx);
2881 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2882 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2884 if (fCheckPOW && fCheckMerkleRoot)
2885 block.fChecked = true;
2887 return true;
2890 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2892 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2893 return true;
2895 int nHeight = pindexPrev->nHeight+1;
2896 // Don't accept any forks from the main chain prior to last checkpoint.
2897 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
2898 // MapBlockIndex.
2899 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2900 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2901 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
2903 return true;
2906 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2908 LOCK(cs_main);
2909 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2912 // Compute at which vout of the block's coinbase transaction the witness
2913 // commitment occurs, or -1 if not found.
2914 static int GetWitnessCommitmentIndex(const CBlock& block)
2916 int commitpos = -1;
2917 if (!block.vtx.empty()) {
2918 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2919 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) {
2920 commitpos = o;
2924 return commitpos;
2927 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2929 int commitpos = GetWitnessCommitmentIndex(block);
2930 static const std::vector<unsigned char> nonce(32, 0x00);
2931 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2932 CMutableTransaction tx(*block.vtx[0]);
2933 tx.vin[0].scriptWitness.stack.resize(1);
2934 tx.vin[0].scriptWitness.stack[0] = nonce;
2935 block.vtx[0] = MakeTransactionRef(std::move(tx));
2939 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2941 std::vector<unsigned char> commitment;
2942 int commitpos = GetWitnessCommitmentIndex(block);
2943 std::vector<unsigned char> ret(32, 0x00);
2944 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2945 if (commitpos == -1) {
2946 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2947 CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2948 CTxOut out;
2949 out.nValue = 0;
2950 out.scriptPubKey.resize(38);
2951 out.scriptPubKey[0] = OP_RETURN;
2952 out.scriptPubKey[1] = 0x24;
2953 out.scriptPubKey[2] = 0xaa;
2954 out.scriptPubKey[3] = 0x21;
2955 out.scriptPubKey[4] = 0xa9;
2956 out.scriptPubKey[5] = 0xed;
2957 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2958 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2959 CMutableTransaction tx(*block.vtx[0]);
2960 tx.vout.push_back(out);
2961 block.vtx[0] = MakeTransactionRef(std::move(tx));
2964 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2965 return commitment;
2968 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2970 assert(pindexPrev != NULL);
2971 const int nHeight = pindexPrev->nHeight + 1;
2972 // Check proof of work
2973 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2974 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2976 // Check timestamp against prev
2977 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2978 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2980 // Check timestamp
2981 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2982 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2984 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2985 // check for version 2, 3 and 4 upgrades
2986 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2987 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2988 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2989 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2990 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2992 return true;
2995 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2997 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2999 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3000 int nLockTimeFlags = 0;
3001 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3002 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3005 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3006 ? pindexPrev->GetMedianTimePast()
3007 : block.GetBlockTime();
3009 // Check that all transactions are finalized
3010 for (const auto& tx : block.vtx) {
3011 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3012 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3016 // Enforce rule that the coinbase starts with serialized block height
3017 if (nHeight >= consensusParams.BIP34Height)
3019 CScript expect = CScript() << nHeight;
3020 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3021 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3022 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3026 // Validation for witness commitments.
3027 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3028 // coinbase (where 0x0000....0000 is used instead).
3029 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3030 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3031 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3032 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3033 // multiple, the last one is used.
3034 bool fHaveWitness = false;
3035 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3036 int commitpos = GetWitnessCommitmentIndex(block);
3037 if (commitpos != -1) {
3038 bool malleated = false;
3039 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3040 // The malleation check is ignored; as the transaction tree itself
3041 // already does not permit it, it is impossible to trigger in the
3042 // witness tree.
3043 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3044 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3046 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3047 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3048 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3050 fHaveWitness = true;
3054 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3055 if (!fHaveWitness) {
3056 for (size_t i = 0; i < block.vtx.size(); i++) {
3057 if (block.vtx[i]->HasWitness()) {
3058 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3063 // After the coinbase witness nonce and commitment are verified,
3064 // we can check if the block weight passes (before we've checked the
3065 // coinbase witness, it would be possible for the weight to be too
3066 // large by filling up the coinbase witness, which doesn't change
3067 // the block hash, so we couldn't mark the block as permanently
3068 // failed).
3069 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3070 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3073 return true;
3076 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3078 AssertLockHeld(cs_main);
3079 // Check for duplicate
3080 uint256 hash = block.GetHash();
3081 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3082 CBlockIndex *pindex = NULL;
3083 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3085 if (miSelf != mapBlockIndex.end()) {
3086 // Block header is already known.
3087 pindex = miSelf->second;
3088 if (ppindex)
3089 *ppindex = pindex;
3090 if (pindex->nStatus & BLOCK_FAILED_MASK)
3091 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3092 return true;
3095 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3096 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3098 // Get prev block index
3099 CBlockIndex* pindexPrev = NULL;
3100 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3101 if (mi == mapBlockIndex.end())
3102 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3103 pindexPrev = (*mi).second;
3104 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3105 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3107 assert(pindexPrev);
3108 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3109 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3111 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3112 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3114 if (pindex == NULL)
3115 pindex = AddToBlockIndex(block);
3117 if (ppindex)
3118 *ppindex = pindex;
3120 CheckBlockIndex(chainparams.GetConsensus());
3122 return true;
3125 // Exposed wrapper for AcceptBlockHeader
3126 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3129 LOCK(cs_main);
3130 for (const CBlockHeader& header : headers) {
3131 CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
3132 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3133 return false;
3135 if (ppindex) {
3136 *ppindex = pindex;
3140 NotifyHeaderTip();
3141 return true;
3144 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3145 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3147 const CBlock& block = *pblock;
3149 if (fNewBlock) *fNewBlock = false;
3150 AssertLockHeld(cs_main);
3152 CBlockIndex *pindexDummy = NULL;
3153 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3155 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3156 return false;
3158 // Try to process all requested blocks that we don't have, but only
3159 // process an unrequested block if it's new and has enough work to
3160 // advance our tip, and isn't too many blocks ahead.
3161 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3162 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3163 // Blocks that are too out-of-order needlessly limit the effectiveness of
3164 // pruning, because pruning will not delete block files that contain any
3165 // blocks which are too close in height to the tip. Apply this test
3166 // regardless of whether pruning is enabled; it should generally be safe to
3167 // not process unrequested blocks.
3168 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3170 // TODO: Decouple this function from the block download logic by removing fRequested
3171 // This requires some new chain data structure to efficiently look up if a
3172 // block is in a chain leading to a candidate for best tip, despite not
3173 // being such a candidate itself.
3175 // TODO: deal better with return value and error conditions for duplicate
3176 // and unrequested blocks.
3177 if (fAlreadyHave) return true;
3178 if (!fRequested) { // If we didn't ask for it:
3179 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3180 if (!fHasMoreWork) return true; // Don't process less-work chains
3181 if (fTooFarAhead) return true; // Block height is too high
3183 if (fNewBlock) *fNewBlock = true;
3185 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3186 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3187 if (state.IsInvalid() && !state.CorruptionPossible()) {
3188 pindex->nStatus |= BLOCK_FAILED_VALID;
3189 setDirtyBlockIndex.insert(pindex);
3191 return error("%s: %s", __func__, FormatStateMessage(state));
3194 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3195 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3196 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3197 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3199 int nHeight = pindex->nHeight;
3201 // Write block to history file
3202 try {
3203 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3204 CDiskBlockPos blockPos;
3205 if (dbp != NULL)
3206 blockPos = *dbp;
3207 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3208 return error("AcceptBlock(): FindBlockPos failed");
3209 if (dbp == NULL)
3210 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3211 AbortNode(state, "Failed to write block");
3212 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3213 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3214 } catch (const std::runtime_error& e) {
3215 return AbortNode(state, std::string("System error: ") + e.what());
3218 if (fCheckForPruning)
3219 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3221 return true;
3224 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3227 CBlockIndex *pindex = NULL;
3228 if (fNewBlock) *fNewBlock = false;
3229 CValidationState state;
3230 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3231 // belt-and-suspenders.
3232 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3234 LOCK(cs_main);
3236 if (ret) {
3237 // Store to disk
3238 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3240 CheckBlockIndex(chainparams.GetConsensus());
3241 if (!ret) {
3242 GetMainSignals().BlockChecked(*pblock, state);
3243 return error("%s: AcceptBlock FAILED", __func__);
3247 NotifyHeaderTip();
3249 CValidationState state; // Only used to report errors, not invalidity - ignore it
3250 if (!ActivateBestChain(state, chainparams, pblock))
3251 return error("%s: ActivateBestChain failed", __func__);
3253 return true;
3256 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3258 AssertLockHeld(cs_main);
3259 assert(pindexPrev && pindexPrev == chainActive.Tip());
3260 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3261 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3263 CCoinsViewCache viewNew(pcoinsTip);
3264 CBlockIndex indexDummy(block);
3265 indexDummy.pprev = pindexPrev;
3266 indexDummy.nHeight = pindexPrev->nHeight + 1;
3268 // NOTE: CheckBlockHeader is called by CheckBlock
3269 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3270 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3271 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3272 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3273 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3274 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3275 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3276 return false;
3277 assert(state.IsValid());
3279 return true;
3283 * BLOCK PRUNING CODE
3286 /* Calculate the amount of disk space the block & undo files currently use */
3287 uint64_t CalculateCurrentUsage()
3289 uint64_t retval = 0;
3290 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3291 retval += file.nSize + file.nUndoSize;
3293 return retval;
3296 /* Prune a block file (modify associated database entries)*/
3297 void PruneOneBlockFile(const int fileNumber)
3299 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3300 CBlockIndex* pindex = it->second;
3301 if (pindex->nFile == fileNumber) {
3302 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3303 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3304 pindex->nFile = 0;
3305 pindex->nDataPos = 0;
3306 pindex->nUndoPos = 0;
3307 setDirtyBlockIndex.insert(pindex);
3309 // Prune from mapBlocksUnlinked -- any block we prune would have
3310 // to be downloaded again in order to consider its chain, at which
3311 // point it would be considered as a candidate for
3312 // mapBlocksUnlinked or setBlockIndexCandidates.
3313 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3314 while (range.first != range.second) {
3315 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3316 range.first++;
3317 if (_it->second == pindex) {
3318 mapBlocksUnlinked.erase(_it);
3324 vinfoBlockFile[fileNumber].SetNull();
3325 setDirtyFileInfo.insert(fileNumber);
3329 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3331 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3332 CDiskBlockPos pos(*it, 0);
3333 fs::remove(GetBlockPosFilename(pos, "blk"));
3334 fs::remove(GetBlockPosFilename(pos, "rev"));
3335 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3339 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3340 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3342 assert(fPruneMode && nManualPruneHeight > 0);
3344 LOCK2(cs_main, cs_LastBlockFile);
3345 if (chainActive.Tip() == NULL)
3346 return;
3348 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3349 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3350 int count=0;
3351 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3352 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3353 continue;
3354 PruneOneBlockFile(fileNumber);
3355 setFilesToPrune.insert(fileNumber);
3356 count++;
3358 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3361 /* This function is called from the RPC code for pruneblockchain */
3362 void PruneBlockFilesManual(int nManualPruneHeight)
3364 CValidationState state;
3365 FlushStateToDisk(state, FLUSH_STATE_NONE, nManualPruneHeight);
3368 /* Calculate the block/rev files that should be deleted to remain under target*/
3369 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3371 LOCK2(cs_main, cs_LastBlockFile);
3372 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3373 return;
3375 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3376 return;
3379 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3380 uint64_t nCurrentUsage = CalculateCurrentUsage();
3381 // We don't check to prune until after we've allocated new space for files
3382 // So we should leave a buffer under our target to account for another allocation
3383 // before the next pruning.
3384 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3385 uint64_t nBytesToPrune;
3386 int count=0;
3388 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3389 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3390 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3392 if (vinfoBlockFile[fileNumber].nSize == 0)
3393 continue;
3395 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3396 break;
3398 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3399 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3400 continue;
3402 PruneOneBlockFile(fileNumber);
3403 // Queue up the files for removal
3404 setFilesToPrune.insert(fileNumber);
3405 nCurrentUsage -= nBytesToPrune;
3406 count++;
3410 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3411 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3412 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3413 nLastBlockWeCanPrune, count);
3416 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3418 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3420 // Check for nMinDiskSpace bytes (currently 50MB)
3421 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3422 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3424 return true;
3427 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3429 if (pos.IsNull())
3430 return NULL;
3431 fs::path path = GetBlockPosFilename(pos, prefix);
3432 fs::create_directories(path.parent_path());
3433 FILE* file = fsbridge::fopen(path, "rb+");
3434 if (!file && !fReadOnly)
3435 file = fsbridge::fopen(path, "wb+");
3436 if (!file) {
3437 LogPrintf("Unable to open file %s\n", path.string());
3438 return NULL;
3440 if (pos.nPos) {
3441 if (fseek(file, pos.nPos, SEEK_SET)) {
3442 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3443 fclose(file);
3444 return NULL;
3447 return file;
3450 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3451 return OpenDiskFile(pos, "blk", fReadOnly);
3454 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3455 return OpenDiskFile(pos, "rev", fReadOnly);
3458 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3460 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3463 CBlockIndex * InsertBlockIndex(uint256 hash)
3465 if (hash.IsNull())
3466 return NULL;
3468 // Return existing
3469 BlockMap::iterator mi = mapBlockIndex.find(hash);
3470 if (mi != mapBlockIndex.end())
3471 return (*mi).second;
3473 // Create new
3474 CBlockIndex* pindexNew = new CBlockIndex();
3475 if (!pindexNew)
3476 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3477 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3478 pindexNew->phashBlock = &((*mi).first);
3480 return pindexNew;
3483 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3485 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3486 return false;
3488 boost::this_thread::interruption_point();
3490 // Calculate nChainWork
3491 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3492 vSortedByHeight.reserve(mapBlockIndex.size());
3493 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3495 CBlockIndex* pindex = item.second;
3496 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3498 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3499 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3501 CBlockIndex* pindex = item.second;
3502 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3503 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3504 // We can link the chain of blocks for which we've received transactions at some point.
3505 // Pruned nodes may have deleted the block.
3506 if (pindex->nTx > 0) {
3507 if (pindex->pprev) {
3508 if (pindex->pprev->nChainTx) {
3509 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3510 } else {
3511 pindex->nChainTx = 0;
3512 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3514 } else {
3515 pindex->nChainTx = pindex->nTx;
3518 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3519 setBlockIndexCandidates.insert(pindex);
3520 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3521 pindexBestInvalid = pindex;
3522 if (pindex->pprev)
3523 pindex->BuildSkip();
3524 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3525 pindexBestHeader = pindex;
3528 // Load block file info
3529 pblocktree->ReadLastBlockFile(nLastBlockFile);
3530 vinfoBlockFile.resize(nLastBlockFile + 1);
3531 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3532 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3533 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3535 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3536 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3537 CBlockFileInfo info;
3538 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3539 vinfoBlockFile.push_back(info);
3540 } else {
3541 break;
3545 // Check presence of blk files
3546 LogPrintf("Checking all blk files are present...\n");
3547 std::set<int> setBlkDataFiles;
3548 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3550 CBlockIndex* pindex = item.second;
3551 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3552 setBlkDataFiles.insert(pindex->nFile);
3555 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3557 CDiskBlockPos pos(*it, 0);
3558 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3559 return false;
3563 // Check whether we have ever pruned block & undo files
3564 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3565 if (fHavePruned)
3566 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3568 // Check whether we need to continue reindexing
3569 bool fReindexing = false;
3570 pblocktree->ReadReindexing(fReindexing);
3571 fReindex |= fReindexing;
3573 // Check whether we have a transaction index
3574 pblocktree->ReadFlag("txindex", fTxIndex);
3575 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3577 // Load pointer to end of best chain
3578 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3579 if (it == mapBlockIndex.end())
3580 return true;
3581 chainActive.SetTip(it->second);
3583 PruneBlockIndexCandidates();
3585 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3586 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3587 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3588 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3590 return true;
3593 CVerifyDB::CVerifyDB()
3595 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3598 CVerifyDB::~CVerifyDB()
3600 uiInterface.ShowProgress("", 100);
3603 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3605 LOCK(cs_main);
3606 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3607 return true;
3609 // Verify blocks in the best chain
3610 if (nCheckDepth <= 0)
3611 nCheckDepth = 1000000000; // suffices until the year 19000
3612 if (nCheckDepth > chainActive.Height())
3613 nCheckDepth = chainActive.Height();
3614 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3615 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3616 CCoinsViewCache coins(coinsview);
3617 CBlockIndex* pindexState = chainActive.Tip();
3618 CBlockIndex* pindexFailure = NULL;
3619 int nGoodTransactions = 0;
3620 CValidationState state;
3621 int reportDone = 0;
3622 LogPrintf("[0%%]...");
3623 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3625 boost::this_thread::interruption_point();
3626 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3627 if (reportDone < percentageDone/10) {
3628 // report every 10% step
3629 LogPrintf("[%d%%]...", percentageDone);
3630 reportDone = percentageDone/10;
3632 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3633 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3634 break;
3635 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3636 // If pruning, only go back as far as we have data.
3637 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3638 break;
3640 CBlock block;
3641 // check level 0: read from disk
3642 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3643 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3644 // check level 1: verify block validity
3645 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3646 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3647 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3648 // check level 2: verify undo validity
3649 if (nCheckLevel >= 2 && pindex) {
3650 CBlockUndo undo;
3651 CDiskBlockPos pos = pindex->GetUndoPos();
3652 if (!pos.IsNull()) {
3653 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3654 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3657 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3658 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3659 bool fClean = true;
3660 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3661 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3662 pindexState = pindex->pprev;
3663 if (!fClean) {
3664 nGoodTransactions = 0;
3665 pindexFailure = pindex;
3666 } else
3667 nGoodTransactions += block.vtx.size();
3669 if (ShutdownRequested())
3670 return true;
3672 if (pindexFailure)
3673 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3675 // check level 4: try reconnecting blocks
3676 if (nCheckLevel >= 4) {
3677 CBlockIndex *pindex = pindexState;
3678 while (pindex != chainActive.Tip()) {
3679 boost::this_thread::interruption_point();
3680 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3681 pindex = chainActive.Next(pindex);
3682 CBlock block;
3683 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3684 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3685 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3686 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3690 LogPrintf("[DONE].\n");
3691 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3693 return true;
3696 bool RewindBlockIndex(const CChainParams& params)
3698 LOCK(cs_main);
3700 int nHeight = 1;
3701 while (nHeight <= chainActive.Height()) {
3702 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3703 break;
3705 nHeight++;
3708 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3709 CValidationState state;
3710 CBlockIndex* pindex = chainActive.Tip();
3711 while (chainActive.Height() >= nHeight) {
3712 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3713 // If pruning, don't try rewinding past the HAVE_DATA point;
3714 // since older blocks can't be served anyway, there's
3715 // no need to walk further, and trying to DisconnectTip()
3716 // will fail (and require a needless reindex/redownload
3717 // of the blockchain).
3718 break;
3720 if (!DisconnectTip(state, params, true)) {
3721 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3723 // Occasionally flush state to disk.
3724 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3725 return false;
3728 // Reduce validity flag and have-data flags.
3729 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3730 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3731 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3732 CBlockIndex* pindexIter = it->second;
3734 // Note: If we encounter an insufficiently validated block that
3735 // is on chainActive, it must be because we are a pruning node, and
3736 // this block or some successor doesn't HAVE_DATA, so we were unable to
3737 // rewind all the way. Blocks remaining on chainActive at this point
3738 // must not have their validity reduced.
3739 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3740 // Reduce validity
3741 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3742 // Remove have-data flags.
3743 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3744 // Remove storage location.
3745 pindexIter->nFile = 0;
3746 pindexIter->nDataPos = 0;
3747 pindexIter->nUndoPos = 0;
3748 // Remove various other things
3749 pindexIter->nTx = 0;
3750 pindexIter->nChainTx = 0;
3751 pindexIter->nSequenceId = 0;
3752 // Make sure it gets written.
3753 setDirtyBlockIndex.insert(pindexIter);
3754 // Update indexes
3755 setBlockIndexCandidates.erase(pindexIter);
3756 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3757 while (ret.first != ret.second) {
3758 if (ret.first->second == pindexIter) {
3759 mapBlocksUnlinked.erase(ret.first++);
3760 } else {
3761 ++ret.first;
3764 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3765 setBlockIndexCandidates.insert(pindexIter);
3769 PruneBlockIndexCandidates();
3771 CheckBlockIndex(params.GetConsensus());
3773 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3774 return false;
3777 return true;
3780 // May NOT be used after any connections are up as much
3781 // of the peer-processing logic assumes a consistent
3782 // block index state
3783 void UnloadBlockIndex()
3785 LOCK(cs_main);
3786 setBlockIndexCandidates.clear();
3787 chainActive.SetTip(NULL);
3788 pindexBestInvalid = NULL;
3789 pindexBestHeader = NULL;
3790 mempool.clear();
3791 mapBlocksUnlinked.clear();
3792 vinfoBlockFile.clear();
3793 nLastBlockFile = 0;
3794 nBlockSequenceId = 1;
3795 setDirtyBlockIndex.clear();
3796 setDirtyFileInfo.clear();
3797 versionbitscache.Clear();
3798 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3799 warningcache[b].clear();
3802 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3803 delete entry.second;
3805 mapBlockIndex.clear();
3806 fHavePruned = false;
3809 bool LoadBlockIndex(const CChainParams& chainparams)
3811 // Load block index from databases
3812 if (!fReindex && !LoadBlockIndexDB(chainparams))
3813 return false;
3814 return true;
3817 bool InitBlockIndex(const CChainParams& chainparams)
3819 LOCK(cs_main);
3821 // Check whether we're already initialized
3822 if (chainActive.Genesis() != NULL)
3823 return true;
3825 // Use the provided setting for -txindex in the new database
3826 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3827 pblocktree->WriteFlag("txindex", fTxIndex);
3828 LogPrintf("Initializing databases...\n");
3830 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3831 if (!fReindex) {
3832 try {
3833 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3834 // Start new block file
3835 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3836 CDiskBlockPos blockPos;
3837 CValidationState state;
3838 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3839 return error("LoadBlockIndex(): FindBlockPos failed");
3840 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3841 return error("LoadBlockIndex(): writing genesis block to disk failed");
3842 CBlockIndex *pindex = AddToBlockIndex(block);
3843 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3844 return error("LoadBlockIndex(): genesis block not accepted");
3845 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3846 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3847 } catch (const std::runtime_error& e) {
3848 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3852 return true;
3855 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3857 // Map of disk positions for blocks with unknown parent (only used for reindex)
3858 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3859 int64_t nStart = GetTimeMillis();
3861 int nLoaded = 0;
3862 try {
3863 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3864 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3865 uint64_t nRewind = blkdat.GetPos();
3866 while (!blkdat.eof()) {
3867 boost::this_thread::interruption_point();
3869 blkdat.SetPos(nRewind);
3870 nRewind++; // start one byte further next time, in case of failure
3871 blkdat.SetLimit(); // remove former limit
3872 unsigned int nSize = 0;
3873 try {
3874 // locate a header
3875 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3876 blkdat.FindByte(chainparams.MessageStart()[0]);
3877 nRewind = blkdat.GetPos()+1;
3878 blkdat >> FLATDATA(buf);
3879 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3880 continue;
3881 // read size
3882 blkdat >> nSize;
3883 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3884 continue;
3885 } catch (const std::exception&) {
3886 // no valid block header found; don't complain
3887 break;
3889 try {
3890 // read block
3891 uint64_t nBlockPos = blkdat.GetPos();
3892 if (dbp)
3893 dbp->nPos = nBlockPos;
3894 blkdat.SetLimit(nBlockPos + nSize);
3895 blkdat.SetPos(nBlockPos);
3896 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3897 CBlock& block = *pblock;
3898 blkdat >> block;
3899 nRewind = blkdat.GetPos();
3901 // detect out of order blocks, and store them for later
3902 uint256 hash = block.GetHash();
3903 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3904 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3905 block.hashPrevBlock.ToString());
3906 if (dbp)
3907 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3908 continue;
3911 // process in case the block isn't known yet
3912 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3913 LOCK(cs_main);
3914 CValidationState state;
3915 if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3916 nLoaded++;
3917 if (state.IsError())
3918 break;
3919 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3920 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3923 // Activate the genesis block so normal node progress can continue
3924 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3925 CValidationState state;
3926 if (!ActivateBestChain(state, chainparams)) {
3927 break;
3931 NotifyHeaderTip();
3933 // Recursively process earlier encountered successors of this block
3934 std::deque<uint256> queue;
3935 queue.push_back(hash);
3936 while (!queue.empty()) {
3937 uint256 head = queue.front();
3938 queue.pop_front();
3939 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3940 while (range.first != range.second) {
3941 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3942 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
3943 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
3945 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
3946 head.ToString());
3947 LOCK(cs_main);
3948 CValidationState dummy;
3949 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
3951 nLoaded++;
3952 queue.push_back(pblockrecursive->GetHash());
3955 range.first++;
3956 mapBlocksUnknownParent.erase(it);
3957 NotifyHeaderTip();
3960 } catch (const std::exception& e) {
3961 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3964 } catch (const std::runtime_error& e) {
3965 AbortNode(std::string("System error: ") + e.what());
3967 if (nLoaded > 0)
3968 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3969 return nLoaded > 0;
3972 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3974 if (!fCheckBlockIndex) {
3975 return;
3978 LOCK(cs_main);
3980 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3981 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3982 // iterating the block tree require that chainActive has been initialized.)
3983 if (chainActive.Height() < 0) {
3984 assert(mapBlockIndex.size() <= 1);
3985 return;
3988 // Build forward-pointing map of the entire block tree.
3989 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3990 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3991 forward.insert(std::make_pair(it->second->pprev, it->second));
3994 assert(forward.size() == mapBlockIndex.size());
3996 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3997 CBlockIndex *pindex = rangeGenesis.first->second;
3998 rangeGenesis.first++;
3999 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4001 // Iterate over the entire block tree, using depth-first search.
4002 // Along the way, remember whether there are blocks on the path from genesis
4003 // block being explored which are the first to have certain properties.
4004 size_t nNodes = 0;
4005 int nHeight = 0;
4006 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4007 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4008 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4009 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4010 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4011 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4012 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4013 while (pindex != NULL) {
4014 nNodes++;
4015 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4016 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4017 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4018 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4019 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4020 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4021 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4023 // Begin: actual consistency checks.
4024 if (pindex->pprev == NULL) {
4025 // Genesis block checks.
4026 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4027 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4029 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)
4030 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4031 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4032 if (!fHavePruned) {
4033 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4034 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4035 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4036 } else {
4037 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4038 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4040 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4041 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4042 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4043 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4044 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4045 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4046 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.
4047 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4048 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4049 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4050 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4051 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4052 if (pindexFirstInvalid == NULL) {
4053 // Checks for not-invalid blocks.
4054 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4056 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4057 if (pindexFirstInvalid == NULL) {
4058 // If this block sorts at least as good as the current tip and
4059 // is valid and we have all data for its parents, it must be in
4060 // setBlockIndexCandidates. chainActive.Tip() must also be there
4061 // even if some data has been pruned.
4062 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4063 assert(setBlockIndexCandidates.count(pindex));
4065 // If some parent is missing, then it could be that this block was in
4066 // setBlockIndexCandidates but had to be removed because of the missing data.
4067 // In this case it must be in mapBlocksUnlinked -- see test below.
4069 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4070 assert(setBlockIndexCandidates.count(pindex) == 0);
4072 // Check whether this block is in mapBlocksUnlinked.
4073 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4074 bool foundInUnlinked = false;
4075 while (rangeUnlinked.first != rangeUnlinked.second) {
4076 assert(rangeUnlinked.first->first == pindex->pprev);
4077 if (rangeUnlinked.first->second == pindex) {
4078 foundInUnlinked = true;
4079 break;
4081 rangeUnlinked.first++;
4083 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4084 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4085 assert(foundInUnlinked);
4087 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4088 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4089 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4090 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4091 assert(fHavePruned); // We must have pruned.
4092 // This block may have entered mapBlocksUnlinked if:
4093 // - it has a descendant that at some point had more work than the
4094 // tip, and
4095 // - we tried switching to that descendant but were missing
4096 // data for some intermediate block between chainActive and the
4097 // tip.
4098 // So if this block is itself better than chainActive.Tip() and it wasn't in
4099 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4100 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4101 if (pindexFirstInvalid == NULL) {
4102 assert(foundInUnlinked);
4106 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4107 // End: actual consistency checks.
4109 // Try descending into the first subnode.
4110 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4111 if (range.first != range.second) {
4112 // A subnode was found.
4113 pindex = range.first->second;
4114 nHeight++;
4115 continue;
4117 // This is a leaf node.
4118 // Move upwards until we reach a node of which we have not yet visited the last child.
4119 while (pindex) {
4120 // We are going to either move to a parent or a sibling of pindex.
4121 // If pindex was the first with a certain property, unset the corresponding variable.
4122 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4123 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4124 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4125 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4126 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4127 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4128 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4129 // Find our parent.
4130 CBlockIndex* pindexPar = pindex->pprev;
4131 // Find which child we just visited.
4132 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4133 while (rangePar.first->second != pindex) {
4134 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4135 rangePar.first++;
4137 // Proceed to the next one.
4138 rangePar.first++;
4139 if (rangePar.first != rangePar.second) {
4140 // Move to the sibling.
4141 pindex = rangePar.first->second;
4142 break;
4143 } else {
4144 // Move up further.
4145 pindex = pindexPar;
4146 nHeight--;
4147 continue;
4152 // Check that we actually traversed the entire map.
4153 assert(nNodes == forward.size());
4156 std::string CBlockFileInfo::ToString() const
4158 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));
4161 CBlockFileInfo* GetBlockFileInfo(size_t n)
4163 return &vinfoBlockFile.at(n);
4166 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4168 LOCK(cs_main);
4169 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4172 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4174 LOCK(cs_main);
4175 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4178 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4180 bool LoadMempool(void)
4182 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4183 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4184 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4185 if (file.IsNull()) {
4186 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4187 return false;
4190 int64_t count = 0;
4191 int64_t skipped = 0;
4192 int64_t failed = 0;
4193 int64_t nNow = GetTime();
4195 try {
4196 uint64_t version;
4197 file >> version;
4198 if (version != MEMPOOL_DUMP_VERSION) {
4199 return false;
4201 uint64_t num;
4202 file >> num;
4203 while (num--) {
4204 CTransactionRef tx;
4205 int64_t nTime;
4206 int64_t nFeeDelta;
4207 file >> tx;
4208 file >> nTime;
4209 file >> nFeeDelta;
4211 CAmount amountdelta = nFeeDelta;
4212 if (amountdelta) {
4213 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4215 CValidationState state;
4216 if (nTime + nExpiryTimeout > nNow) {
4217 LOCK(cs_main);
4218 AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
4219 if (state.IsValid()) {
4220 ++count;
4221 } else {
4222 ++failed;
4224 } else {
4225 ++skipped;
4227 if (ShutdownRequested())
4228 return false;
4230 std::map<uint256, CAmount> mapDeltas;
4231 file >> mapDeltas;
4233 for (const auto& i : mapDeltas) {
4234 mempool.PrioritiseTransaction(i.first, i.second);
4236 } catch (const std::exception& e) {
4237 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4238 return false;
4241 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4242 return true;
4245 void DumpMempool(void)
4247 int64_t start = GetTimeMicros();
4249 std::map<uint256, CAmount> mapDeltas;
4250 std::vector<TxMempoolInfo> vinfo;
4253 LOCK(mempool.cs);
4254 for (const auto &i : mempool.mapDeltas) {
4255 mapDeltas[i.first] = i.second;
4257 vinfo = mempool.infoAll();
4260 int64_t mid = GetTimeMicros();
4262 try {
4263 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4264 if (!filestr) {
4265 return;
4268 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4270 uint64_t version = MEMPOOL_DUMP_VERSION;
4271 file << version;
4273 file << (uint64_t)vinfo.size();
4274 for (const auto& i : vinfo) {
4275 file << *(i.tx);
4276 file << (int64_t)i.nTime;
4277 file << (int64_t)i.nFeeDelta;
4278 mapDeltas.erase(i.tx->GetHash());
4281 file << mapDeltas;
4282 FileCommit(file.Get());
4283 file.fclose();
4284 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4285 int64_t last = GetTimeMicros();
4286 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4287 } catch (const std::exception& e) {
4288 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4292 //! Guess how far we are in the verification process at the given block index
4293 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4294 if (pindex == NULL)
4295 return 0.0;
4297 int64_t nNow = time(NULL);
4299 double fTxTotal;
4301 if (pindex->nChainTx <= data.nTxCount) {
4302 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4303 } else {
4304 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4307 return pindex->nChainTx / fTxTotal;
4310 class CMainCleanup
4312 public:
4313 CMainCleanup() {}
4314 ~CMainCleanup() {
4315 // block headers
4316 BlockMap::iterator it1 = mapBlockIndex.begin();
4317 for (; it1 != mapBlockIndex.end(); it1++)
4318 delete (*it1).second;
4319 mapBlockIndex.clear();
4321 } instance_of_cmaincleanup;