Merge #10279: Add a CChainState class to validation.cpp to take another step towards...
[bitcoinplatinum.git] / src / validation.cpp
blob946a916e822c801652bfb0f74060bdd63a5534cd
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <validation.h>
8 #include <arith_uint256.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <checkpoints.h>
12 #include <checkqueue.h>
13 #include <consensus/consensus.h>
14 #include <consensus/merkle.h>
15 #include <consensus/tx_verify.h>
16 #include <consensus/validation.h>
17 #include <cuckoocache.h>
18 #include <fs.h>
19 #include <hash.h>
20 #include <init.h>
21 #include <policy/fees.h>
22 #include <policy/policy.h>
23 #include <policy/rbf.h>
24 #include <pow.h>
25 #include <primitives/block.h>
26 #include <primitives/transaction.h>
27 #include <random.h>
28 #include <reverse_iterator.h>
29 #include <script/script.h>
30 #include <script/sigcache.h>
31 #include <script/standard.h>
32 #include <timedata.h>
33 #include <tinyformat.h>
34 #include <txdb.h>
35 #include <txmempool.h>
36 #include <ui_interface.h>
37 #include <undo.h>
38 #include <util.h>
39 #include <utilmoneystr.h>
40 #include <utilstrencodings.h>
41 #include <validationinterface.h>
42 #include <versionbits.h>
43 #include <warnings.h>
45 #include <atomic>
46 #include <sstream>
48 #include <boost/algorithm/string/replace.hpp>
49 #include <boost/algorithm/string/join.hpp>
50 #include <boost/thread.hpp>
52 #if defined(NDEBUG)
53 # error "Bitcoin cannot be compiled without assertions."
54 #endif
56 #define MICRO 0.000001
57 #define MILLI 0.001
59 /**
60 * Global state
62 namespace {
63 struct CBlockIndexWorkComparator
65 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
66 // First sort by most total work, ...
67 if (pa->nChainWork > pb->nChainWork) return false;
68 if (pa->nChainWork < pb->nChainWork) return true;
70 // ... then by earliest time received, ...
71 if (pa->nSequenceId < pb->nSequenceId) return false;
72 if (pa->nSequenceId > pb->nSequenceId) return true;
74 // Use pointer address as tie breaker (should only happen with blocks
75 // loaded from disk, as those all have id 0).
76 if (pa < pb) return false;
77 if (pa > pb) return true;
79 // Identical blocks.
80 return false;
83 } // anon namespace
85 enum DisconnectResult
87 DISCONNECT_OK, // All good.
88 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
89 DISCONNECT_FAILED // Something else went wrong.
92 class ConnectTrace;
94 /**
95 * CChainState stores and provides an API to update our local knowledge of the
96 * current best chain and header tree.
98 * It generally provides access to the current block tree, as well as functions
99 * to provide new data, which it will appropriately validate and incorporate in
100 * its state as necessary.
102 * Eventually, the API here is targeted at being exposed externally as a
103 * consumable libconsensus library, so any functions added must only call
104 * other class member functions, pure functions in other parts of the consensus
105 * library, callbacks via the validation interface, or read/write-to-disk
106 * functions (eventually this will also be via callbacks).
108 class CChainState {
109 private:
111 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
112 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
113 * missing the data for the block.
115 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
118 * Every received block is assigned a unique and increasing identifier, so we
119 * know which one to give priority in case of a fork.
121 CCriticalSection cs_nBlockSequenceId;
122 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
123 int32_t nBlockSequenceId = 1;
124 /** Decreasing counter (used by subsequent preciousblock calls). */
125 int32_t nBlockReverseSequenceId = -1;
126 /** chainwork for the last block that preciousblock has been applied to. */
127 arith_uint256 nLastPreciousChainwork = 0;
129 /** In order to efficiently track invalidity of headers, we keep the set of
130 * blocks which we tried to connect and found to be invalid here (ie which
131 * were set to BLOCK_FAILED_VALID since the last restart). We can then
132 * walk this set and check if a new header is a descendant of something in
133 * this set, preventing us from having to walk mapBlockIndex when we try
134 * to connect a bad block and fail.
136 * While this is more complicated than marking everything which descends
137 * from an invalid block as invalid at the time we discover it to be
138 * invalid, doing so would require walking all of mapBlockIndex to find all
139 * descendants. Since this case should be very rare, keeping track of all
140 * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
141 * well.
143 * Because we already walk mapBlockIndex in height-order at startup, we go
144 * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
145 * instead of putting things in this set.
147 std::set<CBlockIndex*> g_failed_blocks;
149 public:
150 CChain chainActive;
151 BlockMap mapBlockIndex;
152 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
153 CBlockIndex *pindexBestInvalid = nullptr;
155 bool LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree);
157 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock);
159 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex);
160 bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock);
162 // Block (dis)connection on a given view:
163 DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
164 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
165 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false);
167 // Block disconnection on our pcoinsTip:
168 bool DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool);
170 // Manual block validity manipulation:
171 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex);
172 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex);
173 bool ResetBlockFailureFlags(CBlockIndex *pindex);
175 bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
176 bool RewindBlockIndex(const CChainParams& params);
177 bool LoadGenesisBlock(const CChainParams& chainparams);
179 void PruneBlockIndexCandidates();
181 void UnloadBlockIndex();
183 private:
184 bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace);
185 bool ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool);
187 CBlockIndex* AddToBlockIndex(const CBlockHeader& block);
188 /** Create a new block index entry for a given block hash */
189 CBlockIndex * InsertBlockIndex(const uint256& hash);
190 void CheckBlockIndex(const Consensus::Params& consensusParams);
192 void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state);
193 CBlockIndex* FindMostWorkChain();
194 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
197 bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params);
198 } g_chainstate;
202 CCriticalSection cs_main;
204 BlockMap& mapBlockIndex = g_chainstate.mapBlockIndex;
205 CChain& chainActive = g_chainstate.chainActive;
206 CBlockIndex *pindexBestHeader = nullptr;
207 CWaitableCriticalSection csBestBlock;
208 CConditionVariable cvBlockChange;
209 int nScriptCheckThreads = 0;
210 std::atomic_bool fImporting(false);
211 std::atomic_bool fReindex(false);
212 bool fTxIndex = false;
213 bool fHavePruned = false;
214 bool fPruneMode = false;
215 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
216 bool fRequireStandard = true;
217 bool fCheckBlockIndex = false;
218 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
219 size_t nCoinCacheUsage = 5000 * 300;
220 uint64_t nPruneTarget = 0;
221 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
222 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
224 uint256 hashAssumeValid;
225 arith_uint256 nMinimumChainWork;
227 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
228 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
230 CBlockPolicyEstimator feeEstimator;
231 CTxMemPool mempool(&feeEstimator);
233 /** Constant stuff for coinbase transactions we create: */
234 CScript COINBASE_FLAGS;
236 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
238 // Internal stuff
239 namespace {
240 CBlockIndex *&pindexBestInvalid = g_chainstate.pindexBestInvalid;
242 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
243 * Pruned nodes may have entries where B is missing data.
245 std::multimap<CBlockIndex*, CBlockIndex*>& mapBlocksUnlinked = g_chainstate.mapBlocksUnlinked;
247 CCriticalSection cs_LastBlockFile;
248 std::vector<CBlockFileInfo> vinfoBlockFile;
249 int nLastBlockFile = 0;
250 /** Global flag to indicate we should check to see if there are
251 * block/undo files that should be deleted. Set on startup
252 * or if we allocate more file space when we're in prune mode
254 bool fCheckForPruning = false;
256 /** Dirty block index entries. */
257 std::set<CBlockIndex*> setDirtyBlockIndex;
259 /** Dirty block file entries. */
260 std::set<int> setDirtyFileInfo;
261 } // anon namespace
263 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
265 // Find the first block the caller has in the main chain
266 for (const uint256& hash : locator.vHave) {
267 BlockMap::iterator mi = mapBlockIndex.find(hash);
268 if (mi != mapBlockIndex.end())
270 CBlockIndex* pindex = (*mi).second;
271 if (chain.Contains(pindex))
272 return pindex;
273 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
274 return chain.Tip();
278 return chain.Genesis();
281 std::unique_ptr<CCoinsViewDB> pcoinsdbview;
282 std::unique_ptr<CCoinsViewCache> pcoinsTip;
283 std::unique_ptr<CBlockTreeDB> pblocktree;
285 enum FlushStateMode {
286 FLUSH_STATE_NONE,
287 FLUSH_STATE_IF_NEEDED,
288 FLUSH_STATE_PERIODIC,
289 FLUSH_STATE_ALWAYS
292 // See definition for documentation
293 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
294 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
295 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
296 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
297 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
299 bool CheckFinalTx(const CTransaction &tx, int flags)
301 AssertLockHeld(cs_main);
303 // By convention a negative value for flags indicates that the
304 // current network-enforced consensus rules should be used. In
305 // a future soft-fork scenario that would mean checking which
306 // rules would be enforced for the next block and setting the
307 // appropriate flags. At the present time no soft-forks are
308 // scheduled, so no flags are set.
309 flags = std::max(flags, 0);
311 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
312 // nLockTime because when IsFinalTx() is called within
313 // CBlock::AcceptBlock(), the height of the block *being*
314 // evaluated is what is used. Thus if we want to know if a
315 // transaction can be part of the *next* block, we need to call
316 // IsFinalTx() with one more than chainActive.Height().
317 const int nBlockHeight = chainActive.Height() + 1;
319 // BIP113 requires that time-locked transactions have nLockTime set to
320 // less than the median time of the previous block they're contained in.
321 // When the next block is created its previous block will be the current
322 // chain tip, so we use that to calculate the median time passed to
323 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
324 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
325 ? chainActive.Tip()->GetMedianTimePast()
326 : GetAdjustedTime();
328 return IsFinalTx(tx, nBlockHeight, nBlockTime);
331 bool TestLockPointValidity(const LockPoints* lp)
333 AssertLockHeld(cs_main);
334 assert(lp);
335 // If there are relative lock times then the maxInputBlock will be set
336 // If there are no relative lock times, the LockPoints don't depend on the chain
337 if (lp->maxInputBlock) {
338 // Check whether chainActive is an extension of the block at which the LockPoints
339 // calculation was valid. If not LockPoints are no longer valid
340 if (!chainActive.Contains(lp->maxInputBlock)) {
341 return false;
345 // LockPoints still valid
346 return true;
349 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
351 AssertLockHeld(cs_main);
352 AssertLockHeld(mempool.cs);
354 CBlockIndex* tip = chainActive.Tip();
355 assert(tip != nullptr);
357 CBlockIndex index;
358 index.pprev = tip;
359 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
360 // height based locks because when SequenceLocks() is called within
361 // ConnectBlock(), the height of the block *being*
362 // evaluated is what is used.
363 // Thus if we want to know if a transaction can be part of the
364 // *next* block, we need to use one more than chainActive.Height()
365 index.nHeight = tip->nHeight + 1;
367 std::pair<int, int64_t> lockPair;
368 if (useExistingLockPoints) {
369 assert(lp);
370 lockPair.first = lp->height;
371 lockPair.second = lp->time;
373 else {
374 // pcoinsTip contains the UTXO set for chainActive.Tip()
375 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool);
376 std::vector<int> prevheights;
377 prevheights.resize(tx.vin.size());
378 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
379 const CTxIn& txin = tx.vin[txinIndex];
380 Coin coin;
381 if (!viewMemPool.GetCoin(txin.prevout, coin)) {
382 return error("%s: Missing input", __func__);
384 if (coin.nHeight == MEMPOOL_HEIGHT) {
385 // Assume all mempool transaction confirm in the next block
386 prevheights[txinIndex] = tip->nHeight + 1;
387 } else {
388 prevheights[txinIndex] = coin.nHeight;
391 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
392 if (lp) {
393 lp->height = lockPair.first;
394 lp->time = lockPair.second;
395 // Also store the hash of the block with the highest height of
396 // all the blocks which have sequence locked prevouts.
397 // This hash needs to still be on the chain
398 // for these LockPoint calculations to be valid
399 // Note: It is impossible to correctly calculate a maxInputBlock
400 // if any of the sequence locked inputs depend on unconfirmed txs,
401 // except in the special case where the relative lock time/height
402 // is 0, which is equivalent to no sequence lock. Since we assume
403 // input height of tip+1 for mempool txs and test the resulting
404 // lockPair from CalculateSequenceLocks against tip+1. We know
405 // EvaluateSequenceLocks will fail if there was a non-zero sequence
406 // lock on a mempool input, so we can use the return value of
407 // CheckSequenceLocks to indicate the LockPoints validity
408 int maxInputHeight = 0;
409 for (int height : prevheights) {
410 // Can ignore mempool inputs since we'll fail if they had non-zero locks
411 if (height != tip->nHeight+1) {
412 maxInputHeight = std::max(maxInputHeight, height);
415 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
418 return EvaluateSequenceLocks(index, lockPair);
421 // Returns the script flags which should be checked for a given block
422 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
424 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
425 int expired = pool.Expire(GetTime() - age);
426 if (expired != 0) {
427 LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
430 std::vector<COutPoint> vNoSpendsRemaining;
431 pool.TrimToSize(limit, &vNoSpendsRemaining);
432 for (const COutPoint& removed : vNoSpendsRemaining)
433 pcoinsTip->Uncache(removed);
436 /** Convert CValidationState to a human-readable message for logging */
437 std::string FormatStateMessage(const CValidationState &state)
439 return strprintf("%s%s (code %i)",
440 state.GetRejectReason(),
441 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
442 state.GetRejectCode());
445 static bool IsCurrentForFeeEstimation()
447 AssertLockHeld(cs_main);
448 if (IsInitialBlockDownload())
449 return false;
450 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
451 return false;
452 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
453 return false;
454 return true;
457 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
458 * disconnected block transactions from the mempool, and also removing any
459 * other transactions from the mempool that are no longer valid given the new
460 * tip/height.
462 * Note: we assume that disconnectpool only contains transactions that are NOT
463 * confirmed in the current chain nor already in the mempool (otherwise,
464 * in-mempool descendants of such transactions would be removed).
466 * Passing fAddToMempool=false will skip trying to add the transactions back,
467 * and instead just erase from the mempool as needed.
470 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
472 AssertLockHeld(cs_main);
473 std::vector<uint256> vHashUpdate;
474 // disconnectpool's insertion_order index sorts the entries from
475 // oldest to newest, but the oldest entry will be the last tx from the
476 // latest mined block that was disconnected.
477 // Iterate disconnectpool in reverse, so that we add transactions
478 // back to the mempool starting with the earliest transaction that had
479 // been previously seen in a block.
480 auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
481 while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
482 // ignore validation errors in resurrected transactions
483 CValidationState stateDummy;
484 if (!fAddToMempool || (*it)->IsCoinBase() ||
485 !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
486 nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
487 // If the transaction doesn't make it in to the mempool, remove any
488 // transactions that depend on it (which would now be orphans).
489 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
490 } else if (mempool.exists((*it)->GetHash())) {
491 vHashUpdate.push_back((*it)->GetHash());
493 ++it;
495 disconnectpool.queuedTx.clear();
496 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
497 // no in-mempool children, which is generally not true when adding
498 // previously-confirmed transactions back to the mempool.
499 // UpdateTransactionsFromBlock finds descendants of any transactions in
500 // the disconnectpool that were added back and cleans up the mempool state.
501 mempool.UpdateTransactionsFromBlock(vHashUpdate);
503 // We also need to remove any now-immature transactions
504 mempool.removeForReorg(pcoinsTip.get(), chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
505 // Re-limit mempool size, in case we added any transactions
506 LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
509 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
510 // were somehow broken and returning the wrong scriptPubKeys
511 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
512 unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
513 AssertLockHeld(cs_main);
515 // pool.cs should be locked already, but go ahead and re-take the lock here
516 // to enforce that mempool doesn't change between when we check the view
517 // and when we actually call through to CheckInputs
518 LOCK(pool.cs);
520 assert(!tx.IsCoinBase());
521 for (const CTxIn& txin : tx.vin) {
522 const Coin& coin = view.AccessCoin(txin.prevout);
524 // At this point we haven't actually checked if the coins are all
525 // available (or shouldn't assume we have, since CheckInputs does).
526 // So we just return failure if the inputs are not available here,
527 // and then only have to check equivalence for available inputs.
528 if (coin.IsSpent()) return false;
530 const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
531 if (txFrom) {
532 assert(txFrom->GetHash() == txin.prevout.hash);
533 assert(txFrom->vout.size() > txin.prevout.n);
534 assert(txFrom->vout[txin.prevout.n] == coin.out);
535 } else {
536 const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
537 assert(!coinFromDisk.IsSpent());
538 assert(coinFromDisk.out == coin.out);
542 return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
545 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
546 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
547 bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
549 const CTransaction& tx = *ptx;
550 const uint256 hash = tx.GetHash();
551 AssertLockHeld(cs_main);
552 if (pfMissingInputs)
553 *pfMissingInputs = false;
555 if (!CheckTransaction(tx, state))
556 return false; // state filled in by CheckTransaction
558 // Coinbase is only valid in a block, not as a loose transaction
559 if (tx.IsCoinBase())
560 return state.DoS(100, false, REJECT_INVALID, "coinbase");
562 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
563 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
564 if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
565 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
568 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
569 std::string reason;
570 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
571 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
573 // Only accept nLockTime-using transactions that can be mined in the next
574 // block; we don't want our mempool filled up with transactions that can't
575 // be mined yet.
576 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
577 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
579 // is it already in the memory pool?
580 if (pool.exists(hash)) {
581 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
584 // Check for conflicts with in-memory transactions
585 std::set<uint256> setConflicts;
587 LOCK(pool.cs); // protect pool.mapNextTx
588 for (const CTxIn &txin : tx.vin)
590 auto itConflicting = pool.mapNextTx.find(txin.prevout);
591 if (itConflicting != pool.mapNextTx.end())
593 const CTransaction *ptxConflicting = itConflicting->second;
594 if (!setConflicts.count(ptxConflicting->GetHash()))
596 // Allow opt-out of transaction replacement by setting
597 // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
599 // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
600 // non-replaceable transactions. All inputs rather than just one
601 // is for the sake of multi-party protocols, where we don't
602 // want a single party to be able to disable replacement.
604 // The opt-out ignores descendants as anyone relying on
605 // first-seen mempool behavior should be checking all
606 // unconfirmed ancestors anyway; doing otherwise is hopelessly
607 // insecure.
608 bool fReplacementOptOut = true;
609 if (fEnableReplacement)
611 for (const CTxIn &_txin : ptxConflicting->vin)
613 if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
615 fReplacementOptOut = false;
616 break;
620 if (fReplacementOptOut) {
621 return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
624 setConflicts.insert(ptxConflicting->GetHash());
631 CCoinsView dummy;
632 CCoinsViewCache view(&dummy);
634 LockPoints lp;
636 LOCK(pool.cs);
637 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
638 view.SetBackend(viewMemPool);
640 // do all inputs exist?
641 for (const CTxIn txin : tx.vin) {
642 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
643 coins_to_uncache.push_back(txin.prevout);
645 if (!view.HaveCoin(txin.prevout)) {
646 // Are inputs missing because we already have the tx?
647 for (size_t out = 0; out < tx.vout.size(); out++) {
648 // Optimistically just do efficient check of cache for outputs
649 if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
650 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
653 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
654 if (pfMissingInputs) {
655 *pfMissingInputs = true;
657 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
661 // Bring the best block into scope
662 view.GetBestBlock();
664 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
665 view.SetBackend(dummy);
667 // Only accept BIP68 sequence locked transactions that can be mined in the next
668 // block; we don't want our mempool filled up with transactions that can't
669 // be mined yet.
670 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
671 // CoinsViewCache instead of create its own
672 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
673 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
675 } // end LOCK(pool.cs)
677 CAmount nFees = 0;
678 if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
679 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
682 // Check for non-standard pay-to-script-hash in inputs
683 if (fRequireStandard && !AreInputsStandard(tx, view))
684 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
686 // Check for non-standard witness in P2WSH
687 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
688 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
690 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
692 // nModifiedFees includes any fee deltas from PrioritiseTransaction
693 CAmount nModifiedFees = nFees;
694 pool.ApplyDelta(hash, nModifiedFees);
696 // Keep track of transactions that spend a coinbase, which we re-scan
697 // during reorgs to ensure COINBASE_MATURITY is still met.
698 bool fSpendsCoinbase = false;
699 for (const CTxIn &txin : tx.vin) {
700 const Coin &coin = view.AccessCoin(txin.prevout);
701 if (coin.IsCoinBase()) {
702 fSpendsCoinbase = true;
703 break;
707 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
708 fSpendsCoinbase, nSigOpsCost, lp);
709 unsigned int nSize = entry.GetTxSize();
711 // Check that the transaction doesn't have an excessive number of
712 // sigops, making it impossible to mine. Since the coinbase transaction
713 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
714 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
715 // merely non-standard transaction.
716 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
717 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
718 strprintf("%d", nSigOpsCost));
720 CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
721 if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
722 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
725 // No transactions are allowed below minRelayTxFee except from disconnected blocks
726 if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
727 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
730 if (nAbsurdFee && nFees > nAbsurdFee)
731 return state.Invalid(false,
732 REJECT_HIGHFEE, "absurdly-high-fee",
733 strprintf("%d > %d", nFees, nAbsurdFee));
735 // Calculate in-mempool ancestors, up to a limit.
736 CTxMemPool::setEntries setAncestors;
737 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
738 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
739 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
740 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
741 std::string errString;
742 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
743 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
746 // A transaction that spends outputs that would be replaced by it is invalid. Now
747 // that we have the set of all ancestors we can detect this
748 // pathological case by making sure setConflicts and setAncestors don't
749 // intersect.
750 for (CTxMemPool::txiter ancestorIt : setAncestors)
752 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
753 if (setConflicts.count(hashAncestor))
755 return state.DoS(10, false,
756 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
757 strprintf("%s spends conflicting transaction %s",
758 hash.ToString(),
759 hashAncestor.ToString()));
763 // Check if it's economically rational to mine this transaction rather
764 // than the ones it replaces.
765 CAmount nConflictingFees = 0;
766 size_t nConflictingSize = 0;
767 uint64_t nConflictingCount = 0;
768 CTxMemPool::setEntries allConflicting;
770 // If we don't hold the lock allConflicting might be incomplete; the
771 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
772 // mempool consistency for us.
773 LOCK(pool.cs);
774 const bool fReplacementTransaction = setConflicts.size();
775 if (fReplacementTransaction)
777 CFeeRate newFeeRate(nModifiedFees, nSize);
778 std::set<uint256> setConflictsParents;
779 const int maxDescendantsToVisit = 100;
780 CTxMemPool::setEntries setIterConflicting;
781 for (const uint256 &hashConflicting : setConflicts)
783 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
784 if (mi == pool.mapTx.end())
785 continue;
787 // Save these to avoid repeated lookups
788 setIterConflicting.insert(mi);
790 // Don't allow the replacement to reduce the feerate of the
791 // mempool.
793 // We usually don't want to accept replacements with lower
794 // feerates than what they replaced as that would lower the
795 // feerate of the next block. Requiring that the feerate always
796 // be increased is also an easy-to-reason about way to prevent
797 // DoS attacks via replacements.
799 // The mining code doesn't (currently) take children into
800 // account (CPFP) so we only consider the feerates of
801 // transactions being directly replaced, not their indirect
802 // descendants. While that does mean high feerate children are
803 // ignored when deciding whether or not to replace, we do
804 // require the replacement to pay more overall fees too,
805 // mitigating most cases.
806 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
807 if (newFeeRate <= oldFeeRate)
809 return state.DoS(0, false,
810 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
811 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
812 hash.ToString(),
813 newFeeRate.ToString(),
814 oldFeeRate.ToString()));
817 for (const CTxIn &txin : mi->GetTx().vin)
819 setConflictsParents.insert(txin.prevout.hash);
822 nConflictingCount += mi->GetCountWithDescendants();
824 // This potentially overestimates the number of actual descendants
825 // but we just want to be conservative to avoid doing too much
826 // work.
827 if (nConflictingCount <= maxDescendantsToVisit) {
828 // If not too many to replace, then calculate the set of
829 // transactions that would have to be evicted
830 for (CTxMemPool::txiter it : setIterConflicting) {
831 pool.CalculateDescendants(it, allConflicting);
833 for (CTxMemPool::txiter it : allConflicting) {
834 nConflictingFees += it->GetModifiedFee();
835 nConflictingSize += it->GetTxSize();
837 } else {
838 return state.DoS(0, false,
839 REJECT_NONSTANDARD, "too many potential replacements", false,
840 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
841 hash.ToString(),
842 nConflictingCount,
843 maxDescendantsToVisit));
846 for (unsigned int j = 0; j < tx.vin.size(); j++)
848 // We don't want to accept replacements that require low
849 // feerate junk to be mined first. Ideally we'd keep track of
850 // the ancestor feerates and make the decision based on that,
851 // but for now requiring all new inputs to be confirmed works.
852 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
854 // Rather than check the UTXO set - potentially expensive -
855 // it's cheaper to just check if the new input refers to a
856 // tx that's in the mempool.
857 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
858 return state.DoS(0, false,
859 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
860 strprintf("replacement %s adds unconfirmed input, idx %d",
861 hash.ToString(), j));
865 // The replacement must pay greater fees than the transactions it
866 // replaces - if we did the bandwidth used by those conflicting
867 // transactions would not be paid for.
868 if (nModifiedFees < nConflictingFees)
870 return state.DoS(0, false,
871 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
872 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
873 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
876 // Finally in addition to paying more fees than the conflicts the
877 // new transaction must pay for its own bandwidth.
878 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
879 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
881 return state.DoS(0, false,
882 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
883 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
884 hash.ToString(),
885 FormatMoney(nDeltaFees),
886 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
890 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
891 if (!chainparams.RequireStandard()) {
892 scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
895 // Check against previous transactions
896 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
897 PrecomputedTransactionData txdata(tx);
898 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
899 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
900 // need to turn both off, and compare against just turning off CLEANSTACK
901 // to see if the failure is specifically due to witness validation.
902 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
903 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
904 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
905 // Only the witness is missing, so the transaction itself may be fine.
906 state.SetCorruptionPossible();
908 return false; // state filled in by CheckInputs
911 // Check again against the current block tip's script verification
912 // flags to cache our script execution flags. This is, of course,
913 // useless if the next block has different script flags from the
914 // previous one, but because the cache tracks script flags for us it
915 // will auto-invalidate and we'll just have a few blocks of extra
916 // misses on soft-fork activation.
918 // This is also useful in case of bugs in the standard flags that cause
919 // transactions to pass as valid when they're actually invalid. For
920 // instance the STRICTENC flag was incorrectly allowing certain
921 // CHECKSIG NOT scripts to pass, even though they were invalid.
923 // There is a similar check in CreateNewBlock() to prevent creating
924 // invalid blocks (using TestBlockValidity), however allowing such
925 // transactions into the mempool can be exploited as a DoS attack.
926 unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
927 if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
929 // If we're using promiscuousmempoolflags, we may hit this normally
930 // Check if current block has some flags that scriptVerifyFlags
931 // does not before printing an ominous warning
932 if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
933 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
934 __func__, hash.ToString(), FormatStateMessage(state));
935 } else {
936 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
937 return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
938 __func__, hash.ToString(), FormatStateMessage(state));
939 } else {
940 LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
945 // Remove conflicting transactions from the mempool
946 for (const CTxMemPool::txiter it : allConflicting)
948 LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
949 it->GetTx().GetHash().ToString(),
950 hash.ToString(),
951 FormatMoney(nModifiedFees - nConflictingFees),
952 (int)nSize - (int)nConflictingSize);
953 if (plTxnReplaced)
954 plTxnReplaced->push_back(it->GetSharedTx());
956 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
958 // This transaction should only count for fee estimation if:
959 // - it isn't a BIP 125 replacement transaction (may not be widely supported)
960 // - it's not being readded during a reorg which bypasses typical mempool fee limits
961 // - the node is not behind
962 // - the transaction is not dependent on any other transactions in the mempool
963 bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
965 // Store transaction in memory
966 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
968 // trim mempool and check if tx was trimmed
969 if (!bypass_limits) {
970 LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
971 if (!pool.exists(hash))
972 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
976 GetMainSignals().TransactionAddedToMempool(ptx);
978 return true;
981 /** (try to) add transaction to memory pool with a specified acceptance time **/
982 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
983 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
984 bool bypass_limits, const CAmount nAbsurdFee)
986 std::vector<COutPoint> coins_to_uncache;
987 bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
988 if (!res) {
989 for (const COutPoint& hashTx : coins_to_uncache)
990 pcoinsTip->Uncache(hashTx);
992 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
993 CValidationState stateDummy;
994 FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
995 return res;
998 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
999 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
1000 bool bypass_limits, const CAmount nAbsurdFee)
1002 const CChainParams& chainparams = Params();
1003 return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
1007 * Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.
1008 * If blockIndex is provided, the transaction is fetched from the corresponding block.
1010 bool GetTransaction(const uint256& hash, CTransactionRef& txOut, const Consensus::Params& consensusParams, uint256& hashBlock, bool fAllowSlow, CBlockIndex* blockIndex)
1012 CBlockIndex* pindexSlow = blockIndex;
1014 LOCK(cs_main);
1016 if (!blockIndex) {
1017 CTransactionRef ptx = mempool.get(hash);
1018 if (ptx) {
1019 txOut = ptx;
1020 return true;
1023 if (fTxIndex) {
1024 CDiskTxPos postx;
1025 if (pblocktree->ReadTxIndex(hash, postx)) {
1026 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1027 if (file.IsNull())
1028 return error("%s: OpenBlockFile failed", __func__);
1029 CBlockHeader header;
1030 try {
1031 file >> header;
1032 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1033 file >> txOut;
1034 } catch (const std::exception& e) {
1035 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1037 hashBlock = header.GetHash();
1038 if (txOut->GetHash() != hash)
1039 return error("%s: txid mismatch", __func__);
1040 return true;
1043 // transaction not found in index, nothing more can be done
1044 return false;
1047 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1048 const Coin& coin = AccessByTxid(*pcoinsTip, hash);
1049 if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
1053 if (pindexSlow) {
1054 CBlock block;
1055 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1056 for (const auto& tx : block.vtx) {
1057 if (tx->GetHash() == hash) {
1058 txOut = tx;
1059 hashBlock = pindexSlow->GetBlockHash();
1060 return true;
1066 return false;
1074 //////////////////////////////////////////////////////////////////////////////
1076 // CBlock and CBlockIndex
1079 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1081 // Open history file to append
1082 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1083 if (fileout.IsNull())
1084 return error("WriteBlockToDisk: OpenBlockFile failed");
1086 // Write index header
1087 unsigned int nSize = GetSerializeSize(fileout, block);
1088 fileout << FLATDATA(messageStart) << nSize;
1090 // Write block
1091 long fileOutPos = ftell(fileout.Get());
1092 if (fileOutPos < 0)
1093 return error("WriteBlockToDisk: ftell failed");
1094 pos.nPos = (unsigned int)fileOutPos;
1095 fileout << block;
1097 return true;
1100 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1102 block.SetNull();
1104 // Open history file to read
1105 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1106 if (filein.IsNull())
1107 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1109 // Read block
1110 try {
1111 filein >> block;
1113 catch (const std::exception& e) {
1114 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1117 // Check the header
1118 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1119 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1121 return true;
1124 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1126 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1127 return false;
1128 if (block.GetHash() != pindex->GetBlockHash())
1129 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1130 pindex->ToString(), pindex->GetBlockPos().ToString());
1131 return true;
1134 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1136 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1137 // Force block reward to zero when right shift is undefined.
1138 if (halvings >= 64)
1139 return 0;
1141 CAmount nSubsidy = 50 * COIN;
1142 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1143 nSubsidy >>= halvings;
1144 return nSubsidy;
1147 bool IsInitialBlockDownload()
1149 // Once this function has returned false, it must remain false.
1150 static std::atomic<bool> latchToFalse{false};
1151 // Optimization: pre-test latch before taking the lock.
1152 if (latchToFalse.load(std::memory_order_relaxed))
1153 return false;
1155 LOCK(cs_main);
1156 if (latchToFalse.load(std::memory_order_relaxed))
1157 return false;
1158 if (fImporting || fReindex)
1159 return true;
1160 if (chainActive.Tip() == nullptr)
1161 return true;
1162 if (chainActive.Tip()->nChainWork < nMinimumChainWork)
1163 return true;
1164 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1165 return true;
1166 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1167 latchToFalse.store(true, std::memory_order_relaxed);
1168 return false;
1171 CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
1173 static void AlertNotify(const std::string& strMessage)
1175 uiInterface.NotifyAlertChanged();
1176 std::string strCmd = gArgs.GetArg("-alertnotify", "");
1177 if (strCmd.empty()) return;
1179 // Alert text should be plain ascii coming from a trusted source, but to
1180 // be safe we first strip anything not in safeChars, then add single quotes around
1181 // the whole string before passing it to the shell:
1182 std::string singleQuote("'");
1183 std::string safeStatus = SanitizeString(strMessage);
1184 safeStatus = singleQuote+safeStatus+singleQuote;
1185 boost::replace_all(strCmd, "%s", safeStatus);
1187 boost::thread t(runCommand, strCmd); // thread runs free
1190 static void CheckForkWarningConditions()
1192 AssertLockHeld(cs_main);
1193 // Before we get past initial download, we cannot reliably alert about forks
1194 // (we assume we don't get stuck on a fork before finishing our initial sync)
1195 if (IsInitialBlockDownload())
1196 return;
1198 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1199 // of our head, drop it
1200 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1201 pindexBestForkTip = nullptr;
1203 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1205 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1207 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1208 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1209 AlertNotify(warning);
1211 if (pindexBestForkTip && pindexBestForkBase)
1213 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__,
1214 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1215 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1216 SetfLargeWorkForkFound(true);
1218 else
1220 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1221 SetfLargeWorkInvalidChainFound(true);
1224 else
1226 SetfLargeWorkForkFound(false);
1227 SetfLargeWorkInvalidChainFound(false);
1231 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1233 AssertLockHeld(cs_main);
1234 // If we are on a fork that is sufficiently large, set a warning flag
1235 CBlockIndex* pfork = pindexNewForkTip;
1236 CBlockIndex* plonger = chainActive.Tip();
1237 while (pfork && pfork != plonger)
1239 while (plonger && plonger->nHeight > pfork->nHeight)
1240 plonger = plonger->pprev;
1241 if (pfork == plonger)
1242 break;
1243 pfork = pfork->pprev;
1246 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1247 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1248 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1249 // hash rate operating on the fork.
1250 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1251 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1252 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1253 if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1254 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1255 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1257 pindexBestForkTip = pindexNewForkTip;
1258 pindexBestForkBase = pfork;
1261 CheckForkWarningConditions();
1264 void static InvalidChainFound(CBlockIndex* pindexNew)
1266 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1267 pindexBestInvalid = pindexNew;
1269 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1270 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1271 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1272 pindexNew->GetBlockTime()));
1273 CBlockIndex *tip = chainActive.Tip();
1274 assert (tip);
1275 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1276 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1277 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1278 CheckForkWarningConditions();
1281 void CChainState::InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1282 if (!state.CorruptionPossible()) {
1283 pindex->nStatus |= BLOCK_FAILED_VALID;
1284 g_failed_blocks.insert(pindex);
1285 setDirtyBlockIndex.insert(pindex);
1286 setBlockIndexCandidates.erase(pindex);
1287 InvalidChainFound(pindex);
1291 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1293 // mark inputs spent
1294 if (!tx.IsCoinBase()) {
1295 txundo.vprevout.reserve(tx.vin.size());
1296 for (const CTxIn &txin : tx.vin) {
1297 txundo.vprevout.emplace_back();
1298 bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1299 assert(is_spent);
1302 // add outputs
1303 AddCoins(inputs, tx, nHeight);
1306 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1308 CTxUndo txundo;
1309 UpdateCoins(tx, inputs, txundo, nHeight);
1312 bool CScriptCheck::operator()() {
1313 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1314 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1315 return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
1318 int GetSpendHeight(const CCoinsViewCache& inputs)
1320 LOCK(cs_main);
1321 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1322 return pindexPrev->nHeight + 1;
1326 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1327 static uint256 scriptExecutionCacheNonce(GetRandHash());
1329 void InitScriptExecutionCache() {
1330 // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1331 // setup_bytes creates the minimum possible cache (2 elements).
1332 size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1333 size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1334 LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1335 (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1339 * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
1340 * This does not modify the UTXO set.
1342 * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
1343 * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
1344 * not pushed onto pvChecks/run.
1346 * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
1347 * which are matched. This is useful for checking blocks where we will likely never need the cache
1348 * entry again.
1350 * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
1352 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1354 if (!tx.IsCoinBase())
1356 if (pvChecks)
1357 pvChecks->reserve(tx.vin.size());
1359 // The first loop above does all the inexpensive checks.
1360 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1361 // Helps prevent CPU exhaustion attacks.
1363 // Skip script verification when connecting blocks under the
1364 // assumevalid block. Assuming the assumevalid block is valid this
1365 // is safe because block merkle hashes are still computed and checked,
1366 // Of course, if an assumed valid block is invalid due to false scriptSigs
1367 // this optimization would allow an invalid chain to be accepted.
1368 if (fScriptChecks) {
1369 // First check if script executions have been cached with the same
1370 // flags. Note that this assumes that the inputs provided are
1371 // correct (ie that the transaction hash which is in tx's prevouts
1372 // properly commits to the scriptPubKey in the inputs view of that
1373 // transaction).
1374 uint256 hashCacheEntry;
1375 // We only use the first 19 bytes of nonce to avoid a second SHA
1376 // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1377 static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1378 CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1379 AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1380 if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1381 return true;
1384 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1385 const COutPoint &prevout = tx.vin[i].prevout;
1386 const Coin& coin = inputs.AccessCoin(prevout);
1387 assert(!coin.IsSpent());
1389 // We very carefully only pass in things to CScriptCheck which
1390 // are clearly committed to by tx' witness hash. This provides
1391 // a sanity check that our caching is not introducing consensus
1392 // failures through additional data in, eg, the coins being
1393 // spent being checked as a part of CScriptCheck.
1395 // Verify signature
1396 CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1397 if (pvChecks) {
1398 pvChecks->push_back(CScriptCheck());
1399 check.swap(pvChecks->back());
1400 } else if (!check()) {
1401 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1402 // Check whether the failure was caused by a
1403 // non-mandatory script verification check, such as
1404 // non-standard DER encodings or non-null dummy
1405 // arguments; if so, don't trigger DoS protection to
1406 // avoid splitting the network between upgraded and
1407 // non-upgraded nodes.
1408 CScriptCheck check2(coin.out, tx, i,
1409 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1410 if (check2())
1411 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1413 // Failures of other flags indicate a transaction that is
1414 // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1415 // such nodes as they are not following the protocol. That
1416 // said during an upgrade careful thought should be taken
1417 // as to the correct behavior - we may want to continue
1418 // peering with non-upgraded nodes even after soft-fork
1419 // super-majority signaling has occurred.
1420 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1424 if (cacheFullScriptStore && !pvChecks) {
1425 // We executed all of the provided scripts, and were told to
1426 // cache the result. Do so now.
1427 scriptExecutionCache.insert(hashCacheEntry);
1432 return true;
1435 namespace {
1437 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1439 // Open history file to append
1440 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1441 if (fileout.IsNull())
1442 return error("%s: OpenUndoFile failed", __func__);
1444 // Write index header
1445 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1446 fileout << FLATDATA(messageStart) << nSize;
1448 // Write undo data
1449 long fileOutPos = ftell(fileout.Get());
1450 if (fileOutPos < 0)
1451 return error("%s: ftell failed", __func__);
1452 pos.nPos = (unsigned int)fileOutPos;
1453 fileout << blockundo;
1455 // calculate & write checksum
1456 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1457 hasher << hashBlock;
1458 hasher << blockundo;
1459 fileout << hasher.GetHash();
1461 return true;
1464 static bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
1466 CDiskBlockPos pos = pindex->GetUndoPos();
1467 if (pos.IsNull()) {
1468 return error("%s: no undo data available", __func__);
1471 // Open history file to read
1472 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1473 if (filein.IsNull())
1474 return error("%s: OpenUndoFile failed", __func__);
1476 // Read block
1477 uint256 hashChecksum;
1478 CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1479 try {
1480 verifier << pindex->pprev->GetBlockHash();
1481 verifier >> blockundo;
1482 filein >> hashChecksum;
1484 catch (const std::exception& e) {
1485 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1488 // Verify checksum
1489 if (hashChecksum != verifier.GetHash())
1490 return error("%s: Checksum mismatch", __func__);
1492 return true;
1495 /** Abort with a message */
1496 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1498 SetMiscWarning(strMessage);
1499 LogPrintf("*** %s\n", strMessage);
1500 uiInterface.ThreadSafeMessageBox(
1501 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1502 "", CClientUIInterface::MSG_ERROR);
1503 StartShutdown();
1504 return false;
1507 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1509 AbortNode(strMessage, userMessage);
1510 return state.Error(strMessage);
1513 } // namespace
1516 * Restore the UTXO in a Coin at a given COutPoint
1517 * @param undo The Coin to be restored.
1518 * @param view The coins view to which to apply the changes.
1519 * @param out The out point that corresponds to the tx input.
1520 * @return A DisconnectResult as an int
1522 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1524 bool fClean = true;
1526 if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1528 if (undo.nHeight == 0) {
1529 // Missing undo metadata (height and coinbase). Older versions included this
1530 // information only in undo records for the last spend of a transactions'
1531 // outputs. This implies that it must be present for some other output of the same tx.
1532 const Coin& alternate = AccessByTxid(view, out.hash);
1533 if (!alternate.IsSpent()) {
1534 undo.nHeight = alternate.nHeight;
1535 undo.fCoinBase = alternate.fCoinBase;
1536 } else {
1537 return DISCONNECT_FAILED; // adding output for transaction without known metadata
1540 // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1541 // sure that the coin did not already exist in the cache. As we have queried for that above
1542 // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1543 // it is an overwrite.
1544 view.AddCoin(out, std::move(undo), !fClean);
1546 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1549 /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
1550 * When FAILED is returned, view is left in an indeterminate state. */
1551 DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
1553 bool fClean = true;
1555 CBlockUndo blockUndo;
1556 if (!UndoReadFromDisk(blockUndo, pindex)) {
1557 error("DisconnectBlock(): failure reading undo data");
1558 return DISCONNECT_FAILED;
1561 if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1562 error("DisconnectBlock(): block and undo data inconsistent");
1563 return DISCONNECT_FAILED;
1566 // undo transactions in reverse order
1567 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1568 const CTransaction &tx = *(block.vtx[i]);
1569 uint256 hash = tx.GetHash();
1570 bool is_coinbase = tx.IsCoinBase();
1572 // Check that all outputs are available and match the outputs in the block itself
1573 // exactly.
1574 for (size_t o = 0; o < tx.vout.size(); o++) {
1575 if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1576 COutPoint out(hash, o);
1577 Coin coin;
1578 bool is_spent = view.SpendCoin(out, &coin);
1579 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1580 fClean = false; // transaction output mismatch
1585 // restore inputs
1586 if (i > 0) { // not coinbases
1587 CTxUndo &txundo = blockUndo.vtxundo[i-1];
1588 if (txundo.vprevout.size() != tx.vin.size()) {
1589 error("DisconnectBlock(): transaction and undo data inconsistent");
1590 return DISCONNECT_FAILED;
1592 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1593 const COutPoint &out = tx.vin[j].prevout;
1594 int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1595 if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1596 fClean = fClean && res != DISCONNECT_UNCLEAN;
1598 // At this point, all of txundo.vprevout should have been moved out.
1602 // move best block pointer to prevout block
1603 view.SetBestBlock(pindex->pprev->GetBlockHash());
1605 return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1608 void static FlushBlockFile(bool fFinalize = false)
1610 LOCK(cs_LastBlockFile);
1612 CDiskBlockPos posOld(nLastBlockFile, 0);
1614 FILE *fileOld = OpenBlockFile(posOld);
1615 if (fileOld) {
1616 if (fFinalize)
1617 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1618 FileCommit(fileOld);
1619 fclose(fileOld);
1622 fileOld = OpenUndoFile(posOld);
1623 if (fileOld) {
1624 if (fFinalize)
1625 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1626 FileCommit(fileOld);
1627 fclose(fileOld);
1631 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1633 static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, CValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
1635 // Write undo information to disk
1636 if (pindex->GetUndoPos().IsNull()) {
1637 CDiskBlockPos _pos;
1638 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1639 return error("ConnectBlock(): FindUndoPos failed");
1640 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1641 return AbortNode(state, "Failed to write undo data");
1643 // update nUndoPos in block index
1644 pindex->nUndoPos = _pos.nPos;
1645 pindex->nStatus |= BLOCK_HAVE_UNDO;
1646 setDirtyBlockIndex.insert(pindex);
1649 return true;
1652 static bool WriteTxIndexDataForBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex)
1654 if (!fTxIndex) return true;
1656 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1657 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1658 vPos.reserve(block.vtx.size());
1659 for (const CTransactionRef& tx : block.vtx)
1661 vPos.push_back(std::make_pair(tx->GetHash(), pos));
1662 pos.nTxOffset += ::GetSerializeSize(*tx, SER_DISK, CLIENT_VERSION);
1665 if (!pblocktree->WriteTxIndex(vPos)) {
1666 return AbortNode(state, "Failed to write transaction index");
1669 return true;
1672 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1674 void ThreadScriptCheck() {
1675 RenameThread("bitcoin-scriptch");
1676 scriptcheckqueue.Thread();
1679 // Protected by cs_main
1680 VersionBitsCache versionbitscache;
1682 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1684 LOCK(cs_main);
1685 int32_t nVersion = VERSIONBITS_TOP_BITS;
1687 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1688 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1689 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1690 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1694 return nVersion;
1698 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1700 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1702 private:
1703 int bit;
1705 public:
1706 explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1708 int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1709 int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1710 int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1711 int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1713 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1715 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1716 ((pindex->nVersion >> bit) & 1) != 0 &&
1717 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1721 // Protected by cs_main
1722 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1724 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1725 AssertLockHeld(cs_main);
1727 unsigned int flags = SCRIPT_VERIFY_NONE;
1729 // Start enforcing P2SH (BIP16)
1730 if (pindex->nHeight >= consensusparams.BIP16Height) {
1731 flags |= SCRIPT_VERIFY_P2SH;
1734 // Start enforcing the DERSIG (BIP66) rule
1735 if (pindex->nHeight >= consensusparams.BIP66Height) {
1736 flags |= SCRIPT_VERIFY_DERSIG;
1739 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1740 if (pindex->nHeight >= consensusparams.BIP65Height) {
1741 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1744 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1745 if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1746 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1749 // Start enforcing WITNESS rules using versionbits logic.
1750 if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1751 flags |= SCRIPT_VERIFY_WITNESS;
1752 flags |= SCRIPT_VERIFY_NULLDUMMY;
1755 return flags;
1760 static int64_t nTimeCheck = 0;
1761 static int64_t nTimeForks = 0;
1762 static int64_t nTimeVerify = 0;
1763 static int64_t nTimeConnect = 0;
1764 static int64_t nTimeIndex = 0;
1765 static int64_t nTimeCallbacks = 0;
1766 static int64_t nTimeTotal = 0;
1767 static int64_t nBlocksTotal = 0;
1769 /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
1770 * Validity checks that depend on the UTXO set are also done; ConnectBlock()
1771 * can fail if those validity checks fail (among other reasons). */
1772 bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1773 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1775 AssertLockHeld(cs_main);
1776 assert(pindex);
1777 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1778 assert((pindex->phashBlock == nullptr) ||
1779 (*pindex->phashBlock == block.GetHash()));
1780 int64_t nTimeStart = GetTimeMicros();
1782 // Check it again in case a previous version let a bad block in
1783 // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1784 // ContextualCheckBlockHeader() here. This means that if we add a new
1785 // consensus rule that is enforced in one of those two functions, then we
1786 // may have let in a block that violates the rule prior to updating the
1787 // software, and we would NOT be enforcing the rule here. Fully solving
1788 // upgrade from one software version to the next after a consensus rule
1789 // change is potentially tricky and issue-specific (see RewindBlockIndex()
1790 // for one general approach that was used for BIP 141 deployment).
1791 // Also, currently the rule against blocks more than 2 hours in the future
1792 // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
1793 // re-enforce that rule here (at least until we make it impossible for
1794 // GetAdjustedTime() to go backward).
1795 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1796 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1798 // verify that the view's current state corresponds to the previous block
1799 uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1800 assert(hashPrevBlock == view.GetBestBlock());
1802 // Special case for the genesis block, skipping connection of its transactions
1803 // (its coinbase is unspendable)
1804 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1805 if (!fJustCheck)
1806 view.SetBestBlock(pindex->GetBlockHash());
1807 return true;
1810 nBlocksTotal++;
1812 bool fScriptChecks = true;
1813 if (!hashAssumeValid.IsNull()) {
1814 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1815 // A suitable default value is included with the software and updated from time to time. Because validity
1816 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1817 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1818 // effectively caching the result of part of the verification.
1819 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1820 if (it != mapBlockIndex.end()) {
1821 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1822 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1823 pindexBestHeader->nChainWork >= nMinimumChainWork) {
1824 // This block is a member of the assumed verified chain and an ancestor of the best header.
1825 // The equivalent time check discourages hash power from extorting the network via DOS attack
1826 // into accepting an invalid block through telling users they must manually set assumevalid.
1827 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1828 // it hard to hide the implication of the demand. This also avoids having release candidates
1829 // that are hardly doing any signature verification at all in testing without having to
1830 // artificially set the default assumed verified block further back.
1831 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1832 // least as good as the expected chain.
1833 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1838 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1839 LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
1841 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1842 // unless those are already completely spent.
1843 // If such overwrites are allowed, coinbases and transactions depending upon those
1844 // can be duplicated to remove the ability to spend the first instance -- even after
1845 // being sent to another address.
1846 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1847 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1848 // already refuses previously-known transaction ids entirely.
1849 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1850 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1851 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1852 // initial block download.
1853 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1854 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1855 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1857 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1858 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1859 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1860 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1861 // duplicate transactions descending from the known pairs either.
1862 // 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.
1863 assert(pindex->pprev);
1864 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1865 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1866 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1868 if (fEnforceBIP30) {
1869 for (const auto& tx : block.vtx) {
1870 for (size_t o = 0; o < tx->vout.size(); o++) {
1871 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
1872 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1873 REJECT_INVALID, "bad-txns-BIP30");
1879 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1880 int nLockTimeFlags = 0;
1881 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1882 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1885 // Get the script flags for this block
1886 unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
1888 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1889 LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
1891 CBlockUndo blockundo;
1893 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
1895 std::vector<int> prevheights;
1896 CAmount nFees = 0;
1897 int nInputs = 0;
1898 int64_t nSigOpsCost = 0;
1899 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1900 std::vector<PrecomputedTransactionData> txdata;
1901 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1902 for (unsigned int i = 0; i < block.vtx.size(); i++)
1904 const CTransaction &tx = *(block.vtx[i]);
1906 nInputs += tx.vin.size();
1908 if (!tx.IsCoinBase())
1910 CAmount txfee = 0;
1911 if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
1912 return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
1914 nFees += txfee;
1915 if (!MoneyRange(nFees)) {
1916 return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
1917 REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
1920 // Check that transaction is BIP68 final
1921 // BIP68 lock checks (as opposed to nLockTime checks) must
1922 // be in ConnectBlock because they require the UTXO set
1923 prevheights.resize(tx.vin.size());
1924 for (size_t j = 0; j < tx.vin.size(); j++) {
1925 prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
1928 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1929 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1930 REJECT_INVALID, "bad-txns-nonfinal");
1934 // GetTransactionSigOpCost counts 3 types of sigops:
1935 // * legacy (always)
1936 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1937 // * witness (when witness enabled in flags and excludes coinbase)
1938 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1939 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1940 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1941 REJECT_INVALID, "bad-blk-sigops");
1943 txdata.emplace_back(tx);
1944 if (!tx.IsCoinBase())
1946 std::vector<CScriptCheck> vChecks;
1947 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1948 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
1949 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1950 tx.GetHash().ToString(), FormatStateMessage(state));
1951 control.Add(vChecks);
1954 CTxUndo undoDummy;
1955 if (i > 0) {
1956 blockundo.vtxundo.push_back(CTxUndo());
1958 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1960 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1961 LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
1963 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1964 if (block.vtx[0]->GetValueOut() > blockReward)
1965 return state.DoS(100,
1966 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1967 block.vtx[0]->GetValueOut(), blockReward),
1968 REJECT_INVALID, "bad-cb-amount");
1970 if (!control.Wait())
1971 return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
1972 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1973 LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
1975 if (fJustCheck)
1976 return true;
1978 if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
1979 return false;
1981 if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
1982 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1983 setDirtyBlockIndex.insert(pindex);
1986 if (!WriteTxIndexDataForBlock(block, state, pindex))
1987 return false;
1989 assert(pindex->phashBlock);
1990 // add this block to the view's block chain
1991 view.SetBestBlock(pindex->GetBlockHash());
1993 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1994 LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
1996 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1997 LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
1999 return true;
2003 * Update the on-disk chain state.
2004 * The caches and indexes are flushed depending on the mode we're called with
2005 * if they're too large, if it's been a while since the last write,
2006 * or always and in all cases if we're in prune mode and are deleting files.
2008 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
2009 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
2010 LOCK(cs_main);
2011 static int64_t nLastWrite = 0;
2012 static int64_t nLastFlush = 0;
2013 static int64_t nLastSetChain = 0;
2014 std::set<int> setFilesToPrune;
2015 bool fFlushForPrune = false;
2016 bool fDoFullFlush = false;
2017 int64_t nNow = 0;
2018 try {
2020 LOCK(cs_LastBlockFile);
2021 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2022 if (nManualPruneHeight > 0) {
2023 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
2024 } else {
2025 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
2026 fCheckForPruning = false;
2028 if (!setFilesToPrune.empty()) {
2029 fFlushForPrune = true;
2030 if (!fHavePruned) {
2031 pblocktree->WriteFlag("prunedblockfiles", true);
2032 fHavePruned = true;
2036 nNow = GetTimeMicros();
2037 // Avoid writing/flushing immediately after startup.
2038 if (nLastWrite == 0) {
2039 nLastWrite = nNow;
2041 if (nLastFlush == 0) {
2042 nLastFlush = nNow;
2044 if (nLastSetChain == 0) {
2045 nLastSetChain = nNow;
2047 int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2048 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2049 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2050 // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
2051 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
2052 // The cache is over the limit, we have to write now.
2053 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
2054 // 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.
2055 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2056 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2057 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2058 // Combine all conditions that result in a full cache flush.
2059 fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2060 // Write blocks and block index to disk.
2061 if (fDoFullFlush || fPeriodicWrite) {
2062 // Depend on nMinDiskSpace to ensure we can write block index
2063 if (!CheckDiskSpace(0))
2064 return state.Error("out of disk space");
2065 // First make sure all block and undo data is flushed to disk.
2066 FlushBlockFile();
2067 // Then update all block file information (which may refer to block and undo files).
2069 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2070 vFiles.reserve(setDirtyFileInfo.size());
2071 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2072 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2073 setDirtyFileInfo.erase(it++);
2075 std::vector<const CBlockIndex*> vBlocks;
2076 vBlocks.reserve(setDirtyBlockIndex.size());
2077 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2078 vBlocks.push_back(*it);
2079 setDirtyBlockIndex.erase(it++);
2081 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2082 return AbortNode(state, "Failed to write to block index database");
2085 // Finally remove any pruned files
2086 if (fFlushForPrune)
2087 UnlinkPrunedFiles(setFilesToPrune);
2088 nLastWrite = nNow;
2090 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2091 if (fDoFullFlush) {
2092 // Typical Coin structures on disk are around 48 bytes in size.
2093 // Pushing a new one to the database can cause it to be written
2094 // twice (once in the log, and once in the tables). This is already
2095 // an overestimation, as most will delete an existing entry or
2096 // overwrite one. Still, use a conservative safety factor of 2.
2097 if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
2098 return state.Error("out of disk space");
2099 // Flush the chainstate (which may refer to block index entries).
2100 if (!pcoinsTip->Flush())
2101 return AbortNode(state, "Failed to write to coin database");
2102 nLastFlush = nNow;
2105 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2106 // Update best block in wallet (so we can detect restored wallets).
2107 GetMainSignals().SetBestChain(chainActive.GetLocator());
2108 nLastSetChain = nNow;
2110 } catch (const std::runtime_error& e) {
2111 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2113 return true;
2116 void FlushStateToDisk() {
2117 CValidationState state;
2118 const CChainParams& chainparams = Params();
2119 FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
2122 void PruneAndFlush() {
2123 CValidationState state;
2124 fCheckForPruning = true;
2125 const CChainParams& chainparams = Params();
2126 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2129 static void DoWarning(const std::string& strWarning)
2131 static bool fWarned = false;
2132 SetMiscWarning(strWarning);
2133 if (!fWarned) {
2134 AlertNotify(strWarning);
2135 fWarned = true;
2139 /** Check warning conditions and do some notifications on new chain tip set. */
2140 void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainParams) {
2141 // New best block
2142 mempool.AddTransactionsUpdated(1);
2144 cvBlockChange.notify_all();
2146 std::vector<std::string> warningMessages;
2147 if (!IsInitialBlockDownload())
2149 int nUpgraded = 0;
2150 const CBlockIndex* pindex = pindexNew;
2151 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2152 WarningBitsConditionChecker checker(bit);
2153 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2154 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2155 const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2156 if (state == THRESHOLD_ACTIVE) {
2157 DoWarning(strWarning);
2158 } else {
2159 warningMessages.push_back(strWarning);
2163 // Check the version of the last 100 blocks to see if we need to upgrade:
2164 for (int i = 0; i < 100 && pindex != nullptr; i++)
2166 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2167 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2168 ++nUpgraded;
2169 pindex = pindex->pprev;
2171 if (nUpgraded > 0)
2172 warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2173 if (nUpgraded > 100/2)
2175 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2176 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2177 DoWarning(strWarning);
2180 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2181 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
2182 log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2183 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()),
2184 GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2185 if (!warningMessages.empty())
2186 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2187 LogPrintf("\n");
2191 /** Disconnect chainActive's tip.
2192 * After calling, the mempool will be in an inconsistent state, with
2193 * transactions from disconnected blocks being added to disconnectpool. You
2194 * should make the mempool consistent again by calling UpdateMempoolForReorg.
2195 * with cs_main held.
2197 * If disconnectpool is nullptr, then no disconnected transactions are added to
2198 * disconnectpool (note that the caller is responsible for mempool consistency
2199 * in any case).
2201 bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2203 CBlockIndex *pindexDelete = chainActive.Tip();
2204 assert(pindexDelete);
2205 // Read block from disk.
2206 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2207 CBlock& block = *pblock;
2208 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2209 return AbortNode(state, "Failed to read block");
2210 // Apply the block atomically to the chain state.
2211 int64_t nStart = GetTimeMicros();
2213 CCoinsViewCache view(pcoinsTip.get());
2214 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2215 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2216 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2217 bool flushed = view.Flush();
2218 assert(flushed);
2220 LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2221 // Write the chain state to disk, if necessary.
2222 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2223 return false;
2225 if (disconnectpool) {
2226 // Save transactions to re-add to mempool at end of reorg
2227 for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2228 disconnectpool->addTransaction(*it);
2230 while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2231 // Drop the earliest entry, and remove its children from the mempool.
2232 auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2233 mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
2234 disconnectpool->removeEntry(it);
2238 chainActive.SetTip(pindexDelete->pprev);
2240 UpdateTip(pindexDelete->pprev, chainparams);
2241 // Let wallets know transactions went from 1-confirmed to
2242 // 0-confirmed or conflicted:
2243 GetMainSignals().BlockDisconnected(pblock);
2244 return true;
2247 static int64_t nTimeReadFromDisk = 0;
2248 static int64_t nTimeConnectTotal = 0;
2249 static int64_t nTimeFlush = 0;
2250 static int64_t nTimeChainState = 0;
2251 static int64_t nTimePostConnect = 0;
2253 struct PerBlockConnectTrace {
2254 CBlockIndex* pindex = nullptr;
2255 std::shared_ptr<const CBlock> pblock;
2256 std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2257 PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2260 * Used to track blocks whose transactions were applied to the UTXO state as a
2261 * part of a single ActivateBestChainStep call.
2263 * This class also tracks transactions that are removed from the mempool as
2264 * conflicts (per block) and can be used to pass all those transactions
2265 * through SyncTransaction.
2267 * This class assumes (and asserts) that the conflicted transactions for a given
2268 * block are added via mempool callbacks prior to the BlockConnected() associated
2269 * with those transactions. If any transactions are marked conflicted, it is
2270 * assumed that an associated block will always be added.
2272 * This class is single-use, once you call GetBlocksConnected() you have to throw
2273 * it away and make a new one.
2275 class ConnectTrace {
2276 private:
2277 std::vector<PerBlockConnectTrace> blocksConnected;
2278 CTxMemPool &pool;
2280 public:
2281 explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2282 pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2285 ~ConnectTrace() {
2286 pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2289 void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2290 assert(!blocksConnected.back().pindex);
2291 assert(pindex);
2292 assert(pblock);
2293 blocksConnected.back().pindex = pindex;
2294 blocksConnected.back().pblock = std::move(pblock);
2295 blocksConnected.emplace_back();
2298 std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2299 // We always keep one extra block at the end of our list because
2300 // blocks are added after all the conflicted transactions have
2301 // been filled in. Thus, the last entry should always be an empty
2302 // one waiting for the transactions from the next block. We pop
2303 // the last entry here to make sure the list we return is sane.
2304 assert(!blocksConnected.back().pindex);
2305 assert(blocksConnected.back().conflictedTxs->empty());
2306 blocksConnected.pop_back();
2307 return blocksConnected;
2310 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
2311 assert(!blocksConnected.back().pindex);
2312 if (reason == MemPoolRemovalReason::CONFLICT) {
2313 blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2319 * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
2320 * corresponding to pindexNew, to bypass loading it again from disk.
2322 * The block is added to connectTrace if connection succeeds.
2324 bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2326 assert(pindexNew->pprev == chainActive.Tip());
2327 // Read block from disk.
2328 int64_t nTime1 = GetTimeMicros();
2329 std::shared_ptr<const CBlock> pthisBlock;
2330 if (!pblock) {
2331 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2332 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2333 return AbortNode(state, "Failed to read block");
2334 pthisBlock = pblockNew;
2335 } else {
2336 pthisBlock = pblock;
2338 const CBlock& blockConnecting = *pthisBlock;
2339 // Apply the block atomically to the chain state.
2340 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2341 int64_t nTime3;
2342 LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2344 CCoinsViewCache view(pcoinsTip.get());
2345 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2346 GetMainSignals().BlockChecked(blockConnecting, state);
2347 if (!rv) {
2348 if (state.IsInvalid())
2349 InvalidBlockFound(pindexNew, state);
2350 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2352 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2353 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2354 bool flushed = view.Flush();
2355 assert(flushed);
2357 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2358 LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2359 // Write the chain state to disk, if necessary.
2360 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2361 return false;
2362 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2363 LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2364 // Remove conflicting transactions from the mempool.;
2365 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2366 disconnectpool.removeForBlock(blockConnecting.vtx);
2367 // Update chainActive & related variables.
2368 chainActive.SetTip(pindexNew);
2369 UpdateTip(pindexNew, chainparams);
2371 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2372 LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2373 LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2375 connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2376 return true;
2380 * Return the tip of the chain with the most work in it, that isn't
2381 * known to be invalid (it's however far from certain to be valid).
2383 CBlockIndex* CChainState::FindMostWorkChain() {
2384 do {
2385 CBlockIndex *pindexNew = nullptr;
2387 // Find the best candidate header.
2389 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2390 if (it == setBlockIndexCandidates.rend())
2391 return nullptr;
2392 pindexNew = *it;
2395 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2396 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2397 CBlockIndex *pindexTest = pindexNew;
2398 bool fInvalidAncestor = false;
2399 while (pindexTest && !chainActive.Contains(pindexTest)) {
2400 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2402 // Pruned nodes may have entries in setBlockIndexCandidates for
2403 // which block files have been deleted. Remove those as candidates
2404 // for the most work chain if we come across them; we can't switch
2405 // to a chain unless we have all the non-active-chain parent blocks.
2406 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2407 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2408 if (fFailedChain || fMissingData) {
2409 // Candidate chain is not usable (either invalid or missing data)
2410 if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2411 pindexBestInvalid = pindexNew;
2412 CBlockIndex *pindexFailed = pindexNew;
2413 // Remove the entire chain from the set.
2414 while (pindexTest != pindexFailed) {
2415 if (fFailedChain) {
2416 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2417 } else if (fMissingData) {
2418 // If we're missing data, then add back to mapBlocksUnlinked,
2419 // so that if the block arrives in the future we can try adding
2420 // to setBlockIndexCandidates again.
2421 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2423 setBlockIndexCandidates.erase(pindexFailed);
2424 pindexFailed = pindexFailed->pprev;
2426 setBlockIndexCandidates.erase(pindexTest);
2427 fInvalidAncestor = true;
2428 break;
2430 pindexTest = pindexTest->pprev;
2432 if (!fInvalidAncestor)
2433 return pindexNew;
2434 } while(true);
2437 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2438 void CChainState::PruneBlockIndexCandidates() {
2439 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2440 // reorganization to a better block fails.
2441 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2442 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2443 setBlockIndexCandidates.erase(it++);
2445 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2446 assert(!setBlockIndexCandidates.empty());
2450 * Try to make some progress towards making pindexMostWork the active block.
2451 * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
2453 bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2455 AssertLockHeld(cs_main);
2456 const CBlockIndex *pindexOldTip = chainActive.Tip();
2457 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2459 // Disconnect active blocks which are no longer in the best chain.
2460 bool fBlocksDisconnected = false;
2461 DisconnectedBlockTransactions disconnectpool;
2462 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2463 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2464 // This is likely a fatal error, but keep the mempool consistent,
2465 // just in case. Only remove from the mempool in this case.
2466 UpdateMempoolForReorg(disconnectpool, false);
2467 return false;
2469 fBlocksDisconnected = true;
2472 // Build list of new blocks to connect.
2473 std::vector<CBlockIndex*> vpindexToConnect;
2474 bool fContinue = true;
2475 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2476 while (fContinue && nHeight != pindexMostWork->nHeight) {
2477 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2478 // a few blocks along the way.
2479 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2480 vpindexToConnect.clear();
2481 vpindexToConnect.reserve(nTargetHeight - nHeight);
2482 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2483 while (pindexIter && pindexIter->nHeight != nHeight) {
2484 vpindexToConnect.push_back(pindexIter);
2485 pindexIter = pindexIter->pprev;
2487 nHeight = nTargetHeight;
2489 // Connect new blocks.
2490 for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2491 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2492 if (state.IsInvalid()) {
2493 // The block violates a consensus rule.
2494 if (!state.CorruptionPossible())
2495 InvalidChainFound(vpindexToConnect.back());
2496 state = CValidationState();
2497 fInvalidFound = true;
2498 fContinue = false;
2499 break;
2500 } else {
2501 // A system error occurred (disk space, database error, ...).
2502 // Make the mempool consistent with the current tip, just in case
2503 // any observers try to use it before shutdown.
2504 UpdateMempoolForReorg(disconnectpool, false);
2505 return false;
2507 } else {
2508 PruneBlockIndexCandidates();
2509 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2510 // We're in a better position than we were. Return temporarily to release the lock.
2511 fContinue = false;
2512 break;
2518 if (fBlocksDisconnected) {
2519 // If any blocks were disconnected, disconnectpool may be non empty. Add
2520 // any disconnected transactions back to the mempool.
2521 UpdateMempoolForReorg(disconnectpool, true);
2523 mempool.check(pcoinsTip.get());
2525 // Callbacks/notifications for a new best chain.
2526 if (fInvalidFound)
2527 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2528 else
2529 CheckForkWarningConditions();
2531 return true;
2534 static void NotifyHeaderTip() {
2535 bool fNotify = false;
2536 bool fInitialBlockDownload = false;
2537 static CBlockIndex* pindexHeaderOld = nullptr;
2538 CBlockIndex* pindexHeader = nullptr;
2540 LOCK(cs_main);
2541 pindexHeader = pindexBestHeader;
2543 if (pindexHeader != pindexHeaderOld) {
2544 fNotify = true;
2545 fInitialBlockDownload = IsInitialBlockDownload();
2546 pindexHeaderOld = pindexHeader;
2549 // Send block tip changed notifications without cs_main
2550 if (fNotify) {
2551 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2556 * Make the best chain active, in multiple steps. The result is either failure
2557 * or an activated best chain. pblock is either nullptr or a pointer to a block
2558 * that is already loaded (to avoid loading it again from disk).
2560 bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2561 // Note that while we're often called here from ProcessNewBlock, this is
2562 // far from a guarantee. Things in the P2P/RPC will often end up calling
2563 // us in the middle of ProcessNewBlock - do not assume pblock is set
2564 // sanely for performance or correctness!
2566 CBlockIndex *pindexMostWork = nullptr;
2567 CBlockIndex *pindexNewTip = nullptr;
2568 int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2569 do {
2570 boost::this_thread::interruption_point();
2571 if (ShutdownRequested())
2572 break;
2574 const CBlockIndex *pindexFork;
2575 bool fInitialDownload;
2577 LOCK(cs_main);
2578 ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
2580 CBlockIndex *pindexOldTip = chainActive.Tip();
2581 if (pindexMostWork == nullptr) {
2582 pindexMostWork = FindMostWorkChain();
2585 // Whether we have anything to do at all.
2586 if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
2587 return true;
2589 bool fInvalidFound = false;
2590 std::shared_ptr<const CBlock> nullBlockPtr;
2591 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2592 return false;
2594 if (fInvalidFound) {
2595 // Wipe cache, we may need another branch now.
2596 pindexMostWork = nullptr;
2598 pindexNewTip = chainActive.Tip();
2599 pindexFork = chainActive.FindFork(pindexOldTip);
2600 fInitialDownload = IsInitialBlockDownload();
2602 for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
2603 assert(trace.pblock && trace.pindex);
2604 GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
2607 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2609 // Notifications/callbacks that can run without cs_main
2611 // Notify external listeners about the new tip.
2612 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2614 // Always notify the UI if a new block tip was connected
2615 if (pindexFork != pindexNewTip) {
2616 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2619 if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
2620 } while (pindexNewTip != pindexMostWork);
2621 CheckBlockIndex(chainparams.GetConsensus());
2623 // Write changes periodically to disk, after relay.
2624 if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
2625 return false;
2628 return true;
2630 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2631 return g_chainstate.ActivateBestChain(state, chainparams, std::move(pblock));
2634 bool CChainState::PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2637 LOCK(cs_main);
2638 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2639 // Nothing to do, this block is not at the tip.
2640 return true;
2642 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2643 // The chain has been extended since the last call, reset the counter.
2644 nBlockReverseSequenceId = -1;
2646 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2647 setBlockIndexCandidates.erase(pindex);
2648 pindex->nSequenceId = nBlockReverseSequenceId;
2649 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2650 // We can't keep reducing the counter if somebody really wants to
2651 // call preciousblock 2**31-1 times on the same set of tips...
2652 nBlockReverseSequenceId--;
2654 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2655 setBlockIndexCandidates.insert(pindex);
2656 PruneBlockIndexCandidates();
2660 return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
2662 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
2663 return g_chainstate.PreciousBlock(state, params, pindex);
2666 bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2668 AssertLockHeld(cs_main);
2670 // We first disconnect backwards and then mark the blocks as invalid.
2671 // This prevents a case where pruned nodes may fail to invalidateblock
2672 // and be left unable to start as they have no tip candidates (as there
2673 // are no blocks that meet the "have data and are not invalid per
2674 // nStatus" criteria for inclusion in setBlockIndexCandidates).
2676 bool pindex_was_in_chain = false;
2677 CBlockIndex *invalid_walk_tip = chainActive.Tip();
2679 DisconnectedBlockTransactions disconnectpool;
2680 while (chainActive.Contains(pindex)) {
2681 pindex_was_in_chain = true;
2682 // ActivateBestChain considers blocks already in chainActive
2683 // unconditionally valid already, so force disconnect away from it.
2684 if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2685 // It's probably hopeless to try to make the mempool consistent
2686 // here if DisconnectTip failed, but we can try.
2687 UpdateMempoolForReorg(disconnectpool, false);
2688 return false;
2692 // Now mark the blocks we just disconnected as descendants invalid
2693 // (note this may not be all descendants).
2694 while (pindex_was_in_chain && invalid_walk_tip != pindex) {
2695 invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
2696 setDirtyBlockIndex.insert(invalid_walk_tip);
2697 setBlockIndexCandidates.erase(invalid_walk_tip);
2698 invalid_walk_tip = invalid_walk_tip->pprev;
2701 // Mark the block itself as invalid.
2702 pindex->nStatus |= BLOCK_FAILED_VALID;
2703 setDirtyBlockIndex.insert(pindex);
2704 setBlockIndexCandidates.erase(pindex);
2705 g_failed_blocks.insert(pindex);
2707 // DisconnectTip will add transactions to disconnectpool; try to add these
2708 // back to the mempool.
2709 UpdateMempoolForReorg(disconnectpool, true);
2711 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2712 // add it again.
2713 BlockMap::iterator it = mapBlockIndex.begin();
2714 while (it != mapBlockIndex.end()) {
2715 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2716 setBlockIndexCandidates.insert(it->second);
2718 it++;
2721 InvalidChainFound(pindex);
2722 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2723 return true;
2725 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
2726 return g_chainstate.InvalidateBlock(state, chainparams, pindex);
2729 bool CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
2730 AssertLockHeld(cs_main);
2732 int nHeight = pindex->nHeight;
2734 // Remove the invalidity flag from this block and all its descendants.
2735 BlockMap::iterator it = mapBlockIndex.begin();
2736 while (it != mapBlockIndex.end()) {
2737 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2738 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2739 setDirtyBlockIndex.insert(it->second);
2740 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2741 setBlockIndexCandidates.insert(it->second);
2743 if (it->second == pindexBestInvalid) {
2744 // Reset invalid block marker if it was pointing to one of those.
2745 pindexBestInvalid = nullptr;
2747 g_failed_blocks.erase(it->second);
2749 it++;
2752 // Remove the invalidity flag from all ancestors too.
2753 while (pindex != nullptr) {
2754 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2755 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2756 setDirtyBlockIndex.insert(pindex);
2758 pindex = pindex->pprev;
2760 return true;
2762 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2763 return g_chainstate.ResetBlockFailureFlags(pindex);
2766 CBlockIndex* CChainState::AddToBlockIndex(const CBlockHeader& block)
2768 // Check for duplicate
2769 uint256 hash = block.GetHash();
2770 BlockMap::iterator it = mapBlockIndex.find(hash);
2771 if (it != mapBlockIndex.end())
2772 return it->second;
2774 // Construct new block index object
2775 CBlockIndex* pindexNew = new CBlockIndex(block);
2776 // We assign the sequence id to blocks only when the full data is available,
2777 // to avoid miners withholding blocks but broadcasting headers, to get a
2778 // competitive advantage.
2779 pindexNew->nSequenceId = 0;
2780 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2781 pindexNew->phashBlock = &((*mi).first);
2782 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2783 if (miPrev != mapBlockIndex.end())
2785 pindexNew->pprev = (*miPrev).second;
2786 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2787 pindexNew->BuildSkip();
2789 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2790 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2791 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2792 if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2793 pindexBestHeader = pindexNew;
2795 setDirtyBlockIndex.insert(pindexNew);
2797 return pindexNew;
2800 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2801 bool CChainState::ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
2803 pindexNew->nTx = block.vtx.size();
2804 pindexNew->nChainTx = 0;
2805 pindexNew->nFile = pos.nFile;
2806 pindexNew->nDataPos = pos.nPos;
2807 pindexNew->nUndoPos = 0;
2808 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2809 if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
2810 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2812 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2813 setDirtyBlockIndex.insert(pindexNew);
2815 if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
2816 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2817 std::deque<CBlockIndex*> queue;
2818 queue.push_back(pindexNew);
2820 // Recursively process any descendant blocks that now may be eligible to be connected.
2821 while (!queue.empty()) {
2822 CBlockIndex *pindex = queue.front();
2823 queue.pop_front();
2824 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2826 LOCK(cs_nBlockSequenceId);
2827 pindex->nSequenceId = nBlockSequenceId++;
2829 if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2830 setBlockIndexCandidates.insert(pindex);
2832 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2833 while (range.first != range.second) {
2834 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2835 queue.push_back(it->second);
2836 range.first++;
2837 mapBlocksUnlinked.erase(it);
2840 } else {
2841 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2842 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2846 return true;
2849 static bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2851 LOCK(cs_LastBlockFile);
2853 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2854 if (vinfoBlockFile.size() <= nFile) {
2855 vinfoBlockFile.resize(nFile + 1);
2858 if (!fKnown) {
2859 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2860 nFile++;
2861 if (vinfoBlockFile.size() <= nFile) {
2862 vinfoBlockFile.resize(nFile + 1);
2865 pos.nFile = nFile;
2866 pos.nPos = vinfoBlockFile[nFile].nSize;
2869 if ((int)nFile != nLastBlockFile) {
2870 if (!fKnown) {
2871 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2873 FlushBlockFile(!fKnown);
2874 nLastBlockFile = nFile;
2877 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2878 if (fKnown)
2879 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2880 else
2881 vinfoBlockFile[nFile].nSize += nAddSize;
2883 if (!fKnown) {
2884 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2885 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2886 if (nNewChunks > nOldChunks) {
2887 if (fPruneMode)
2888 fCheckForPruning = true;
2889 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2890 FILE *file = OpenBlockFile(pos);
2891 if (file) {
2892 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2893 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2894 fclose(file);
2897 else
2898 return error("out of disk space");
2902 setDirtyFileInfo.insert(nFile);
2903 return true;
2906 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2908 pos.nFile = nFile;
2910 LOCK(cs_LastBlockFile);
2912 unsigned int nNewSize;
2913 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2914 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2915 setDirtyFileInfo.insert(nFile);
2917 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2918 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2919 if (nNewChunks > nOldChunks) {
2920 if (fPruneMode)
2921 fCheckForPruning = true;
2922 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2923 FILE *file = OpenUndoFile(pos);
2924 if (file) {
2925 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2926 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2927 fclose(file);
2930 else
2931 return state.Error("out of disk space");
2934 return true;
2937 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
2939 // Check proof of work matches claimed amount
2940 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2941 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2943 return true;
2946 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2948 // These are checks that are independent of context.
2950 if (block.fChecked)
2951 return true;
2953 // Check that the header is valid (particularly PoW). This is mostly
2954 // redundant with the call in AcceptBlockHeader.
2955 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2956 return false;
2958 // Check the merkle root.
2959 if (fCheckMerkleRoot) {
2960 bool mutated;
2961 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2962 if (block.hashMerkleRoot != hashMerkleRoot2)
2963 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2965 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2966 // of transactions in a block without affecting the merkle root of a block,
2967 // while still invalidating it.
2968 if (mutated)
2969 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2972 // All potential-corruption validation must be done before we do any
2973 // transaction validation, as otherwise we may mark the header as invalid
2974 // because we receive the wrong transactions for it.
2975 // Note that witness malleability is checked in ContextualCheckBlock, so no
2976 // checks that use witness data may be performed here.
2978 // Size limits
2979 if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
2980 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2982 // First transaction must be coinbase, the rest must not be
2983 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2984 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2985 for (unsigned int i = 1; i < block.vtx.size(); i++)
2986 if (block.vtx[i]->IsCoinBase())
2987 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2989 // Check transactions
2990 for (const auto& tx : block.vtx)
2991 if (!CheckTransaction(*tx, state, false))
2992 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2993 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2995 unsigned int nSigOps = 0;
2996 for (const auto& tx : block.vtx)
2998 nSigOps += GetLegacySigOpCount(*tx);
3000 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
3001 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3003 if (fCheckPOW && fCheckMerkleRoot)
3004 block.fChecked = true;
3006 return true;
3009 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
3011 LOCK(cs_main);
3012 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
3015 // Compute at which vout of the block's coinbase transaction the witness
3016 // commitment occurs, or -1 if not found.
3017 static int GetWitnessCommitmentIndex(const CBlock& block)
3019 int commitpos = -1;
3020 if (!block.vtx.empty()) {
3021 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
3022 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) {
3023 commitpos = o;
3027 return commitpos;
3030 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3032 int commitpos = GetWitnessCommitmentIndex(block);
3033 static const std::vector<unsigned char> nonce(32, 0x00);
3034 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
3035 CMutableTransaction tx(*block.vtx[0]);
3036 tx.vin[0].scriptWitness.stack.resize(1);
3037 tx.vin[0].scriptWitness.stack[0] = nonce;
3038 block.vtx[0] = MakeTransactionRef(std::move(tx));
3042 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3044 std::vector<unsigned char> commitment;
3045 int commitpos = GetWitnessCommitmentIndex(block);
3046 std::vector<unsigned char> ret(32, 0x00);
3047 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
3048 if (commitpos == -1) {
3049 uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3050 CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
3051 CTxOut out;
3052 out.nValue = 0;
3053 out.scriptPubKey.resize(38);
3054 out.scriptPubKey[0] = OP_RETURN;
3055 out.scriptPubKey[1] = 0x24;
3056 out.scriptPubKey[2] = 0xaa;
3057 out.scriptPubKey[3] = 0x21;
3058 out.scriptPubKey[4] = 0xa9;
3059 out.scriptPubKey[5] = 0xed;
3060 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3061 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3062 CMutableTransaction tx(*block.vtx[0]);
3063 tx.vout.push_back(out);
3064 block.vtx[0] = MakeTransactionRef(std::move(tx));
3067 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3068 return commitment;
3071 /** Context-dependent validity checks.
3072 * By "context", we mean only the previous block headers, but not the UTXO
3073 * set; UTXO-related validity checks are done in ConnectBlock().
3074 * NOTE: This function is not currently invoked by ConnectBlock(), so we
3075 * should consider upgrade issues if we change which consensus rules are
3076 * enforced in this function (eg by adding a new consensus rule). See comment
3077 * in ConnectBlock().
3078 * Note that -reindex-chainstate skips the validation that happens here!
3080 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
3082 assert(pindexPrev != nullptr);
3083 const int nHeight = pindexPrev->nHeight + 1;
3085 // Check proof of work
3086 const Consensus::Params& consensusParams = params.GetConsensus();
3087 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3088 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
3090 // Check against checkpoints
3091 if (fCheckpointsEnabled) {
3092 // Don't accept any forks from the main chain prior to last checkpoint.
3093 // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3094 // MapBlockIndex.
3095 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
3096 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3097 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3100 // Check timestamp against prev
3101 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3102 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
3104 // Check timestamp
3105 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3106 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
3108 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3109 // check for version 2, 3 and 4 upgrades
3110 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
3111 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
3112 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
3113 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
3114 strprintf("rejected nVersion=0x%08x block", block.nVersion));
3116 return true;
3119 /** NOTE: This function is not currently invoked by ConnectBlock(), so we
3120 * should consider upgrade issues if we change which consensus rules are
3121 * enforced in this function (eg by adding a new consensus rule). See comment
3122 * in ConnectBlock().
3123 * Note that -reindex-chainstate skips the validation that happens here!
3125 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3127 const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3129 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3130 int nLockTimeFlags = 0;
3131 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3132 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3135 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3136 ? pindexPrev->GetMedianTimePast()
3137 : block.GetBlockTime();
3139 // Check that all transactions are finalized
3140 for (const auto& tx : block.vtx) {
3141 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3142 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3146 // Enforce rule that the coinbase starts with serialized block height
3147 if (nHeight >= consensusParams.BIP34Height)
3149 CScript expect = CScript() << nHeight;
3150 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3151 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3152 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3156 // Validation for witness commitments.
3157 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3158 // coinbase (where 0x0000....0000 is used instead).
3159 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3160 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3161 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3162 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3163 // multiple, the last one is used.
3164 bool fHaveWitness = false;
3165 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3166 int commitpos = GetWitnessCommitmentIndex(block);
3167 if (commitpos != -1) {
3168 bool malleated = false;
3169 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3170 // The malleation check is ignored; as the transaction tree itself
3171 // already does not permit it, it is impossible to trigger in the
3172 // witness tree.
3173 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3174 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3176 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3177 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3178 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3180 fHaveWitness = true;
3184 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3185 if (!fHaveWitness) {
3186 for (const auto& tx : block.vtx) {
3187 if (tx->HasWitness()) {
3188 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3193 // After the coinbase witness nonce and commitment are verified,
3194 // we can check if the block weight passes (before we've checked the
3195 // coinbase witness, it would be possible for the weight to be too
3196 // large by filling up the coinbase witness, which doesn't change
3197 // the block hash, so we couldn't mark the block as permanently
3198 // failed).
3199 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3200 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3203 return true;
3206 bool CChainState::AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3208 AssertLockHeld(cs_main);
3209 // Check for duplicate
3210 uint256 hash = block.GetHash();
3211 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3212 CBlockIndex *pindex = nullptr;
3213 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3215 if (miSelf != mapBlockIndex.end()) {
3216 // Block header is already known.
3217 pindex = miSelf->second;
3218 if (ppindex)
3219 *ppindex = pindex;
3220 if (pindex->nStatus & BLOCK_FAILED_MASK)
3221 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3222 return true;
3225 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3226 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3228 // Get prev block index
3229 CBlockIndex* pindexPrev = nullptr;
3230 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3231 if (mi == mapBlockIndex.end())
3232 return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3233 pindexPrev = (*mi).second;
3234 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3235 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3236 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3237 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3239 if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3240 for (const CBlockIndex* failedit : g_failed_blocks) {
3241 if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3242 assert(failedit->nStatus & BLOCK_FAILED_VALID);
3243 CBlockIndex* invalid_walk = pindexPrev;
3244 while (invalid_walk != failedit) {
3245 invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3246 setDirtyBlockIndex.insert(invalid_walk);
3247 invalid_walk = invalid_walk->pprev;
3249 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3254 if (pindex == nullptr)
3255 pindex = AddToBlockIndex(block);
3257 if (ppindex)
3258 *ppindex = pindex;
3260 CheckBlockIndex(chainparams.GetConsensus());
3262 return true;
3265 // Exposed wrapper for AcceptBlockHeader
3266 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
3268 if (first_invalid != nullptr) first_invalid->SetNull();
3270 LOCK(cs_main);
3271 for (const CBlockHeader& header : headers) {
3272 CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3273 if (!g_chainstate.AcceptBlockHeader(header, state, chainparams, &pindex)) {
3274 if (first_invalid) *first_invalid = header;
3275 return false;
3277 if (ppindex) {
3278 *ppindex = pindex;
3282 NotifyHeaderTip();
3283 return true;
3286 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3287 static CDiskBlockPos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const CDiskBlockPos* dbp) {
3288 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3289 CDiskBlockPos blockPos;
3290 if (dbp != nullptr)
3291 blockPos = *dbp;
3292 if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
3293 error("%s: FindBlockPos failed", __func__);
3294 return CDiskBlockPos();
3296 if (dbp == nullptr) {
3297 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
3298 AbortNode("Failed to write block");
3299 return CDiskBlockPos();
3302 return blockPos;
3305 /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
3306 bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3308 const CBlock& block = *pblock;
3310 if (fNewBlock) *fNewBlock = false;
3311 AssertLockHeld(cs_main);
3313 CBlockIndex *pindexDummy = nullptr;
3314 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3316 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3317 return false;
3319 // Try to process all requested blocks that we don't have, but only
3320 // process an unrequested block if it's new and has enough work to
3321 // advance our tip, and isn't too many blocks ahead.
3322 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3323 bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
3324 // Blocks that are too out-of-order needlessly limit the effectiveness of
3325 // pruning, because pruning will not delete block files that contain any
3326 // blocks which are too close in height to the tip. Apply this test
3327 // regardless of whether pruning is enabled; it should generally be safe to
3328 // not process unrequested blocks.
3329 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3331 // TODO: Decouple this function from the block download logic by removing fRequested
3332 // This requires some new chain data structure to efficiently look up if a
3333 // block is in a chain leading to a candidate for best tip, despite not
3334 // being such a candidate itself.
3336 // TODO: deal better with return value and error conditions for duplicate
3337 // and unrequested blocks.
3338 if (fAlreadyHave) return true;
3339 if (!fRequested) { // If we didn't ask for it:
3340 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3341 if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3342 if (fTooFarAhead) return true; // Block height is too high
3344 // Protect against DoS attacks from low-work chains.
3345 // If our tip is behind, a peer could try to send us
3346 // low-work blocks on a fake chain that we would never
3347 // request; don't process these.
3348 if (pindex->nChainWork < nMinimumChainWork) return true;
3350 if (fNewBlock) *fNewBlock = true;
3352 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3353 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3354 if (state.IsInvalid() && !state.CorruptionPossible()) {
3355 pindex->nStatus |= BLOCK_FAILED_VALID;
3356 setDirtyBlockIndex.insert(pindex);
3358 return error("%s: %s", __func__, FormatStateMessage(state));
3361 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3362 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3363 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3364 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3366 // Write block to history file
3367 try {
3368 CDiskBlockPos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
3369 if (blockPos.IsNull()) {
3370 state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3371 return false;
3373 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
3374 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3375 } catch (const std::runtime_error& e) {
3376 return AbortNode(state, std::string("System error: ") + e.what());
3379 if (fCheckForPruning)
3380 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3382 CheckBlockIndex(chainparams.GetConsensus());
3384 return true;
3387 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3390 CBlockIndex *pindex = nullptr;
3391 if (fNewBlock) *fNewBlock = false;
3392 CValidationState state;
3393 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3394 // belt-and-suspenders.
3395 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3397 LOCK(cs_main);
3399 if (ret) {
3400 // Store to disk
3401 ret = g_chainstate.AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3403 if (!ret) {
3404 GetMainSignals().BlockChecked(*pblock, state);
3405 return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
3409 NotifyHeaderTip();
3411 CValidationState state; // Only used to report errors, not invalidity - ignore it
3412 if (!g_chainstate.ActivateBestChain(state, chainparams, pblock))
3413 return error("%s: ActivateBestChain failed", __func__);
3415 return true;
3418 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3420 AssertLockHeld(cs_main);
3421 assert(pindexPrev && pindexPrev == chainActive.Tip());
3422 CCoinsViewCache viewNew(pcoinsTip.get());
3423 CBlockIndex indexDummy(block);
3424 indexDummy.pprev = pindexPrev;
3425 indexDummy.nHeight = pindexPrev->nHeight + 1;
3427 // NOTE: CheckBlockHeader is called by CheckBlock
3428 if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3429 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3430 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3431 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3432 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3433 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3434 if (!g_chainstate.ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3435 return false;
3436 assert(state.IsValid());
3438 return true;
3442 * BLOCK PRUNING CODE
3445 /* Calculate the amount of disk space the block & undo files currently use */
3446 uint64_t CalculateCurrentUsage()
3448 LOCK(cs_LastBlockFile);
3450 uint64_t retval = 0;
3451 for (const CBlockFileInfo &file : vinfoBlockFile) {
3452 retval += file.nSize + file.nUndoSize;
3454 return retval;
3457 /* Prune a block file (modify associated database entries)*/
3458 void PruneOneBlockFile(const int fileNumber)
3460 LOCK(cs_LastBlockFile);
3462 for (const auto& entry : mapBlockIndex) {
3463 CBlockIndex* pindex = entry.second;
3464 if (pindex->nFile == fileNumber) {
3465 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3466 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3467 pindex->nFile = 0;
3468 pindex->nDataPos = 0;
3469 pindex->nUndoPos = 0;
3470 setDirtyBlockIndex.insert(pindex);
3472 // Prune from mapBlocksUnlinked -- any block we prune would have
3473 // to be downloaded again in order to consider its chain, at which
3474 // point it would be considered as a candidate for
3475 // mapBlocksUnlinked or setBlockIndexCandidates.
3476 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3477 while (range.first != range.second) {
3478 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3479 range.first++;
3480 if (_it->second == pindex) {
3481 mapBlocksUnlinked.erase(_it);
3487 vinfoBlockFile[fileNumber].SetNull();
3488 setDirtyFileInfo.insert(fileNumber);
3492 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3494 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3495 CDiskBlockPos pos(*it, 0);
3496 fs::remove(GetBlockPosFilename(pos, "blk"));
3497 fs::remove(GetBlockPosFilename(pos, "rev"));
3498 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3502 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3503 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3505 assert(fPruneMode && nManualPruneHeight > 0);
3507 LOCK2(cs_main, cs_LastBlockFile);
3508 if (chainActive.Tip() == nullptr)
3509 return;
3511 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3512 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3513 int count=0;
3514 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3515 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3516 continue;
3517 PruneOneBlockFile(fileNumber);
3518 setFilesToPrune.insert(fileNumber);
3519 count++;
3521 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3524 /* This function is called from the RPC code for pruneblockchain */
3525 void PruneBlockFilesManual(int nManualPruneHeight)
3527 CValidationState state;
3528 const CChainParams& chainparams = Params();
3529 FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3533 * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
3534 * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
3535 * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
3536 * (which in this case means the blockchain must be re-downloaded.)
3538 * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
3539 * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
3540 * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
3541 * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
3542 * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
3543 * A db flag records the fact that at least some block files have been pruned.
3545 * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
3547 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3549 LOCK2(cs_main, cs_LastBlockFile);
3550 if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3551 return;
3553 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3554 return;
3557 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3558 uint64_t nCurrentUsage = CalculateCurrentUsage();
3559 // We don't check to prune until after we've allocated new space for files
3560 // So we should leave a buffer under our target to account for another allocation
3561 // before the next pruning.
3562 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3563 uint64_t nBytesToPrune;
3564 int count=0;
3566 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3567 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3568 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3570 if (vinfoBlockFile[fileNumber].nSize == 0)
3571 continue;
3573 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3574 break;
3576 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3577 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3578 continue;
3580 PruneOneBlockFile(fileNumber);
3581 // Queue up the files for removal
3582 setFilesToPrune.insert(fileNumber);
3583 nCurrentUsage -= nBytesToPrune;
3584 count++;
3588 LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3589 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3590 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3591 nLastBlockWeCanPrune, count);
3594 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3596 uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
3598 // Check for nMinDiskSpace bytes (currently 50MB)
3599 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3600 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3602 return true;
3605 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3607 if (pos.IsNull())
3608 return nullptr;
3609 fs::path path = GetBlockPosFilename(pos, prefix);
3610 fs::create_directories(path.parent_path());
3611 FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+");
3612 if (!file && !fReadOnly)
3613 file = fsbridge::fopen(path, "wb+");
3614 if (!file) {
3615 LogPrintf("Unable to open file %s\n", path.string());
3616 return nullptr;
3618 if (pos.nPos) {
3619 if (fseek(file, pos.nPos, SEEK_SET)) {
3620 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3621 fclose(file);
3622 return nullptr;
3625 return file;
3628 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3629 return OpenDiskFile(pos, "blk", fReadOnly);
3632 /** Open an undo file (rev?????.dat) */
3633 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3634 return OpenDiskFile(pos, "rev", fReadOnly);
3637 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3639 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3642 CBlockIndex * CChainState::InsertBlockIndex(const uint256& hash)
3644 if (hash.IsNull())
3645 return nullptr;
3647 // Return existing
3648 BlockMap::iterator mi = mapBlockIndex.find(hash);
3649 if (mi != mapBlockIndex.end())
3650 return (*mi).second;
3652 // Create new
3653 CBlockIndex* pindexNew = new CBlockIndex();
3654 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3655 pindexNew->phashBlock = &((*mi).first);
3657 return pindexNew;
3660 bool CChainState::LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree)
3662 if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash){ return this->InsertBlockIndex(hash); }))
3663 return false;
3665 boost::this_thread::interruption_point();
3667 // Calculate nChainWork
3668 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3669 vSortedByHeight.reserve(mapBlockIndex.size());
3670 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3672 CBlockIndex* pindex = item.second;
3673 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3675 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3676 for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
3678 CBlockIndex* pindex = item.second;
3679 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3680 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3681 // We can link the chain of blocks for which we've received transactions at some point.
3682 // Pruned nodes may have deleted the block.
3683 if (pindex->nTx > 0) {
3684 if (pindex->pprev) {
3685 if (pindex->pprev->nChainTx) {
3686 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3687 } else {
3688 pindex->nChainTx = 0;
3689 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3691 } else {
3692 pindex->nChainTx = pindex->nTx;
3695 if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
3696 pindex->nStatus |= BLOCK_FAILED_CHILD;
3697 setDirtyBlockIndex.insert(pindex);
3699 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
3700 setBlockIndexCandidates.insert(pindex);
3701 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3702 pindexBestInvalid = pindex;
3703 if (pindex->pprev)
3704 pindex->BuildSkip();
3705 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3706 pindexBestHeader = pindex;
3709 return true;
3712 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3714 if (!g_chainstate.LoadBlockIndex(chainparams.GetConsensus(), *pblocktree))
3715 return false;
3717 // Load block file info
3718 pblocktree->ReadLastBlockFile(nLastBlockFile);
3719 vinfoBlockFile.resize(nLastBlockFile + 1);
3720 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3721 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3722 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3724 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3725 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3726 CBlockFileInfo info;
3727 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3728 vinfoBlockFile.push_back(info);
3729 } else {
3730 break;
3734 // Check presence of blk files
3735 LogPrintf("Checking all blk files are present...\n");
3736 std::set<int> setBlkDataFiles;
3737 for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
3739 CBlockIndex* pindex = item.second;
3740 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3741 setBlkDataFiles.insert(pindex->nFile);
3744 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3746 CDiskBlockPos pos(*it, 0);
3747 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3748 return false;
3752 // Check whether we have ever pruned block & undo files
3753 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3754 if (fHavePruned)
3755 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3757 // Check whether we need to continue reindexing
3758 bool fReindexing = false;
3759 pblocktree->ReadReindexing(fReindexing);
3760 if(fReindexing) fReindex = true;
3762 // Check whether we have a transaction index
3763 pblocktree->ReadFlag("txindex", fTxIndex);
3764 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3766 return true;
3769 bool LoadChainTip(const CChainParams& chainparams)
3771 if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
3773 if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
3774 // In case we just added the genesis block, connect it now, so
3775 // that we always have a chainActive.Tip() when we return.
3776 LogPrintf("%s: Connecting genesis block...\n", __func__);
3777 CValidationState state;
3778 if (!ActivateBestChain(state, chainparams)) {
3779 return false;
3783 // Load pointer to end of best chain
3784 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3785 if (it == mapBlockIndex.end())
3786 return false;
3787 chainActive.SetTip(it->second);
3789 g_chainstate.PruneBlockIndexCandidates();
3791 LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
3792 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3793 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3794 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3795 return true;
3798 CVerifyDB::CVerifyDB()
3800 uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
3803 CVerifyDB::~CVerifyDB()
3805 uiInterface.ShowProgress("", 100, false);
3808 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3810 LOCK(cs_main);
3811 if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
3812 return true;
3814 // Verify blocks in the best chain
3815 if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
3816 nCheckDepth = chainActive.Height();
3817 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3818 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3819 CCoinsViewCache coins(coinsview);
3820 CBlockIndex* pindexState = chainActive.Tip();
3821 CBlockIndex* pindexFailure = nullptr;
3822 int nGoodTransactions = 0;
3823 CValidationState state;
3824 int reportDone = 0;
3825 LogPrintf("[0%%]...");
3826 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3828 boost::this_thread::interruption_point();
3829 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3830 if (reportDone < percentageDone/10) {
3831 // report every 10% step
3832 LogPrintf("[%d%%]...", percentageDone);
3833 reportDone = percentageDone/10;
3835 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
3836 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3837 break;
3838 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3839 // If pruning, only go back as far as we have data.
3840 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3841 break;
3843 CBlock block;
3844 // check level 0: read from disk
3845 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3846 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3847 // check level 1: verify block validity
3848 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3849 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3850 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3851 // check level 2: verify undo validity
3852 if (nCheckLevel >= 2 && pindex) {
3853 CBlockUndo undo;
3854 if (!pindex->GetUndoPos().IsNull()) {
3855 if (!UndoReadFromDisk(undo, pindex)) {
3856 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3860 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3861 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3862 assert(coins.GetBestBlock() == pindex->GetBlockHash());
3863 DisconnectResult res = g_chainstate.DisconnectBlock(block, pindex, coins);
3864 if (res == DISCONNECT_FAILED) {
3865 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3867 pindexState = pindex->pprev;
3868 if (res == DISCONNECT_UNCLEAN) {
3869 nGoodTransactions = 0;
3870 pindexFailure = pindex;
3871 } else {
3872 nGoodTransactions += block.vtx.size();
3875 if (ShutdownRequested())
3876 return true;
3878 if (pindexFailure)
3879 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3881 // check level 4: try reconnecting blocks
3882 if (nCheckLevel >= 4) {
3883 CBlockIndex *pindex = pindexState;
3884 while (pindex != chainActive.Tip()) {
3885 boost::this_thread::interruption_point();
3886 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
3887 pindex = chainActive.Next(pindex);
3888 CBlock block;
3889 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3890 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3891 if (!g_chainstate.ConnectBlock(block, state, pindex, coins, chainparams))
3892 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3896 LogPrintf("[DONE].\n");
3897 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3899 return true;
3902 /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
3903 bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
3905 // TODO: merge with ConnectBlock
3906 CBlock block;
3907 if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
3908 return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3911 for (const CTransactionRef& tx : block.vtx) {
3912 if (!tx->IsCoinBase()) {
3913 for (const CTxIn &txin : tx->vin) {
3914 inputs.SpendCoin(txin.prevout);
3917 // Pass check = true as every addition may be an overwrite.
3918 AddCoins(inputs, *tx, pindex->nHeight, true);
3920 return true;
3923 bool CChainState::ReplayBlocks(const CChainParams& params, CCoinsView* view)
3925 LOCK(cs_main);
3927 CCoinsViewCache cache(view);
3929 std::vector<uint256> hashHeads = view->GetHeadBlocks();
3930 if (hashHeads.empty()) return true; // We're already in a consistent state.
3931 if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
3933 uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
3934 LogPrintf("Replaying blocks\n");
3936 const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
3937 const CBlockIndex* pindexNew; // New tip during the interrupted flush.
3938 const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
3940 if (mapBlockIndex.count(hashHeads[0]) == 0) {
3941 return error("ReplayBlocks(): reorganization to unknown block requested");
3943 pindexNew = mapBlockIndex[hashHeads[0]];
3945 if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
3946 if (mapBlockIndex.count(hashHeads[1]) == 0) {
3947 return error("ReplayBlocks(): reorganization from unknown block requested");
3949 pindexOld = mapBlockIndex[hashHeads[1]];
3950 pindexFork = LastCommonAncestor(pindexOld, pindexNew);
3951 assert(pindexFork != nullptr);
3954 // Rollback along the old branch.
3955 while (pindexOld != pindexFork) {
3956 if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
3957 CBlock block;
3958 if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
3959 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3961 LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
3962 DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
3963 if (res == DISCONNECT_FAILED) {
3964 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
3966 // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
3967 // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
3968 // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
3969 // the result is still a version of the UTXO set with the effects of that block undone.
3971 pindexOld = pindexOld->pprev;
3974 // Roll forward from the forking point to the new tip.
3975 int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
3976 for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
3977 const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
3978 LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
3979 if (!RollforwardBlock(pindex, cache, params)) return false;
3982 cache.SetBestBlock(pindexNew->GetBlockHash());
3983 cache.Flush();
3984 uiInterface.ShowProgress("", 100, false);
3985 return true;
3988 bool ReplayBlocks(const CChainParams& params, CCoinsView* view) {
3989 return g_chainstate.ReplayBlocks(params, view);
3992 bool CChainState::RewindBlockIndex(const CChainParams& params)
3994 LOCK(cs_main);
3996 // Note that during -reindex-chainstate we are called with an empty chainActive!
3998 int nHeight = 1;
3999 while (nHeight <= chainActive.Height()) {
4000 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
4001 break;
4003 nHeight++;
4006 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4007 CValidationState state;
4008 CBlockIndex* pindex = chainActive.Tip();
4009 while (chainActive.Height() >= nHeight) {
4010 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4011 // If pruning, don't try rewinding past the HAVE_DATA point;
4012 // since older blocks can't be served anyway, there's
4013 // no need to walk further, and trying to DisconnectTip()
4014 // will fail (and require a needless reindex/redownload
4015 // of the blockchain).
4016 break;
4018 if (!DisconnectTip(state, params, nullptr)) {
4019 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4021 // Occasionally flush state to disk.
4022 if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
4023 return false;
4026 // Reduce validity flag and have-data flags.
4027 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4028 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4029 for (const auto& entry : mapBlockIndex) {
4030 CBlockIndex* pindexIter = entry.second;
4032 // Note: If we encounter an insufficiently validated block that
4033 // is on chainActive, it must be because we are a pruning node, and
4034 // this block or some successor doesn't HAVE_DATA, so we were unable to
4035 // rewind all the way. Blocks remaining on chainActive at this point
4036 // must not have their validity reduced.
4037 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
4038 // Reduce validity
4039 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
4040 // Remove have-data flags.
4041 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4042 // Remove storage location.
4043 pindexIter->nFile = 0;
4044 pindexIter->nDataPos = 0;
4045 pindexIter->nUndoPos = 0;
4046 // Remove various other things
4047 pindexIter->nTx = 0;
4048 pindexIter->nChainTx = 0;
4049 pindexIter->nSequenceId = 0;
4050 // Make sure it gets written.
4051 setDirtyBlockIndex.insert(pindexIter);
4052 // Update indexes
4053 setBlockIndexCandidates.erase(pindexIter);
4054 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4055 while (ret.first != ret.second) {
4056 if (ret.first->second == pindexIter) {
4057 mapBlocksUnlinked.erase(ret.first++);
4058 } else {
4059 ++ret.first;
4062 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4063 setBlockIndexCandidates.insert(pindexIter);
4067 if (chainActive.Tip() != nullptr) {
4068 // We can't prune block index candidates based on our tip if we have
4069 // no tip due to chainActive being empty!
4070 PruneBlockIndexCandidates();
4072 CheckBlockIndex(params.GetConsensus());
4075 return true;
4078 bool RewindBlockIndex(const CChainParams& params) {
4079 if (!g_chainstate.RewindBlockIndex(params)) {
4080 return false;
4083 if (chainActive.Tip() != nullptr) {
4084 // FlushStateToDisk can possibly read chainActive. Be conservative
4085 // and skip it here, we're about to -reindex-chainstate anyway, so
4086 // it'll get called a bunch real soon.
4087 CValidationState state;
4088 if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
4089 return false;
4093 return true;
4096 void CChainState::UnloadBlockIndex() {
4097 nBlockSequenceId = 1;
4098 g_failed_blocks.clear();
4099 setBlockIndexCandidates.clear();
4102 // May NOT be used after any connections are up as much
4103 // of the peer-processing logic assumes a consistent
4104 // block index state
4105 void UnloadBlockIndex()
4107 LOCK(cs_main);
4108 chainActive.SetTip(nullptr);
4109 pindexBestInvalid = nullptr;
4110 pindexBestHeader = nullptr;
4111 mempool.clear();
4112 mapBlocksUnlinked.clear();
4113 vinfoBlockFile.clear();
4114 nLastBlockFile = 0;
4115 setDirtyBlockIndex.clear();
4116 setDirtyFileInfo.clear();
4117 versionbitscache.Clear();
4118 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
4119 warningcache[b].clear();
4122 for (BlockMap::value_type& entry : mapBlockIndex) {
4123 delete entry.second;
4125 mapBlockIndex.clear();
4126 fHavePruned = false;
4128 g_chainstate.UnloadBlockIndex();
4131 bool LoadBlockIndex(const CChainParams& chainparams)
4133 // Load block index from databases
4134 bool needs_init = fReindex;
4135 if (!fReindex) {
4136 bool ret = LoadBlockIndexDB(chainparams);
4137 if (!ret) return false;
4138 needs_init = mapBlockIndex.empty();
4141 if (needs_init) {
4142 // Everything here is for *new* reindex/DBs. Thus, though
4143 // LoadBlockIndexDB may have set fReindex if we shut down
4144 // mid-reindex previously, we don't check fReindex and
4145 // instead only check it prior to LoadBlockIndexDB to set
4146 // needs_init.
4148 LogPrintf("Initializing databases...\n");
4149 // Use the provided setting for -txindex in the new database
4150 fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
4151 pblocktree->WriteFlag("txindex", fTxIndex);
4153 return true;
4156 bool CChainState::LoadGenesisBlock(const CChainParams& chainparams)
4158 LOCK(cs_main);
4160 // Check whether we're already initialized by checking for genesis in
4161 // mapBlockIndex. Note that we can't use chainActive here, since it is
4162 // set based on the coins db, not the block index db, which is the only
4163 // thing loaded at this point.
4164 if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
4165 return true;
4167 try {
4168 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
4169 CDiskBlockPos blockPos = SaveBlockToDisk(block, 0, chainparams, nullptr);
4170 if (blockPos.IsNull())
4171 return error("%s: writing genesis block to disk failed", __func__);
4172 CBlockIndex *pindex = AddToBlockIndex(block);
4173 CValidationState state;
4174 if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
4175 return error("%s: genesis block not accepted", __func__);
4176 } catch (const std::runtime_error& e) {
4177 return error("%s: failed to write genesis block: %s", __func__, e.what());
4180 return true;
4183 bool LoadGenesisBlock(const CChainParams& chainparams)
4185 return g_chainstate.LoadGenesisBlock(chainparams);
4188 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
4190 // Map of disk positions for blocks with unknown parent (only used for reindex)
4191 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4192 int64_t nStart = GetTimeMillis();
4194 int nLoaded = 0;
4195 try {
4196 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4197 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
4198 uint64_t nRewind = blkdat.GetPos();
4199 while (!blkdat.eof()) {
4200 boost::this_thread::interruption_point();
4202 blkdat.SetPos(nRewind);
4203 nRewind++; // start one byte further next time, in case of failure
4204 blkdat.SetLimit(); // remove former limit
4205 unsigned int nSize = 0;
4206 try {
4207 // locate a header
4208 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4209 blkdat.FindByte(chainparams.MessageStart()[0]);
4210 nRewind = blkdat.GetPos()+1;
4211 blkdat >> FLATDATA(buf);
4212 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
4213 continue;
4214 // read size
4215 blkdat >> nSize;
4216 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
4217 continue;
4218 } catch (const std::exception&) {
4219 // no valid block header found; don't complain
4220 break;
4222 try {
4223 // read block
4224 uint64_t nBlockPos = blkdat.GetPos();
4225 if (dbp)
4226 dbp->nPos = nBlockPos;
4227 blkdat.SetLimit(nBlockPos + nSize);
4228 blkdat.SetPos(nBlockPos);
4229 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4230 CBlock& block = *pblock;
4231 blkdat >> block;
4232 nRewind = blkdat.GetPos();
4234 // detect out of order blocks, and store them for later
4235 uint256 hash = block.GetHash();
4236 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4237 LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4238 block.hashPrevBlock.ToString());
4239 if (dbp)
4240 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4241 continue;
4244 // process in case the block isn't known yet
4245 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4246 LOCK(cs_main);
4247 CValidationState state;
4248 if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4249 nLoaded++;
4250 if (state.IsError())
4251 break;
4252 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4253 LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4256 // Activate the genesis block so normal node progress can continue
4257 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4258 CValidationState state;
4259 if (!ActivateBestChain(state, chainparams)) {
4260 break;
4264 NotifyHeaderTip();
4266 // Recursively process earlier encountered successors of this block
4267 std::deque<uint256> queue;
4268 queue.push_back(hash);
4269 while (!queue.empty()) {
4270 uint256 head = queue.front();
4271 queue.pop_front();
4272 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4273 while (range.first != range.second) {
4274 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4275 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4276 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4278 LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4279 head.ToString());
4280 LOCK(cs_main);
4281 CValidationState dummy;
4282 if (g_chainstate.AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4284 nLoaded++;
4285 queue.push_back(pblockrecursive->GetHash());
4288 range.first++;
4289 mapBlocksUnknownParent.erase(it);
4290 NotifyHeaderTip();
4293 } catch (const std::exception& e) {
4294 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4297 } catch (const std::runtime_error& e) {
4298 AbortNode(std::string("System error: ") + e.what());
4300 if (nLoaded > 0)
4301 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4302 return nLoaded > 0;
4305 void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
4307 if (!fCheckBlockIndex) {
4308 return;
4311 LOCK(cs_main);
4313 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4314 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4315 // iterating the block tree require that chainActive has been initialized.)
4316 if (chainActive.Height() < 0) {
4317 assert(mapBlockIndex.size() <= 1);
4318 return;
4321 // Build forward-pointing map of the entire block tree.
4322 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4323 for (auto& entry : mapBlockIndex) {
4324 forward.insert(std::make_pair(entry.second->pprev, entry.second));
4327 assert(forward.size() == mapBlockIndex.size());
4329 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4330 CBlockIndex *pindex = rangeGenesis.first->second;
4331 rangeGenesis.first++;
4332 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4334 // Iterate over the entire block tree, using depth-first search.
4335 // Along the way, remember whether there are blocks on the path from genesis
4336 // block being explored which are the first to have certain properties.
4337 size_t nNodes = 0;
4338 int nHeight = 0;
4339 CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4340 CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4341 CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4342 CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4343 CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4344 CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4345 CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4346 while (pindex != nullptr) {
4347 nNodes++;
4348 if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4349 if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4350 if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4351 if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4352 if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4353 if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4354 if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4356 // Begin: actual consistency checks.
4357 if (pindex->pprev == nullptr) {
4358 // Genesis block checks.
4359 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4360 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4362 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)
4363 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4364 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4365 if (!fHavePruned) {
4366 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4367 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4368 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4369 } else {
4370 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4371 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4373 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4374 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4375 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4376 assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4377 assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4378 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4379 assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4380 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4381 assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4382 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4383 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4384 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4385 if (pindexFirstInvalid == nullptr) {
4386 // Checks for not-invalid blocks.
4387 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4389 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4390 if (pindexFirstInvalid == nullptr) {
4391 // If this block sorts at least as good as the current tip and
4392 // is valid and we have all data for its parents, it must be in
4393 // setBlockIndexCandidates. chainActive.Tip() must also be there
4394 // even if some data has been pruned.
4395 if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4396 assert(setBlockIndexCandidates.count(pindex));
4398 // If some parent is missing, then it could be that this block was in
4399 // setBlockIndexCandidates but had to be removed because of the missing data.
4400 // In this case it must be in mapBlocksUnlinked -- see test below.
4402 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4403 assert(setBlockIndexCandidates.count(pindex) == 0);
4405 // Check whether this block is in mapBlocksUnlinked.
4406 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4407 bool foundInUnlinked = false;
4408 while (rangeUnlinked.first != rangeUnlinked.second) {
4409 assert(rangeUnlinked.first->first == pindex->pprev);
4410 if (rangeUnlinked.first->second == pindex) {
4411 foundInUnlinked = true;
4412 break;
4414 rangeUnlinked.first++;
4416 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4417 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4418 assert(foundInUnlinked);
4420 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4421 if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4422 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4423 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4424 assert(fHavePruned); // We must have pruned.
4425 // This block may have entered mapBlocksUnlinked if:
4426 // - it has a descendant that at some point had more work than the
4427 // tip, and
4428 // - we tried switching to that descendant but were missing
4429 // data for some intermediate block between chainActive and the
4430 // tip.
4431 // So if this block is itself better than chainActive.Tip() and it wasn't in
4432 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4433 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4434 if (pindexFirstInvalid == nullptr) {
4435 assert(foundInUnlinked);
4439 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4440 // End: actual consistency checks.
4442 // Try descending into the first subnode.
4443 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4444 if (range.first != range.second) {
4445 // A subnode was found.
4446 pindex = range.first->second;
4447 nHeight++;
4448 continue;
4450 // This is a leaf node.
4451 // Move upwards until we reach a node of which we have not yet visited the last child.
4452 while (pindex) {
4453 // We are going to either move to a parent or a sibling of pindex.
4454 // If pindex was the first with a certain property, unset the corresponding variable.
4455 if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4456 if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4457 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4458 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4459 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4460 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4461 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4462 // Find our parent.
4463 CBlockIndex* pindexPar = pindex->pprev;
4464 // Find which child we just visited.
4465 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4466 while (rangePar.first->second != pindex) {
4467 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4468 rangePar.first++;
4470 // Proceed to the next one.
4471 rangePar.first++;
4472 if (rangePar.first != rangePar.second) {
4473 // Move to the sibling.
4474 pindex = rangePar.first->second;
4475 break;
4476 } else {
4477 // Move up further.
4478 pindex = pindexPar;
4479 nHeight--;
4480 continue;
4485 // Check that we actually traversed the entire map.
4486 assert(nNodes == forward.size());
4489 std::string CBlockFileInfo::ToString() const
4491 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));
4494 CBlockFileInfo* GetBlockFileInfo(size_t n)
4496 LOCK(cs_LastBlockFile);
4498 return &vinfoBlockFile.at(n);
4501 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4503 LOCK(cs_main);
4504 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4507 BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
4509 LOCK(cs_main);
4510 return VersionBitsStatistics(chainActive.Tip(), params, pos);
4513 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4515 LOCK(cs_main);
4516 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4519 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4521 bool LoadMempool(void)
4523 const CChainParams& chainparams = Params();
4524 int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4525 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4526 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4527 if (file.IsNull()) {
4528 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4529 return false;
4532 int64_t count = 0;
4533 int64_t expired = 0;
4534 int64_t failed = 0;
4535 int64_t already_there = 0;
4536 int64_t nNow = GetTime();
4538 try {
4539 uint64_t version;
4540 file >> version;
4541 if (version != MEMPOOL_DUMP_VERSION) {
4542 return false;
4544 uint64_t num;
4545 file >> num;
4546 while (num--) {
4547 CTransactionRef tx;
4548 int64_t nTime;
4549 int64_t nFeeDelta;
4550 file >> tx;
4551 file >> nTime;
4552 file >> nFeeDelta;
4554 CAmount amountdelta = nFeeDelta;
4555 if (amountdelta) {
4556 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4558 CValidationState state;
4559 if (nTime + nExpiryTimeout > nNow) {
4560 LOCK(cs_main);
4561 AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4562 nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
4563 if (state.IsValid()) {
4564 ++count;
4565 } else {
4566 // mempool may contain the transaction already, e.g. from
4567 // wallet(s) having loaded it while we were processing
4568 // mempool transactions; consider these as valid, instead of
4569 // failed, but mark them as 'already there'
4570 if (mempool.exists(tx->GetHash())) {
4571 ++already_there;
4572 } else {
4573 ++failed;
4576 } else {
4577 ++expired;
4579 if (ShutdownRequested())
4580 return false;
4582 std::map<uint256, CAmount> mapDeltas;
4583 file >> mapDeltas;
4585 for (const auto& i : mapDeltas) {
4586 mempool.PrioritiseTransaction(i.first, i.second);
4588 } catch (const std::exception& e) {
4589 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4590 return false;
4593 LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4594 return true;
4597 bool DumpMempool(void)
4599 int64_t start = GetTimeMicros();
4601 std::map<uint256, CAmount> mapDeltas;
4602 std::vector<TxMempoolInfo> vinfo;
4605 LOCK(mempool.cs);
4606 for (const auto &i : mempool.mapDeltas) {
4607 mapDeltas[i.first] = i.second;
4609 vinfo = mempool.infoAll();
4612 int64_t mid = GetTimeMicros();
4614 try {
4615 FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
4616 if (!filestr) {
4617 return false;
4620 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4622 uint64_t version = MEMPOOL_DUMP_VERSION;
4623 file << version;
4625 file << (uint64_t)vinfo.size();
4626 for (const auto& i : vinfo) {
4627 file << *(i.tx);
4628 file << (int64_t)i.nTime;
4629 file << (int64_t)i.nFeeDelta;
4630 mapDeltas.erase(i.tx->GetHash());
4633 file << mapDeltas;
4634 FileCommit(file.Get());
4635 file.fclose();
4636 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4637 int64_t last = GetTimeMicros();
4638 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
4639 } catch (const std::exception& e) {
4640 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4641 return false;
4643 return true;
4646 //! Guess how far we are in the verification process at the given block index
4647 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
4648 if (pindex == nullptr)
4649 return 0.0;
4651 int64_t nNow = time(nullptr);
4653 double fTxTotal;
4655 if (pindex->nChainTx <= data.nTxCount) {
4656 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4657 } else {
4658 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4661 return pindex->nChainTx / fTxTotal;
4664 class CMainCleanup
4666 public:
4667 CMainCleanup() {}
4668 ~CMainCleanup() {
4669 // block headers
4670 BlockMap::iterator it1 = mapBlockIndex.begin();
4671 for (; it1 != mapBlockIndex.end(); it1++)
4672 delete (*it1).second;
4673 mapBlockIndex.clear();
4675 } instance_of_cmaincleanup;