Fix parameter naming inconsistencies between .h and .cpp files
[bitcoinplatinum.git] / src / validation.cpp
blobbe82026b3ca801e67037ec49698784e5c9c7ab94
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 "chainparams.h"
10 #include "checkpoints.h"
11 #include "checkqueue.h"
12 #include "consensus/consensus.h"
13 #include "consensus/merkle.h"
14 #include "consensus/validation.h"
15 #include "hash.h"
16 #include "init.h"
17 #include "policy/fees.h"
18 #include "policy/policy.h"
19 #include "pow.h"
20 #include "primitives/block.h"
21 #include "primitives/transaction.h"
22 #include "random.h"
23 #include "script/script.h"
24 #include "script/sigcache.h"
25 #include "script/standard.h"
26 #include "timedata.h"
27 #include "tinyformat.h"
28 #include "txdb.h"
29 #include "txmempool.h"
30 #include "ui_interface.h"
31 #include "undo.h"
32 #include "util.h"
33 #include "utilmoneystr.h"
34 #include "utilstrencodings.h"
35 #include "validationinterface.h"
36 #include "versionbits.h"
37 #include "warnings.h"
39 #include <atomic>
40 #include <sstream>
42 #include <boost/algorithm/string/replace.hpp>
43 #include <boost/algorithm/string/join.hpp>
44 #include <boost/filesystem.hpp>
45 #include <boost/filesystem/fstream.hpp>
46 #include <boost/math/distributions/poisson.hpp>
47 #include <boost/thread.hpp>
49 #if defined(NDEBUG)
50 # error "Bitcoin cannot be compiled without assertions."
51 #endif
53 /**
54 * Global state
57 CCriticalSection cs_main;
59 BlockMap mapBlockIndex;
60 CChain chainActive;
61 CBlockIndex *pindexBestHeader = NULL;
62 CWaitableCriticalSection csBestBlock;
63 CConditionVariable cvBlockChange;
64 int nScriptCheckThreads = 0;
65 std::atomic_bool fImporting(false);
66 bool fReindex = false;
67 bool fTxIndex = false;
68 bool fHavePruned = false;
69 bool fPruneMode = false;
70 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
71 bool fRequireStandard = true;
72 bool fCheckBlockIndex = false;
73 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
74 size_t nCoinCacheUsage = 5000 * 300;
75 uint64_t nPruneTarget = 0;
76 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
77 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
79 uint256 hashAssumeValid;
81 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
82 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
84 CTxMemPool mempool;
86 static void CheckBlockIndex(const Consensus::Params& consensusParams);
88 /** Constant stuff for coinbase transactions we create: */
89 CScript COINBASE_FLAGS;
91 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
93 // Internal stuff
94 namespace {
96 struct CBlockIndexWorkComparator
98 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
99 // First sort by most total work, ...
100 if (pa->nChainWork > pb->nChainWork) return false;
101 if (pa->nChainWork < pb->nChainWork) return true;
103 // ... then by earliest time received, ...
104 if (pa->nSequenceId < pb->nSequenceId) return false;
105 if (pa->nSequenceId > pb->nSequenceId) return true;
107 // Use pointer address as tie breaker (should only happen with blocks
108 // loaded from disk, as those all have id 0).
109 if (pa < pb) return false;
110 if (pa > pb) return true;
112 // Identical blocks.
113 return false;
117 CBlockIndex *pindexBestInvalid;
120 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
121 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
122 * missing the data for the block.
124 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
125 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
126 * Pruned nodes may have entries where B is missing data.
128 std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
130 CCriticalSection cs_LastBlockFile;
131 std::vector<CBlockFileInfo> vinfoBlockFile;
132 int nLastBlockFile = 0;
133 /** Global flag to indicate we should check to see if there are
134 * block/undo files that should be deleted. Set on startup
135 * or if we allocate more file space when we're in prune mode
137 bool fCheckForPruning = false;
140 * Every received block is assigned a unique and increasing identifier, so we
141 * know which one to give priority in case of a fork.
143 CCriticalSection cs_nBlockSequenceId;
144 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
145 int32_t nBlockSequenceId = 1;
146 /** Decreasing counter (used by subsequent preciousblock calls). */
147 int32_t nBlockReverseSequenceId = -1;
148 /** chainwork for the last block that preciousblock has been applied to. */
149 arith_uint256 nLastPreciousChainwork = 0;
151 /** Dirty block index entries. */
152 std::set<CBlockIndex*> setDirtyBlockIndex;
154 /** Dirty block file entries. */
155 std::set<int> setDirtyFileInfo;
156 } // anon namespace
158 /* Use this class to start tracking transactions that are removed from the
159 * mempool and pass all those transactions through SyncTransaction when the
160 * object goes out of scope. This is currently only used to call SyncTransaction
161 * on conflicts removed from the mempool during block connection. Applied in
162 * ActivateBestChain around ActivateBestStep which in turn calls:
163 * ConnectTip->removeForBlock->removeConflicts
165 class MemPoolConflictRemovalTracker
167 private:
168 std::vector<CTransactionRef> conflictedTxs;
169 CTxMemPool &pool;
171 public:
172 MemPoolConflictRemovalTracker(CTxMemPool &_pool) : pool(_pool) {
173 pool.NotifyEntryRemoved.connect(boost::bind(&MemPoolConflictRemovalTracker::NotifyEntryRemoved, this, _1, _2));
176 void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
177 if (reason == MemPoolRemovalReason::CONFLICT) {
178 conflictedTxs.push_back(txRemoved);
182 ~MemPoolConflictRemovalTracker() {
183 pool.NotifyEntryRemoved.disconnect(boost::bind(&MemPoolConflictRemovalTracker::NotifyEntryRemoved, this, _1, _2));
184 for (const auto& tx : conflictedTxs) {
185 GetMainSignals().SyncTransaction(*tx, NULL, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
187 conflictedTxs.clear();
191 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
193 // Find the first block the caller has in the main chain
194 BOOST_FOREACH(const uint256& hash, locator.vHave) {
195 BlockMap::iterator mi = mapBlockIndex.find(hash);
196 if (mi != mapBlockIndex.end())
198 CBlockIndex* pindex = (*mi).second;
199 if (chain.Contains(pindex))
200 return pindex;
201 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
202 return chain.Tip();
206 return chain.Genesis();
209 CCoinsViewCache *pcoinsTip = NULL;
210 CBlockTreeDB *pblocktree = NULL;
212 enum FlushStateMode {
213 FLUSH_STATE_NONE,
214 FLUSH_STATE_IF_NEEDED,
215 FLUSH_STATE_PERIODIC,
216 FLUSH_STATE_ALWAYS
219 // See definition for documentation
220 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
221 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
223 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
225 if (tx.nLockTime == 0)
226 return true;
227 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
228 return true;
229 for (const auto& txin : tx.vin) {
230 if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
231 return false;
233 return true;
236 bool CheckFinalTx(const CTransaction &tx, int flags)
238 AssertLockHeld(cs_main);
240 // By convention a negative value for flags indicates that the
241 // current network-enforced consensus rules should be used. In
242 // a future soft-fork scenario that would mean checking which
243 // rules would be enforced for the next block and setting the
244 // appropriate flags. At the present time no soft-forks are
245 // scheduled, so no flags are set.
246 flags = std::max(flags, 0);
248 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
249 // nLockTime because when IsFinalTx() is called within
250 // CBlock::AcceptBlock(), the height of the block *being*
251 // evaluated is what is used. Thus if we want to know if a
252 // transaction can be part of the *next* block, we need to call
253 // IsFinalTx() with one more than chainActive.Height().
254 const int nBlockHeight = chainActive.Height() + 1;
256 // BIP113 will require that time-locked transactions have nLockTime set to
257 // less than the median time of the previous block they're contained in.
258 // When the next block is created its previous block will be the current
259 // chain tip, so we use that to calculate the median time passed to
260 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
261 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
262 ? chainActive.Tip()->GetMedianTimePast()
263 : GetAdjustedTime();
265 return IsFinalTx(tx, nBlockHeight, nBlockTime);
269 * Calculates the block height and previous block's median time past at
270 * which the transaction will be considered final in the context of BIP 68.
271 * Also removes from the vector of input heights any entries which did not
272 * correspond to sequence locked inputs as they do not affect the calculation.
274 static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
276 assert(prevHeights->size() == tx.vin.size());
278 // Will be set to the equivalent height- and time-based nLockTime
279 // values that would be necessary to satisfy all relative lock-
280 // time constraints given our view of block chain history.
281 // The semantics of nLockTime are the last invalid height/time, so
282 // use -1 to have the effect of any height or time being valid.
283 int nMinHeight = -1;
284 int64_t nMinTime = -1;
286 // tx.nVersion is signed integer so requires cast to unsigned otherwise
287 // we would be doing a signed comparison and half the range of nVersion
288 // wouldn't support BIP 68.
289 bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
290 && flags & LOCKTIME_VERIFY_SEQUENCE;
292 // Do not enforce sequence numbers as a relative lock time
293 // unless we have been instructed to
294 if (!fEnforceBIP68) {
295 return std::make_pair(nMinHeight, nMinTime);
298 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
299 const CTxIn& txin = tx.vin[txinIndex];
301 // Sequence numbers with the most significant bit set are not
302 // treated as relative lock-times, nor are they given any
303 // consensus-enforced meaning at this point.
304 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
305 // The height of this input is not relevant for sequence locks
306 (*prevHeights)[txinIndex] = 0;
307 continue;
310 int nCoinHeight = (*prevHeights)[txinIndex];
312 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
313 int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
314 // NOTE: Subtract 1 to maintain nLockTime semantics
315 // BIP 68 relative lock times have the semantics of calculating
316 // the first block or time at which the transaction would be
317 // valid. When calculating the effective block time or height
318 // for the entire transaction, we switch to using the
319 // semantics of nLockTime which is the last invalid block
320 // time or height. Thus we subtract 1 from the calculated
321 // time or height.
323 // Time-based relative lock-times are measured from the
324 // smallest allowed timestamp of the block containing the
325 // txout being spent, which is the median time past of the
326 // block prior.
327 nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
328 } else {
329 nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
333 return std::make_pair(nMinHeight, nMinTime);
336 static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
338 assert(block.pprev);
339 int64_t nBlockTime = block.pprev->GetMedianTimePast();
340 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
341 return false;
343 return true;
346 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
348 return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
351 bool TestLockPointValidity(const LockPoints* lp)
353 AssertLockHeld(cs_main);
354 assert(lp);
355 // If there are relative lock times then the maxInputBlock will be set
356 // If there are no relative lock times, the LockPoints don't depend on the chain
357 if (lp->maxInputBlock) {
358 // Check whether chainActive is an extension of the block at which the LockPoints
359 // calculation was valid. If not LockPoints are no longer valid
360 if (!chainActive.Contains(lp->maxInputBlock)) {
361 return false;
365 // LockPoints still valid
366 return true;
369 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
371 AssertLockHeld(cs_main);
372 AssertLockHeld(mempool.cs);
374 CBlockIndex* tip = chainActive.Tip();
375 CBlockIndex index;
376 index.pprev = tip;
377 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
378 // height based locks because when SequenceLocks() is called within
379 // ConnectBlock(), the height of the block *being*
380 // evaluated is what is used.
381 // Thus if we want to know if a transaction can be part of the
382 // *next* block, we need to use one more than chainActive.Height()
383 index.nHeight = tip->nHeight + 1;
385 std::pair<int, int64_t> lockPair;
386 if (useExistingLockPoints) {
387 assert(lp);
388 lockPair.first = lp->height;
389 lockPair.second = lp->time;
391 else {
392 // pcoinsTip contains the UTXO set for chainActive.Tip()
393 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
394 std::vector<int> prevheights;
395 prevheights.resize(tx.vin.size());
396 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
397 const CTxIn& txin = tx.vin[txinIndex];
398 CCoins coins;
399 if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
400 return error("%s: Missing input", __func__);
402 if (coins.nHeight == MEMPOOL_HEIGHT) {
403 // Assume all mempool transaction confirm in the next block
404 prevheights[txinIndex] = tip->nHeight + 1;
405 } else {
406 prevheights[txinIndex] = coins.nHeight;
409 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
410 if (lp) {
411 lp->height = lockPair.first;
412 lp->time = lockPair.second;
413 // Also store the hash of the block with the highest height of
414 // all the blocks which have sequence locked prevouts.
415 // This hash needs to still be on the chain
416 // for these LockPoint calculations to be valid
417 // Note: It is impossible to correctly calculate a maxInputBlock
418 // if any of the sequence locked inputs depend on unconfirmed txs,
419 // except in the special case where the relative lock time/height
420 // is 0, which is equivalent to no sequence lock. Since we assume
421 // input height of tip+1 for mempool txs and test the resulting
422 // lockPair from CalculateSequenceLocks against tip+1. We know
423 // EvaluateSequenceLocks will fail if there was a non-zero sequence
424 // lock on a mempool input, so we can use the return value of
425 // CheckSequenceLocks to indicate the LockPoints validity
426 int maxInputHeight = 0;
427 BOOST_FOREACH(int height, prevheights) {
428 // Can ignore mempool inputs since we'll fail if they had non-zero locks
429 if (height != tip->nHeight+1) {
430 maxInputHeight = std::max(maxInputHeight, height);
433 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
436 return EvaluateSequenceLocks(index, lockPair);
440 unsigned int GetLegacySigOpCount(const CTransaction& tx)
442 unsigned int nSigOps = 0;
443 for (const auto& txin : tx.vin)
445 nSigOps += txin.scriptSig.GetSigOpCount(false);
447 for (const auto& txout : tx.vout)
449 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
451 return nSigOps;
454 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
456 if (tx.IsCoinBase())
457 return 0;
459 unsigned int nSigOps = 0;
460 for (unsigned int i = 0; i < tx.vin.size(); i++)
462 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
463 if (prevout.scriptPubKey.IsPayToScriptHash())
464 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
466 return nSigOps;
469 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
471 int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
473 if (tx.IsCoinBase())
474 return nSigOps;
476 if (flags & SCRIPT_VERIFY_P2SH) {
477 nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
480 for (unsigned int i = 0; i < tx.vin.size(); i++)
482 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
483 nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
485 return nSigOps;
492 bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)
494 // Basic checks that don't depend on any context
495 if (tx.vin.empty())
496 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
497 if (tx.vout.empty())
498 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
499 // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
500 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
501 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
503 // Check for negative or overflow output values
504 CAmount nValueOut = 0;
505 for (const auto& txout : tx.vout)
507 if (txout.nValue < 0)
508 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
509 if (txout.nValue > MAX_MONEY)
510 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
511 nValueOut += txout.nValue;
512 if (!MoneyRange(nValueOut))
513 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
516 // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
517 if (fCheckDuplicateInputs) {
518 std::set<COutPoint> vInOutPoints;
519 for (const auto& txin : tx.vin)
521 if (!vInOutPoints.insert(txin.prevout).second)
522 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
526 if (tx.IsCoinBase())
528 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
529 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
531 else
533 for (const auto& txin : tx.vin)
534 if (txin.prevout.IsNull())
535 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
538 return true;
541 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
542 int expired = pool.Expire(GetTime() - age);
543 if (expired != 0)
544 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
546 std::vector<uint256> vNoSpendsRemaining;
547 pool.TrimToSize(limit, &vNoSpendsRemaining);
548 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
549 pcoinsTip->Uncache(removed);
552 /** Convert CValidationState to a human-readable message for logging */
553 std::string FormatStateMessage(const CValidationState &state)
555 return strprintf("%s%s (code %i)",
556 state.GetRejectReason(),
557 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
558 state.GetRejectCode());
561 static bool IsCurrentForFeeEstimation()
563 AssertLockHeld(cs_main);
564 if (IsInitialBlockDownload())
565 return false;
566 if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
567 return false;
568 if (chainActive.Height() < pindexBestHeader->nHeight - 1)
569 return false;
570 return true;
573 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
574 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
575 bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
577 const CTransaction& tx = *ptx;
578 const uint256 hash = tx.GetHash();
579 AssertLockHeld(cs_main);
580 if (pfMissingInputs)
581 *pfMissingInputs = false;
583 if (!CheckTransaction(tx, state))
584 return false; // state filled in by CheckTransaction
586 // Coinbase is only valid in a block, not as a loose transaction
587 if (tx.IsCoinBase())
588 return state.DoS(100, false, REJECT_INVALID, "coinbase");
590 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
591 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus());
592 if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
593 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
596 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
597 std::string reason;
598 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
599 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
601 // Only accept nLockTime-using transactions that can be mined in the next
602 // block; we don't want our mempool filled up with transactions that can't
603 // be mined yet.
604 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
605 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
607 // is it already in the memory pool?
608 if (pool.exists(hash))
609 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
611 // Check for conflicts with in-memory transactions
612 std::set<uint256> setConflicts;
614 LOCK(pool.cs); // protect pool.mapNextTx
615 BOOST_FOREACH(const CTxIn &txin, tx.vin)
617 auto itConflicting = pool.mapNextTx.find(txin.prevout);
618 if (itConflicting != pool.mapNextTx.end())
620 const CTransaction *ptxConflicting = itConflicting->second;
621 if (!setConflicts.count(ptxConflicting->GetHash()))
623 // Allow opt-out of transaction replacement by setting
624 // nSequence >= maxint-1 on all inputs.
626 // maxint-1 is picked to still allow use of nLockTime by
627 // non-replaceable transactions. All inputs rather than just one
628 // is for the sake of multi-party protocols, where we don't
629 // want a single party to be able to disable replacement.
631 // The opt-out ignores descendants as anyone relying on
632 // first-seen mempool behavior should be checking all
633 // unconfirmed ancestors anyway; doing otherwise is hopelessly
634 // insecure.
635 bool fReplacementOptOut = true;
636 if (fEnableReplacement)
638 BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
640 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
642 fReplacementOptOut = false;
643 break;
647 if (fReplacementOptOut)
648 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
650 setConflicts.insert(ptxConflicting->GetHash());
657 CCoinsView dummy;
658 CCoinsViewCache view(&dummy);
660 CAmount nValueIn = 0;
661 LockPoints lp;
663 LOCK(pool.cs);
664 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
665 view.SetBackend(viewMemPool);
667 // do we already have it?
668 bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
669 if (view.HaveCoins(hash)) {
670 if (!fHadTxInCache)
671 vHashTxnToUncache.push_back(hash);
672 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
675 // do all inputs exist?
676 // Note that this does not check for the presence of actual outputs (see the next check for that),
677 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
678 BOOST_FOREACH(const CTxIn txin, tx.vin) {
679 if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
680 vHashTxnToUncache.push_back(txin.prevout.hash);
681 if (!view.HaveCoins(txin.prevout.hash)) {
682 if (pfMissingInputs)
683 *pfMissingInputs = true;
684 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
688 // are the actual inputs available?
689 if (!view.HaveInputs(tx))
690 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
692 // Bring the best block into scope
693 view.GetBestBlock();
695 nValueIn = view.GetValueIn(tx);
697 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
698 view.SetBackend(dummy);
700 // Only accept BIP68 sequence locked transactions that can be mined in the next
701 // block; we don't want our mempool filled up with transactions that can't
702 // be mined yet.
703 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
704 // CoinsViewCache instead of create its own
705 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
706 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
709 // Check for non-standard pay-to-script-hash in inputs
710 if (fRequireStandard && !AreInputsStandard(tx, view))
711 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
713 // Check for non-standard witness in P2WSH
714 if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
715 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
717 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
719 CAmount nValueOut = tx.GetValueOut();
720 CAmount nFees = nValueIn-nValueOut;
721 // nModifiedFees includes any fee deltas from PrioritiseTransaction
722 CAmount nModifiedFees = nFees;
723 pool.ApplyDelta(hash, nModifiedFees);
725 // Keep track of transactions that spend a coinbase, which we re-scan
726 // during reorgs to ensure COINBASE_MATURITY is still met.
727 bool fSpendsCoinbase = false;
728 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
729 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
730 if (coins->IsCoinBase()) {
731 fSpendsCoinbase = true;
732 break;
736 CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
737 fSpendsCoinbase, nSigOpsCost, lp);
738 unsigned int nSize = entry.GetTxSize();
740 // Check that the transaction doesn't have an excessive number of
741 // sigops, making it impossible to mine. Since the coinbase transaction
742 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
743 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
744 // merely non-standard transaction.
745 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
746 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
747 strprintf("%d", nSigOpsCost));
749 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
750 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
751 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
754 // No transactions are allowed below minRelayTxFee except from disconnected blocks
755 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
756 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
759 if (nAbsurdFee && nFees > nAbsurdFee)
760 return state.Invalid(false,
761 REJECT_HIGHFEE, "absurdly-high-fee",
762 strprintf("%d > %d", nFees, nAbsurdFee));
764 // Calculate in-mempool ancestors, up to a limit.
765 CTxMemPool::setEntries setAncestors;
766 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
767 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
768 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
769 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
770 std::string errString;
771 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
772 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
775 // A transaction that spends outputs that would be replaced by it is invalid. Now
776 // that we have the set of all ancestors we can detect this
777 // pathological case by making sure setConflicts and setAncestors don't
778 // intersect.
779 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
781 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
782 if (setConflicts.count(hashAncestor))
784 return state.DoS(10, false,
785 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
786 strprintf("%s spends conflicting transaction %s",
787 hash.ToString(),
788 hashAncestor.ToString()));
792 // Check if it's economically rational to mine this transaction rather
793 // than the ones it replaces.
794 CAmount nConflictingFees = 0;
795 size_t nConflictingSize = 0;
796 uint64_t nConflictingCount = 0;
797 CTxMemPool::setEntries allConflicting;
799 // If we don't hold the lock allConflicting might be incomplete; the
800 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
801 // mempool consistency for us.
802 LOCK(pool.cs);
803 const bool fReplacementTransaction = setConflicts.size();
804 if (fReplacementTransaction)
806 CFeeRate newFeeRate(nModifiedFees, nSize);
807 std::set<uint256> setConflictsParents;
808 const int maxDescendantsToVisit = 100;
809 CTxMemPool::setEntries setIterConflicting;
810 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
812 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
813 if (mi == pool.mapTx.end())
814 continue;
816 // Save these to avoid repeated lookups
817 setIterConflicting.insert(mi);
819 // Don't allow the replacement to reduce the feerate of the
820 // mempool.
822 // We usually don't want to accept replacements with lower
823 // feerates than what they replaced as that would lower the
824 // feerate of the next block. Requiring that the feerate always
825 // be increased is also an easy-to-reason about way to prevent
826 // DoS attacks via replacements.
828 // The mining code doesn't (currently) take children into
829 // account (CPFP) so we only consider the feerates of
830 // transactions being directly replaced, not their indirect
831 // descendants. While that does mean high feerate children are
832 // ignored when deciding whether or not to replace, we do
833 // require the replacement to pay more overall fees too,
834 // mitigating most cases.
835 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
836 if (newFeeRate <= oldFeeRate)
838 return state.DoS(0, false,
839 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
840 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
841 hash.ToString(),
842 newFeeRate.ToString(),
843 oldFeeRate.ToString()));
846 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
848 setConflictsParents.insert(txin.prevout.hash);
851 nConflictingCount += mi->GetCountWithDescendants();
853 // This potentially overestimates the number of actual descendants
854 // but we just want to be conservative to avoid doing too much
855 // work.
856 if (nConflictingCount <= maxDescendantsToVisit) {
857 // If not too many to replace, then calculate the set of
858 // transactions that would have to be evicted
859 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
860 pool.CalculateDescendants(it, allConflicting);
862 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
863 nConflictingFees += it->GetModifiedFee();
864 nConflictingSize += it->GetTxSize();
866 } else {
867 return state.DoS(0, false,
868 REJECT_NONSTANDARD, "too many potential replacements", false,
869 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
870 hash.ToString(),
871 nConflictingCount,
872 maxDescendantsToVisit));
875 for (unsigned int j = 0; j < tx.vin.size(); j++)
877 // We don't want to accept replacements that require low
878 // feerate junk to be mined first. Ideally we'd keep track of
879 // the ancestor feerates and make the decision based on that,
880 // but for now requiring all new inputs to be confirmed works.
881 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
883 // Rather than check the UTXO set - potentially expensive -
884 // it's cheaper to just check if the new input refers to a
885 // tx that's in the mempool.
886 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
887 return state.DoS(0, false,
888 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
889 strprintf("replacement %s adds unconfirmed input, idx %d",
890 hash.ToString(), j));
894 // The replacement must pay greater fees than the transactions it
895 // replaces - if we did the bandwidth used by those conflicting
896 // transactions would not be paid for.
897 if (nModifiedFees < nConflictingFees)
899 return state.DoS(0, false,
900 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
901 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
902 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
905 // Finally in addition to paying more fees than the conflicts the
906 // new transaction must pay for its own bandwidth.
907 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
908 if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
910 return state.DoS(0, false,
911 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
912 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
913 hash.ToString(),
914 FormatMoney(nDeltaFees),
915 FormatMoney(::incrementalRelayFee.GetFee(nSize))));
919 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
920 if (!Params().RequireStandard()) {
921 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
924 // Check against previous transactions
925 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
926 PrecomputedTransactionData txdata(tx);
927 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
928 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
929 // need to turn both off, and compare against just turning off CLEANSTACK
930 // to see if the failure is specifically due to witness validation.
931 CValidationState stateDummy; // Want reported failures to be from first CheckInputs
932 if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
933 !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
934 // Only the witness is missing, so the transaction itself may be fine.
935 state.SetCorruptionPossible();
937 return false; // state filled in by CheckInputs
940 // Check again against just the consensus-critical mandatory script
941 // verification flags, in case of bugs in the standard flags that cause
942 // transactions to pass as valid when they're actually invalid. For
943 // instance the STRICTENC flag was incorrectly allowing certain
944 // CHECKSIG NOT scripts to pass, even though they were invalid.
946 // There is a similar check in CreateNewBlock() to prevent creating
947 // invalid blocks, however allowing such transactions into the mempool
948 // can be exploited as a DoS attack.
949 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
951 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
952 __func__, hash.ToString(), FormatStateMessage(state));
955 // Remove conflicting transactions from the mempool
956 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
958 LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
959 it->GetTx().GetHash().ToString(),
960 hash.ToString(),
961 FormatMoney(nModifiedFees - nConflictingFees),
962 (int)nSize - (int)nConflictingSize);
963 if (plTxnReplaced)
964 plTxnReplaced->push_back(it->GetSharedTx());
966 pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
968 // This transaction should only count for fee estimation if it isn't a
969 // BIP 125 replacement transaction (may not be widely supported), the
970 // node is not behind, and the transaction is not dependent on any other
971 // transactions in the mempool.
972 bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
974 // Store transaction in memory
975 pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
977 // trim mempool and check if tx was trimmed
978 if (!fOverrideMempoolLimit) {
979 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
980 if (!pool.exists(hash))
981 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
985 GetMainSignals().SyncTransaction(tx, NULL, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
987 return true;
990 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
991 bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
992 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
994 std::vector<uint256> vHashTxToUncache;
995 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
996 if (!res) {
997 BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
998 pcoinsTip->Uncache(hashTx);
1000 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1001 CValidationState stateDummy;
1002 FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
1003 return res;
1006 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
1007 bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
1008 bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
1010 return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
1013 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
1014 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
1016 CBlockIndex *pindexSlow = NULL;
1018 LOCK(cs_main);
1020 CTransactionRef ptx = mempool.get(hash);
1021 if (ptx)
1023 txOut = ptx;
1024 return true;
1027 if (fTxIndex) {
1028 CDiskTxPos postx;
1029 if (pblocktree->ReadTxIndex(hash, postx)) {
1030 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1031 if (file.IsNull())
1032 return error("%s: OpenBlockFile failed", __func__);
1033 CBlockHeader header;
1034 try {
1035 file >> header;
1036 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1037 file >> txOut;
1038 } catch (const std::exception& e) {
1039 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1041 hashBlock = header.GetHash();
1042 if (txOut->GetHash() != hash)
1043 return error("%s: txid mismatch", __func__);
1044 return true;
1048 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1049 int nHeight = -1;
1051 const CCoinsViewCache& view = *pcoinsTip;
1052 const CCoins* coins = view.AccessCoins(hash);
1053 if (coins)
1054 nHeight = coins->nHeight;
1056 if (nHeight > 0)
1057 pindexSlow = chainActive[nHeight];
1060 if (pindexSlow) {
1061 CBlock block;
1062 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1063 for (const auto& tx : block.vtx) {
1064 if (tx->GetHash() == hash) {
1065 txOut = tx;
1066 hashBlock = pindexSlow->GetBlockHash();
1067 return true;
1073 return false;
1081 //////////////////////////////////////////////////////////////////////////////
1083 // CBlock and CBlockIndex
1086 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1088 // Open history file to append
1089 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1090 if (fileout.IsNull())
1091 return error("WriteBlockToDisk: OpenBlockFile failed");
1093 // Write index header
1094 unsigned int nSize = GetSerializeSize(fileout, block);
1095 fileout << FLATDATA(messageStart) << nSize;
1097 // Write block
1098 long fileOutPos = ftell(fileout.Get());
1099 if (fileOutPos < 0)
1100 return error("WriteBlockToDisk: ftell failed");
1101 pos.nPos = (unsigned int)fileOutPos;
1102 fileout << block;
1104 return true;
1107 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1109 block.SetNull();
1111 // Open history file to read
1112 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1113 if (filein.IsNull())
1114 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1116 // Read block
1117 try {
1118 filein >> block;
1120 catch (const std::exception& e) {
1121 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1124 // Check the header
1125 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1126 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1128 return true;
1131 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1133 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1134 return false;
1135 if (block.GetHash() != pindex->GetBlockHash())
1136 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1137 pindex->ToString(), pindex->GetBlockPos().ToString());
1138 return true;
1141 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1143 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1144 // Force block reward to zero when right shift is undefined.
1145 if (halvings >= 64)
1146 return 0;
1148 CAmount nSubsidy = 50 * COIN;
1149 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1150 nSubsidy >>= halvings;
1151 return nSubsidy;
1154 bool IsInitialBlockDownload()
1156 const CChainParams& chainParams = Params();
1158 // Once this function has returned false, it must remain false.
1159 static std::atomic<bool> latchToFalse{false};
1160 // Optimization: pre-test latch before taking the lock.
1161 if (latchToFalse.load(std::memory_order_relaxed))
1162 return false;
1164 LOCK(cs_main);
1165 if (latchToFalse.load(std::memory_order_relaxed))
1166 return false;
1167 if (fImporting || fReindex)
1168 return true;
1169 if (chainActive.Tip() == NULL)
1170 return true;
1171 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1172 return true;
1173 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1174 return true;
1175 latchToFalse.store(true, std::memory_order_relaxed);
1176 return false;
1179 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1181 static void AlertNotify(const std::string& strMessage)
1183 uiInterface.NotifyAlertChanged();
1184 std::string strCmd = GetArg("-alertnotify", "");
1185 if (strCmd.empty()) return;
1187 // Alert text should be plain ascii coming from a trusted source, but to
1188 // be safe we first strip anything not in safeChars, then add single quotes around
1189 // the whole string before passing it to the shell:
1190 std::string singleQuote("'");
1191 std::string safeStatus = SanitizeString(strMessage);
1192 safeStatus = singleQuote+safeStatus+singleQuote;
1193 boost::replace_all(strCmd, "%s", safeStatus);
1195 boost::thread t(runCommand, strCmd); // thread runs free
1198 void CheckForkWarningConditions()
1200 AssertLockHeld(cs_main);
1201 // Before we get past initial download, we cannot reliably alert about forks
1202 // (we assume we don't get stuck on a fork before finishing our initial sync)
1203 if (IsInitialBlockDownload())
1204 return;
1206 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1207 // of our head, drop it
1208 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1209 pindexBestForkTip = NULL;
1211 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1213 if (!GetfLargeWorkForkFound() && pindexBestForkBase)
1215 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1216 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1217 AlertNotify(warning);
1219 if (pindexBestForkTip && pindexBestForkBase)
1221 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__,
1222 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1223 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1224 SetfLargeWorkForkFound(true);
1226 else
1228 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1229 SetfLargeWorkInvalidChainFound(true);
1232 else
1234 SetfLargeWorkForkFound(false);
1235 SetfLargeWorkInvalidChainFound(false);
1239 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1241 AssertLockHeld(cs_main);
1242 // If we are on a fork that is sufficiently large, set a warning flag
1243 CBlockIndex* pfork = pindexNewForkTip;
1244 CBlockIndex* plonger = chainActive.Tip();
1245 while (pfork && pfork != plonger)
1247 while (plonger && plonger->nHeight > pfork->nHeight)
1248 plonger = plonger->pprev;
1249 if (pfork == plonger)
1250 break;
1251 pfork = pfork->pprev;
1254 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1255 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1256 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1257 // hash rate operating on the fork.
1258 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1259 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1260 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1261 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1262 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1263 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1265 pindexBestForkTip = pindexNewForkTip;
1266 pindexBestForkBase = pfork;
1269 CheckForkWarningConditions();
1272 void static InvalidChainFound(CBlockIndex* pindexNew)
1274 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1275 pindexBestInvalid = pindexNew;
1277 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1278 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1279 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1280 pindexNew->GetBlockTime()));
1281 CBlockIndex *tip = chainActive.Tip();
1282 assert (tip);
1283 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1284 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1285 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1286 CheckForkWarningConditions();
1289 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1290 if (!state.CorruptionPossible()) {
1291 pindex->nStatus |= BLOCK_FAILED_VALID;
1292 setDirtyBlockIndex.insert(pindex);
1293 setBlockIndexCandidates.erase(pindex);
1294 InvalidChainFound(pindex);
1298 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1300 // mark inputs spent
1301 if (!tx.IsCoinBase()) {
1302 txundo.vprevout.reserve(tx.vin.size());
1303 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1304 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1305 unsigned nPos = txin.prevout.n;
1307 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1308 assert(false);
1309 // mark an outpoint spent, and construct undo information
1310 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1311 coins->Spend(nPos);
1312 if (coins->vout.size() == 0) {
1313 CTxInUndo& undo = txundo.vprevout.back();
1314 undo.nHeight = coins->nHeight;
1315 undo.fCoinBase = coins->fCoinBase;
1316 undo.nVersion = coins->nVersion;
1320 // add outputs
1321 inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1324 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1326 CTxUndo txundo;
1327 UpdateCoins(tx, inputs, txundo, nHeight);
1330 bool CScriptCheck::operator()() {
1331 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1332 const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1333 if (!VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error)) {
1334 return false;
1336 return true;
1339 int GetSpendHeight(const CCoinsViewCache& inputs)
1341 LOCK(cs_main);
1342 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1343 return pindexPrev->nHeight + 1;
1346 namespace Consensus {
1347 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1349 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1350 // for an attacker to attempt to split the network.
1351 if (!inputs.HaveInputs(tx))
1352 return state.Invalid(false, 0, "", "Inputs unavailable");
1354 CAmount nValueIn = 0;
1355 CAmount nFees = 0;
1356 for (unsigned int i = 0; i < tx.vin.size(); i++)
1358 const COutPoint &prevout = tx.vin[i].prevout;
1359 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1360 assert(coins);
1362 // If prev is coinbase, check that it's matured
1363 if (coins->IsCoinBase()) {
1364 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1365 return state.Invalid(false,
1366 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1367 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1370 // Check for negative or overflow input values
1371 nValueIn += coins->vout[prevout.n].nValue;
1372 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1373 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1377 if (nValueIn < tx.GetValueOut())
1378 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1379 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1381 // Tally transaction fees
1382 CAmount nTxFee = nValueIn - tx.GetValueOut();
1383 if (nTxFee < 0)
1384 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1385 nFees += nTxFee;
1386 if (!MoneyRange(nFees))
1387 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1388 return true;
1390 }// namespace Consensus
1392 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1394 if (!tx.IsCoinBase())
1396 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1397 return false;
1399 if (pvChecks)
1400 pvChecks->reserve(tx.vin.size());
1402 // The first loop above does all the inexpensive checks.
1403 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1404 // Helps prevent CPU exhaustion attacks.
1406 // Skip script verification when connecting blocks under the
1407 // assumevalid block. Assuming the assumevalid block is valid this
1408 // is safe because block merkle hashes are still computed and checked,
1409 // Of course, if an assumed valid block is invalid due to false scriptSigs
1410 // this optimization would allow an invalid chain to be accepted.
1411 if (fScriptChecks) {
1412 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1413 const COutPoint &prevout = tx.vin[i].prevout;
1414 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1415 assert(coins);
1417 // Verify signature
1418 CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1419 if (pvChecks) {
1420 pvChecks->push_back(CScriptCheck());
1421 check.swap(pvChecks->back());
1422 } else if (!check()) {
1423 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1424 // Check whether the failure was caused by a
1425 // non-mandatory script verification check, such as
1426 // non-standard DER encodings or non-null dummy
1427 // arguments; if so, don't trigger DoS protection to
1428 // avoid splitting the network between upgraded and
1429 // non-upgraded nodes.
1430 CScriptCheck check2(*coins, tx, i,
1431 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1432 if (check2())
1433 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1435 // Failures of other flags indicate a transaction that is
1436 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1437 // such nodes as they are not following the protocol. That
1438 // said during an upgrade careful thought should be taken
1439 // as to the correct behavior - we may want to continue
1440 // peering with non-upgraded nodes even after soft-fork
1441 // super-majority signaling has occurred.
1442 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1448 return true;
1451 namespace {
1453 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1455 // Open history file to append
1456 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1457 if (fileout.IsNull())
1458 return error("%s: OpenUndoFile failed", __func__);
1460 // Write index header
1461 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1462 fileout << FLATDATA(messageStart) << nSize;
1464 // Write undo data
1465 long fileOutPos = ftell(fileout.Get());
1466 if (fileOutPos < 0)
1467 return error("%s: ftell failed", __func__);
1468 pos.nPos = (unsigned int)fileOutPos;
1469 fileout << blockundo;
1471 // calculate & write checksum
1472 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1473 hasher << hashBlock;
1474 hasher << blockundo;
1475 fileout << hasher.GetHash();
1477 return true;
1480 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1482 // Open history file to read
1483 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1484 if (filein.IsNull())
1485 return error("%s: OpenUndoFile failed", __func__);
1487 // Read block
1488 uint256 hashChecksum;
1489 try {
1490 filein >> blockundo;
1491 filein >> hashChecksum;
1493 catch (const std::exception& e) {
1494 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1497 // Verify checksum
1498 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1499 hasher << hashBlock;
1500 hasher << blockundo;
1501 if (hashChecksum != hasher.GetHash())
1502 return error("%s: Checksum mismatch", __func__);
1504 return true;
1507 /** Abort with a message */
1508 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1510 SetMiscWarning(strMessage);
1511 LogPrintf("*** %s\n", strMessage);
1512 uiInterface.ThreadSafeMessageBox(
1513 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1514 "", CClientUIInterface::MSG_ERROR);
1515 StartShutdown();
1516 return false;
1519 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1521 AbortNode(strMessage, userMessage);
1522 return state.Error(strMessage);
1525 } // anon namespace
1528 * Apply the undo operation of a CTxInUndo to the given chain state.
1529 * @param undo The undo object.
1530 * @param view The coins view to which to apply the changes.
1531 * @param out The out point that corresponds to the tx input.
1532 * @return True on success.
1534 bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1536 bool fClean = true;
1538 CCoinsModifier coins = view.ModifyCoins(out.hash);
1539 if (undo.nHeight != 0) {
1540 // undo data contains height: this is the last output of the prevout tx being spent
1541 if (!coins->IsPruned())
1542 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1543 coins->Clear();
1544 coins->fCoinBase = undo.fCoinBase;
1545 coins->nHeight = undo.nHeight;
1546 coins->nVersion = undo.nVersion;
1547 } else {
1548 if (coins->IsPruned())
1549 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1551 if (coins->IsAvailable(out.n))
1552 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1553 if (coins->vout.size() < out.n+1)
1554 coins->vout.resize(out.n+1);
1555 coins->vout[out.n] = undo.txout;
1557 return fClean;
1560 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1562 assert(pindex->GetBlockHash() == view.GetBestBlock());
1564 if (pfClean)
1565 *pfClean = false;
1567 bool fClean = true;
1569 CBlockUndo blockUndo;
1570 CDiskBlockPos pos = pindex->GetUndoPos();
1571 if (pos.IsNull())
1572 return error("DisconnectBlock(): no undo data available");
1573 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1574 return error("DisconnectBlock(): failure reading undo data");
1576 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1577 return error("DisconnectBlock(): block and undo data inconsistent");
1579 // undo transactions in reverse order
1580 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1581 const CTransaction &tx = *(block.vtx[i]);
1582 uint256 hash = tx.GetHash();
1584 // Check that all outputs are available and match the outputs in the block itself
1585 // exactly.
1587 CCoinsModifier outs = view.ModifyCoins(hash);
1588 outs->ClearUnspendable();
1590 CCoins outsBlock(tx, pindex->nHeight);
1591 // The CCoins serialization does not serialize negative numbers.
1592 // No network rules currently depend on the version here, so an inconsistency is harmless
1593 // but it must be corrected before txout nversion ever influences a network rule.
1594 if (outsBlock.nVersion < 0)
1595 outs->nVersion = outsBlock.nVersion;
1596 if (*outs != outsBlock)
1597 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1599 // remove outputs
1600 outs->Clear();
1603 // restore inputs
1604 if (i > 0) { // not coinbases
1605 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1606 if (txundo.vprevout.size() != tx.vin.size())
1607 return error("DisconnectBlock(): transaction and undo data inconsistent");
1608 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1609 const COutPoint &out = tx.vin[j].prevout;
1610 const CTxInUndo &undo = txundo.vprevout[j];
1611 if (!ApplyTxInUndo(undo, view, out))
1612 fClean = false;
1617 // move best block pointer to prevout block
1618 view.SetBestBlock(pindex->pprev->GetBlockHash());
1620 if (pfClean) {
1621 *pfClean = fClean;
1622 return true;
1625 return fClean;
1628 void static FlushBlockFile(bool fFinalize = false)
1630 LOCK(cs_LastBlockFile);
1632 CDiskBlockPos posOld(nLastBlockFile, 0);
1634 FILE *fileOld = OpenBlockFile(posOld);
1635 if (fileOld) {
1636 if (fFinalize)
1637 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1638 FileCommit(fileOld);
1639 fclose(fileOld);
1642 fileOld = OpenUndoFile(posOld);
1643 if (fileOld) {
1644 if (fFinalize)
1645 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1646 FileCommit(fileOld);
1647 fclose(fileOld);
1651 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1653 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1655 void ThreadScriptCheck() {
1656 RenameThread("bitcoin-scriptch");
1657 scriptcheckqueue.Thread();
1660 // Protected by cs_main
1661 VersionBitsCache versionbitscache;
1663 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1665 LOCK(cs_main);
1666 int32_t nVersion = VERSIONBITS_TOP_BITS;
1668 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1669 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1670 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1671 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1675 return nVersion;
1679 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1681 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1683 private:
1684 int bit;
1686 public:
1687 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1689 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1690 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1691 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1692 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1694 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1696 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1697 ((pindex->nVersion >> bit) & 1) != 0 &&
1698 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1702 // Protected by cs_main
1703 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1705 static int64_t nTimeCheck = 0;
1706 static int64_t nTimeForks = 0;
1707 static int64_t nTimeVerify = 0;
1708 static int64_t nTimeConnect = 0;
1709 static int64_t nTimeIndex = 0;
1710 static int64_t nTimeCallbacks = 0;
1711 static int64_t nTimeTotal = 0;
1713 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1714 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1716 AssertLockHeld(cs_main);
1717 assert(pindex);
1718 // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1719 assert((pindex->phashBlock == NULL) ||
1720 (*pindex->phashBlock == block.GetHash()));
1721 int64_t nTimeStart = GetTimeMicros();
1723 // Check it again in case a previous version let a bad block in
1724 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1725 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1727 // verify that the view's current state corresponds to the previous block
1728 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1729 assert(hashPrevBlock == view.GetBestBlock());
1731 // Special case for the genesis block, skipping connection of its transactions
1732 // (its coinbase is unspendable)
1733 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1734 if (!fJustCheck)
1735 view.SetBestBlock(pindex->GetBlockHash());
1736 return true;
1739 bool fScriptChecks = true;
1740 if (!hashAssumeValid.IsNull()) {
1741 // We've been configured with the hash of a block which has been externally verified to have a valid history.
1742 // A suitable default value is included with the software and updated from time to time. Because validity
1743 // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1744 // This setting doesn't force the selection of any particular chain but makes validating some faster by
1745 // effectively caching the result of part of the verification.
1746 BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1747 if (it != mapBlockIndex.end()) {
1748 if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1749 pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1750 pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1751 // This block is a member of the assumed verified chain and an ancestor of the best header.
1752 // The equivalent time check discourages hash power from extorting the network via DOS attack
1753 // into accepting an invalid block through telling users they must manually set assumevalid.
1754 // Requiring a software change or burying the invalid block, regardless of the setting, makes
1755 // it hard to hide the implication of the demand. This also avoids having release candidates
1756 // that are hardly doing any signature verification at all in testing without having to
1757 // artificially set the default assumed verified block further back.
1758 // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1759 // least as good as the expected chain.
1760 fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1765 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1766 LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1768 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1769 // unless those are already completely spent.
1770 // If such overwrites are allowed, coinbases and transactions depending upon those
1771 // can be duplicated to remove the ability to spend the first instance -- even after
1772 // being sent to another address.
1773 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1774 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1775 // already refuses previously-known transaction ids entirely.
1776 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1777 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1778 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1779 // initial block download.
1780 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1781 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1782 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1784 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1785 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1786 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1787 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1788 // duplicate transactions descending from the known pairs either.
1789 // 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.
1790 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1791 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1792 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1794 if (fEnforceBIP30) {
1795 for (const auto& tx : block.vtx) {
1796 const CCoins* coins = view.AccessCoins(tx->GetHash());
1797 if (coins && !coins->IsPruned())
1798 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1799 REJECT_INVALID, "bad-txns-BIP30");
1803 // BIP16 didn't become active until Apr 1 2012
1804 int64_t nBIP16SwitchTime = 1333238400;
1805 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1807 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1809 // Start enforcing the DERSIG (BIP66) rule
1810 if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
1811 flags |= SCRIPT_VERIFY_DERSIG;
1814 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1815 if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
1816 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1819 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1820 int nLockTimeFlags = 0;
1821 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1822 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1823 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1826 // Start enforcing WITNESS rules using versionbits logic.
1827 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) {
1828 flags |= SCRIPT_VERIFY_WITNESS;
1829 flags |= SCRIPT_VERIFY_NULLDUMMY;
1832 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1833 LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1835 CBlockUndo blockundo;
1837 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1839 std::vector<int> prevheights;
1840 CAmount nFees = 0;
1841 int nInputs = 0;
1842 int64_t nSigOpsCost = 0;
1843 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1844 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1845 vPos.reserve(block.vtx.size());
1846 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1847 std::vector<PrecomputedTransactionData> txdata;
1848 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1849 for (unsigned int i = 0; i < block.vtx.size(); i++)
1851 const CTransaction &tx = *(block.vtx[i]);
1853 nInputs += tx.vin.size();
1855 if (!tx.IsCoinBase())
1857 if (!view.HaveInputs(tx))
1858 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1859 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1861 // Check that transaction is BIP68 final
1862 // BIP68 lock checks (as opposed to nLockTime checks) must
1863 // be in ConnectBlock because they require the UTXO set
1864 prevheights.resize(tx.vin.size());
1865 for (size_t j = 0; j < tx.vin.size(); j++) {
1866 prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
1869 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1870 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1871 REJECT_INVALID, "bad-txns-nonfinal");
1875 // GetTransactionSigOpCost counts 3 types of sigops:
1876 // * legacy (always)
1877 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1878 // * witness (when witness enabled in flags and excludes coinbase)
1879 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1880 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1881 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1882 REJECT_INVALID, "bad-blk-sigops");
1884 txdata.emplace_back(tx);
1885 if (!tx.IsCoinBase())
1887 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1889 std::vector<CScriptCheck> vChecks;
1890 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1891 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1892 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1893 tx.GetHash().ToString(), FormatStateMessage(state));
1894 control.Add(vChecks);
1897 CTxUndo undoDummy;
1898 if (i > 0) {
1899 blockundo.vtxundo.push_back(CTxUndo());
1901 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1903 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1904 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1906 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1907 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
1909 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1910 if (block.vtx[0]->GetValueOut() > blockReward)
1911 return state.DoS(100,
1912 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1913 block.vtx[0]->GetValueOut(), blockReward),
1914 REJECT_INVALID, "bad-cb-amount");
1916 if (!control.Wait())
1917 return state.DoS(100, false);
1918 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1919 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
1921 if (fJustCheck)
1922 return true;
1924 // Write undo information to disk
1925 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1927 if (pindex->GetUndoPos().IsNull()) {
1928 CDiskBlockPos _pos;
1929 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1930 return error("ConnectBlock(): FindUndoPos failed");
1931 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1932 return AbortNode(state, "Failed to write undo data");
1934 // update nUndoPos in block index
1935 pindex->nUndoPos = _pos.nPos;
1936 pindex->nStatus |= BLOCK_HAVE_UNDO;
1939 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1940 setDirtyBlockIndex.insert(pindex);
1943 if (fTxIndex)
1944 if (!pblocktree->WriteTxIndex(vPos))
1945 return AbortNode(state, "Failed to write transaction index");
1947 // add this block to the view's block chain
1948 view.SetBestBlock(pindex->GetBlockHash());
1950 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1951 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1953 // Watch for changes to the previous coinbase transaction.
1954 static uint256 hashPrevBestCoinBase;
1955 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1956 hashPrevBestCoinBase = block.vtx[0]->GetHash();
1959 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1960 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1962 return true;
1966 * Update the on-disk chain state.
1967 * The caches and indexes are flushed depending on the mode we're called with
1968 * if they're too large, if it's been a while since the last write,
1969 * or always and in all cases if we're in prune mode and are deleting files.
1971 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
1972 int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
1973 const CChainParams& chainparams = Params();
1974 LOCK2(cs_main, cs_LastBlockFile);
1975 static int64_t nLastWrite = 0;
1976 static int64_t nLastFlush = 0;
1977 static int64_t nLastSetChain = 0;
1978 std::set<int> setFilesToPrune;
1979 bool fFlushForPrune = false;
1980 try {
1981 if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
1982 if (nManualPruneHeight > 0) {
1983 FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
1984 } else {
1985 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1986 fCheckForPruning = false;
1988 if (!setFilesToPrune.empty()) {
1989 fFlushForPrune = true;
1990 if (!fHavePruned) {
1991 pblocktree->WriteFlag("prunedblockfiles", true);
1992 fHavePruned = true;
1996 int64_t nNow = GetTimeMicros();
1997 // Avoid writing/flushing immediately after startup.
1998 if (nLastWrite == 0) {
1999 nLastWrite = nNow;
2001 if (nLastFlush == 0) {
2002 nLastFlush = nNow;
2004 if (nLastSetChain == 0) {
2005 nLastSetChain = nNow;
2007 int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2008 int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2009 int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2010 // The cache is large and we're within 10% and 100 MiB of the limit, but we have time now (not in the middle of a block processing).
2011 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - 100 * 1024 * 1024);
2012 // The cache is over the limit, we have to write now.
2013 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
2014 // 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.
2015 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2016 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2017 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2018 // Combine all conditions that result in a full cache flush.
2019 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2020 // Write blocks and block index to disk.
2021 if (fDoFullFlush || fPeriodicWrite) {
2022 // Depend on nMinDiskSpace to ensure we can write block index
2023 if (!CheckDiskSpace(0))
2024 return state.Error("out of disk space");
2025 // First make sure all block and undo data is flushed to disk.
2026 FlushBlockFile();
2027 // Then update all block file information (which may refer to block and undo files).
2029 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2030 vFiles.reserve(setDirtyFileInfo.size());
2031 for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2032 vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2033 setDirtyFileInfo.erase(it++);
2035 std::vector<const CBlockIndex*> vBlocks;
2036 vBlocks.reserve(setDirtyBlockIndex.size());
2037 for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2038 vBlocks.push_back(*it);
2039 setDirtyBlockIndex.erase(it++);
2041 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2042 return AbortNode(state, "Failed to write to block index database");
2045 // Finally remove any pruned files
2046 if (fFlushForPrune)
2047 UnlinkPrunedFiles(setFilesToPrune);
2048 nLastWrite = nNow;
2050 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2051 if (fDoFullFlush) {
2052 // Typical CCoins structures on disk are around 128 bytes in size.
2053 // Pushing a new one to the database can cause it to be written
2054 // twice (once in the log, and once in the tables). This is already
2055 // an overestimation, as most will delete an existing entry or
2056 // overwrite one. Still, use a conservative safety factor of 2.
2057 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2058 return state.Error("out of disk space");
2059 // Flush the chainstate (which may refer to block index entries).
2060 if (!pcoinsTip->Flush())
2061 return AbortNode(state, "Failed to write to coin database");
2062 nLastFlush = nNow;
2064 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2065 // Update best block in wallet (so we can detect restored wallets).
2066 GetMainSignals().SetBestChain(chainActive.GetLocator());
2067 nLastSetChain = nNow;
2069 } catch (const std::runtime_error& e) {
2070 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2072 return true;
2075 void FlushStateToDisk() {
2076 CValidationState state;
2077 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2080 void PruneAndFlush() {
2081 CValidationState state;
2082 fCheckForPruning = true;
2083 FlushStateToDisk(state, FLUSH_STATE_NONE);
2086 /** Update chainActive and related internal data structures. */
2087 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2088 chainActive.SetTip(pindexNew);
2090 // New best block
2091 mempool.AddTransactionsUpdated(1);
2093 cvBlockChange.notify_all();
2095 static bool fWarned = false;
2096 std::vector<std::string> warningMessages;
2097 if (!IsInitialBlockDownload())
2099 int nUpgraded = 0;
2100 const CBlockIndex* pindex = chainActive.Tip();
2101 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2102 WarningBitsConditionChecker checker(bit);
2103 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2104 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2105 if (state == THRESHOLD_ACTIVE) {
2106 std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2107 SetMiscWarning(strWarning);
2108 if (!fWarned) {
2109 AlertNotify(strWarning);
2110 fWarned = true;
2112 } else {
2113 warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
2117 // Check the version of the last 100 blocks to see if we need to upgrade:
2118 for (int i = 0; i < 100 && pindex != NULL; i++)
2120 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2121 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2122 ++nUpgraded;
2123 pindex = pindex->pprev;
2125 if (nUpgraded > 0)
2126 warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
2127 if (nUpgraded > 100/2)
2129 std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2130 // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2131 SetMiscWarning(strWarning);
2132 if (!fWarned) {
2133 AlertNotify(strWarning);
2134 fWarned = true;
2138 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
2139 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2140 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2141 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2142 GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2143 if (!warningMessages.empty())
2144 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2145 LogPrintf("\n");
2149 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
2150 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
2152 CBlockIndex *pindexDelete = chainActive.Tip();
2153 assert(pindexDelete);
2154 // Read block from disk.
2155 CBlock block;
2156 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2157 return AbortNode(state, "Failed to read block");
2158 // Apply the block atomically to the chain state.
2159 int64_t nStart = GetTimeMicros();
2161 CCoinsViewCache view(pcoinsTip);
2162 if (!DisconnectBlock(block, state, pindexDelete, view))
2163 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2164 bool flushed = view.Flush();
2165 assert(flushed);
2167 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2168 // Write the chain state to disk, if necessary.
2169 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2170 return false;
2172 if (!fBare) {
2173 // Resurrect mempool transactions from the disconnected block.
2174 std::vector<uint256> vHashUpdate;
2175 for (const auto& it : block.vtx) {
2176 const CTransaction& tx = *it;
2177 // ignore validation errors in resurrected transactions
2178 CValidationState stateDummy;
2179 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
2180 mempool.removeRecursive(tx, MemPoolRemovalReason::REORG);
2181 } else if (mempool.exists(tx.GetHash())) {
2182 vHashUpdate.push_back(tx.GetHash());
2185 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2186 // no in-mempool children, which is generally not true when adding
2187 // previously-confirmed transactions back to the mempool.
2188 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2189 // block that were added back and cleans up the mempool state.
2190 mempool.UpdateTransactionsFromBlock(vHashUpdate);
2193 // Update chainActive and related variables.
2194 UpdateTip(pindexDelete->pprev, chainparams);
2195 // Let wallets know transactions went from 1-confirmed to
2196 // 0-confirmed or conflicted:
2197 for (const auto& tx : block.vtx) {
2198 GetMainSignals().SyncTransaction(*tx, pindexDelete->pprev, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
2200 return true;
2203 static int64_t nTimeReadFromDisk = 0;
2204 static int64_t nTimeConnectTotal = 0;
2205 static int64_t nTimeFlush = 0;
2206 static int64_t nTimeChainState = 0;
2207 static int64_t nTimePostConnect = 0;
2210 * Used to track blocks whose transactions were applied to the UTXO state as a
2211 * part of a single ActivateBestChainStep call.
2213 struct ConnectTrace {
2214 std::vector<std::pair<CBlockIndex*, std::shared_ptr<const CBlock> > > blocksConnected;
2218 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2219 * corresponding to pindexNew, to bypass loading it again from disk.
2221 * The block is always added to connectTrace (either after loading from disk or by copying
2222 * pblock) - if that is not intended, care must be taken to remove the last entry in
2223 * blocksConnected in case of failure.
2225 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2227 assert(pindexNew->pprev == chainActive.Tip());
2228 // Read block from disk.
2229 int64_t nTime1 = GetTimeMicros();
2230 if (!pblock) {
2231 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2232 connectTrace.blocksConnected.emplace_back(pindexNew, pblockNew);
2233 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2234 return AbortNode(state, "Failed to read block");
2235 } else {
2236 connectTrace.blocksConnected.emplace_back(pindexNew, pblock);
2238 const CBlock& blockConnecting = *connectTrace.blocksConnected.back().second;
2239 // Apply the block atomically to the chain state.
2240 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2241 int64_t nTime3;
2242 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2244 CCoinsViewCache view(pcoinsTip);
2245 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2246 GetMainSignals().BlockChecked(blockConnecting, state);
2247 if (!rv) {
2248 if (state.IsInvalid())
2249 InvalidBlockFound(pindexNew, state);
2250 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2252 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2253 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2254 bool flushed = view.Flush();
2255 assert(flushed);
2257 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2258 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2259 // Write the chain state to disk, if necessary.
2260 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2261 return false;
2262 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2263 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2264 // Remove conflicting transactions from the mempool.;
2265 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2266 // Update chainActive & related variables.
2267 UpdateTip(pindexNew, chainparams);
2269 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2270 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2271 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2272 return true;
2276 * Return the tip of the chain with the most work in it, that isn't
2277 * known to be invalid (it's however far from certain to be valid).
2279 static CBlockIndex* FindMostWorkChain() {
2280 do {
2281 CBlockIndex *pindexNew = NULL;
2283 // Find the best candidate header.
2285 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2286 if (it == setBlockIndexCandidates.rend())
2287 return NULL;
2288 pindexNew = *it;
2291 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2292 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2293 CBlockIndex *pindexTest = pindexNew;
2294 bool fInvalidAncestor = false;
2295 while (pindexTest && !chainActive.Contains(pindexTest)) {
2296 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2298 // Pruned nodes may have entries in setBlockIndexCandidates for
2299 // which block files have been deleted. Remove those as candidates
2300 // for the most work chain if we come across them; we can't switch
2301 // to a chain unless we have all the non-active-chain parent blocks.
2302 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2303 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2304 if (fFailedChain || fMissingData) {
2305 // Candidate chain is not usable (either invalid or missing data)
2306 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2307 pindexBestInvalid = pindexNew;
2308 CBlockIndex *pindexFailed = pindexNew;
2309 // Remove the entire chain from the set.
2310 while (pindexTest != pindexFailed) {
2311 if (fFailedChain) {
2312 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2313 } else if (fMissingData) {
2314 // If we're missing data, then add back to mapBlocksUnlinked,
2315 // so that if the block arrives in the future we can try adding
2316 // to setBlockIndexCandidates again.
2317 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2319 setBlockIndexCandidates.erase(pindexFailed);
2320 pindexFailed = pindexFailed->pprev;
2322 setBlockIndexCandidates.erase(pindexTest);
2323 fInvalidAncestor = true;
2324 break;
2326 pindexTest = pindexTest->pprev;
2328 if (!fInvalidAncestor)
2329 return pindexNew;
2330 } while(true);
2333 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2334 static void PruneBlockIndexCandidates() {
2335 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2336 // reorganization to a better block fails.
2337 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2338 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2339 setBlockIndexCandidates.erase(it++);
2341 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2342 assert(!setBlockIndexCandidates.empty());
2346 * Try to make some progress towards making pindexMostWork the active block.
2347 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2349 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2351 AssertLockHeld(cs_main);
2352 const CBlockIndex *pindexOldTip = chainActive.Tip();
2353 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2355 // Disconnect active blocks which are no longer in the best chain.
2356 bool fBlocksDisconnected = false;
2357 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2358 if (!DisconnectTip(state, chainparams))
2359 return false;
2360 fBlocksDisconnected = true;
2363 // Build list of new blocks to connect.
2364 std::vector<CBlockIndex*> vpindexToConnect;
2365 bool fContinue = true;
2366 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2367 while (fContinue && nHeight != pindexMostWork->nHeight) {
2368 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2369 // a few blocks along the way.
2370 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2371 vpindexToConnect.clear();
2372 vpindexToConnect.reserve(nTargetHeight - nHeight);
2373 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2374 while (pindexIter && pindexIter->nHeight != nHeight) {
2375 vpindexToConnect.push_back(pindexIter);
2376 pindexIter = pindexIter->pprev;
2378 nHeight = nTargetHeight;
2380 // Connect new blocks.
2381 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2382 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2383 if (state.IsInvalid()) {
2384 // The block violates a consensus rule.
2385 if (!state.CorruptionPossible())
2386 InvalidChainFound(vpindexToConnect.back());
2387 state = CValidationState();
2388 fInvalidFound = true;
2389 fContinue = false;
2390 // If we didn't actually connect the block, don't notify listeners about it
2391 connectTrace.blocksConnected.pop_back();
2392 break;
2393 } else {
2394 // A system error occurred (disk space, database error, ...).
2395 return false;
2397 } else {
2398 PruneBlockIndexCandidates();
2399 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2400 // We're in a better position than we were. Return temporarily to release the lock.
2401 fContinue = false;
2402 break;
2408 if (fBlocksDisconnected) {
2409 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2410 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2412 mempool.check(pcoinsTip);
2414 // Callbacks/notifications for a new best chain.
2415 if (fInvalidFound)
2416 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2417 else
2418 CheckForkWarningConditions();
2420 return true;
2423 static void NotifyHeaderTip() {
2424 bool fNotify = false;
2425 bool fInitialBlockDownload = false;
2426 static CBlockIndex* pindexHeaderOld = NULL;
2427 CBlockIndex* pindexHeader = NULL;
2429 LOCK(cs_main);
2430 pindexHeader = pindexBestHeader;
2432 if (pindexHeader != pindexHeaderOld) {
2433 fNotify = true;
2434 fInitialBlockDownload = IsInitialBlockDownload();
2435 pindexHeaderOld = pindexHeader;
2438 // Send block tip changed notifications without cs_main
2439 if (fNotify) {
2440 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2445 * Make the best chain active, in multiple steps. The result is either failure
2446 * or an activated best chain. pblock is either NULL or a pointer to a block
2447 * that is already loaded (to avoid loading it again from disk).
2449 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2450 // Note that while we're often called here from ProcessNewBlock, this is
2451 // far from a guarantee. Things in the P2P/RPC will often end up calling
2452 // us in the middle of ProcessNewBlock - do not assume pblock is set
2453 // sanely for performance or correctness!
2455 CBlockIndex *pindexMostWork = NULL;
2456 CBlockIndex *pindexNewTip = NULL;
2457 do {
2458 boost::this_thread::interruption_point();
2459 if (ShutdownRequested())
2460 break;
2462 const CBlockIndex *pindexFork;
2463 ConnectTrace connectTrace;
2464 bool fInitialDownload;
2466 LOCK(cs_main);
2467 { // TODO: Temporarily ensure that mempool removals are notified before
2468 // connected transactions. This shouldn't matter, but the abandoned
2469 // state of transactions in our wallet is currently cleared when we
2470 // receive another notification and there is a race condition where
2471 // notification of a connected conflict might cause an outside process
2472 // to abandon a transaction and then have it inadvertently cleared by
2473 // the notification that the conflicted transaction was evicted.
2474 MemPoolConflictRemovalTracker mrt(mempool);
2475 CBlockIndex *pindexOldTip = chainActive.Tip();
2476 if (pindexMostWork == NULL) {
2477 pindexMostWork = FindMostWorkChain();
2480 // Whether we have anything to do at all.
2481 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2482 return true;
2484 bool fInvalidFound = false;
2485 std::shared_ptr<const CBlock> nullBlockPtr;
2486 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2487 return false;
2489 if (fInvalidFound) {
2490 // Wipe cache, we may need another branch now.
2491 pindexMostWork = NULL;
2493 pindexNewTip = chainActive.Tip();
2494 pindexFork = chainActive.FindFork(pindexOldTip);
2495 fInitialDownload = IsInitialBlockDownload();
2497 // throw all transactions though the signal-interface
2499 } // MemPoolConflictRemovalTracker destroyed and conflict evictions are notified
2501 // Transactions in the connected block are notified
2502 for (const auto& pair : connectTrace.blocksConnected) {
2503 assert(pair.second);
2504 const CBlock& block = *(pair.second);
2505 for (unsigned int i = 0; i < block.vtx.size(); i++)
2506 GetMainSignals().SyncTransaction(*block.vtx[i], pair.first, i);
2509 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2511 // Notifications/callbacks that can run without cs_main
2513 // Notify external listeners about the new tip.
2514 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2516 // Always notify the UI if a new block tip was connected
2517 if (pindexFork != pindexNewTip) {
2518 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2520 } while (pindexNewTip != pindexMostWork);
2521 CheckBlockIndex(chainparams.GetConsensus());
2523 // Write changes periodically to disk, after relay.
2524 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2525 return false;
2528 return true;
2532 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2535 LOCK(cs_main);
2536 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2537 // Nothing to do, this block is not at the tip.
2538 return true;
2540 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2541 // The chain has been extended since the last call, reset the counter.
2542 nBlockReverseSequenceId = -1;
2544 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2545 setBlockIndexCandidates.erase(pindex);
2546 pindex->nSequenceId = nBlockReverseSequenceId;
2547 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2548 // We can't keep reducing the counter if somebody really wants to
2549 // call preciousblock 2**31-1 times on the same set of tips...
2550 nBlockReverseSequenceId--;
2552 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2553 setBlockIndexCandidates.insert(pindex);
2554 PruneBlockIndexCandidates();
2558 return ActivateBestChain(state, params);
2561 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2563 AssertLockHeld(cs_main);
2565 // Mark the block itself as invalid.
2566 pindex->nStatus |= BLOCK_FAILED_VALID;
2567 setDirtyBlockIndex.insert(pindex);
2568 setBlockIndexCandidates.erase(pindex);
2570 while (chainActive.Contains(pindex)) {
2571 CBlockIndex *pindexWalk = chainActive.Tip();
2572 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2573 setDirtyBlockIndex.insert(pindexWalk);
2574 setBlockIndexCandidates.erase(pindexWalk);
2575 // ActivateBestChain considers blocks already in chainActive
2576 // unconditionally valid already, so force disconnect away from it.
2577 if (!DisconnectTip(state, chainparams)) {
2578 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2579 return false;
2583 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2585 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2586 // add it again.
2587 BlockMap::iterator it = mapBlockIndex.begin();
2588 while (it != mapBlockIndex.end()) {
2589 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2590 setBlockIndexCandidates.insert(it->second);
2592 it++;
2595 InvalidChainFound(pindex);
2596 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2597 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2598 return true;
2601 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2602 AssertLockHeld(cs_main);
2604 int nHeight = pindex->nHeight;
2606 // Remove the invalidity flag from this block and all its descendants.
2607 BlockMap::iterator it = mapBlockIndex.begin();
2608 while (it != mapBlockIndex.end()) {
2609 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2610 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2611 setDirtyBlockIndex.insert(it->second);
2612 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2613 setBlockIndexCandidates.insert(it->second);
2615 if (it->second == pindexBestInvalid) {
2616 // Reset invalid block marker if it was pointing to one of those.
2617 pindexBestInvalid = NULL;
2620 it++;
2623 // Remove the invalidity flag from all ancestors too.
2624 while (pindex != NULL) {
2625 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2626 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2627 setDirtyBlockIndex.insert(pindex);
2629 pindex = pindex->pprev;
2631 return true;
2634 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2636 // Check for duplicate
2637 uint256 hash = block.GetHash();
2638 BlockMap::iterator it = mapBlockIndex.find(hash);
2639 if (it != mapBlockIndex.end())
2640 return it->second;
2642 // Construct new block index object
2643 CBlockIndex* pindexNew = new CBlockIndex(block);
2644 assert(pindexNew);
2645 // We assign the sequence id to blocks only when the full data is available,
2646 // to avoid miners withholding blocks but broadcasting headers, to get a
2647 // competitive advantage.
2648 pindexNew->nSequenceId = 0;
2649 BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2650 pindexNew->phashBlock = &((*mi).first);
2651 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2652 if (miPrev != mapBlockIndex.end())
2654 pindexNew->pprev = (*miPrev).second;
2655 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2656 pindexNew->BuildSkip();
2658 pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2659 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2660 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2661 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2662 pindexBestHeader = pindexNew;
2664 setDirtyBlockIndex.insert(pindexNew);
2666 return pindexNew;
2669 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2670 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2672 pindexNew->nTx = block.vtx.size();
2673 pindexNew->nChainTx = 0;
2674 pindexNew->nFile = pos.nFile;
2675 pindexNew->nDataPos = pos.nPos;
2676 pindexNew->nUndoPos = 0;
2677 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2678 if (IsWitnessEnabled(pindexNew->pprev, Params().GetConsensus())) {
2679 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2681 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2682 setDirtyBlockIndex.insert(pindexNew);
2684 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2685 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2686 std::deque<CBlockIndex*> queue;
2687 queue.push_back(pindexNew);
2689 // Recursively process any descendant blocks that now may be eligible to be connected.
2690 while (!queue.empty()) {
2691 CBlockIndex *pindex = queue.front();
2692 queue.pop_front();
2693 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2695 LOCK(cs_nBlockSequenceId);
2696 pindex->nSequenceId = nBlockSequenceId++;
2698 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2699 setBlockIndexCandidates.insert(pindex);
2701 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2702 while (range.first != range.second) {
2703 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2704 queue.push_back(it->second);
2705 range.first++;
2706 mapBlocksUnlinked.erase(it);
2709 } else {
2710 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2711 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2715 return true;
2718 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2720 LOCK(cs_LastBlockFile);
2722 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2723 if (vinfoBlockFile.size() <= nFile) {
2724 vinfoBlockFile.resize(nFile + 1);
2727 if (!fKnown) {
2728 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2729 nFile++;
2730 if (vinfoBlockFile.size() <= nFile) {
2731 vinfoBlockFile.resize(nFile + 1);
2734 pos.nFile = nFile;
2735 pos.nPos = vinfoBlockFile[nFile].nSize;
2738 if ((int)nFile != nLastBlockFile) {
2739 if (!fKnown) {
2740 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2742 FlushBlockFile(!fKnown);
2743 nLastBlockFile = nFile;
2746 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2747 if (fKnown)
2748 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2749 else
2750 vinfoBlockFile[nFile].nSize += nAddSize;
2752 if (!fKnown) {
2753 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2754 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2755 if (nNewChunks > nOldChunks) {
2756 if (fPruneMode)
2757 fCheckForPruning = true;
2758 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2759 FILE *file = OpenBlockFile(pos);
2760 if (file) {
2761 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2762 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2763 fclose(file);
2766 else
2767 return state.Error("out of disk space");
2771 setDirtyFileInfo.insert(nFile);
2772 return true;
2775 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2777 pos.nFile = nFile;
2779 LOCK(cs_LastBlockFile);
2781 unsigned int nNewSize;
2782 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2783 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2784 setDirtyFileInfo.insert(nFile);
2786 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2787 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2788 if (nNewChunks > nOldChunks) {
2789 if (fPruneMode)
2790 fCheckForPruning = true;
2791 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2792 FILE *file = OpenUndoFile(pos);
2793 if (file) {
2794 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2795 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2796 fclose(file);
2799 else
2800 return state.Error("out of disk space");
2803 return true;
2806 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW)
2808 // Check proof of work matches claimed amount
2809 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2810 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2812 return true;
2815 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2817 // These are checks that are independent of context.
2819 if (block.fChecked)
2820 return true;
2822 // Check that the header is valid (particularly PoW). This is mostly
2823 // redundant with the call in AcceptBlockHeader.
2824 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2825 return false;
2827 // Check the merkle root.
2828 if (fCheckMerkleRoot) {
2829 bool mutated;
2830 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2831 if (block.hashMerkleRoot != hashMerkleRoot2)
2832 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2834 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2835 // of transactions in a block without affecting the merkle root of a block,
2836 // while still invalidating it.
2837 if (mutated)
2838 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2841 // All potential-corruption validation must be done before we do any
2842 // transaction validation, as otherwise we may mark the header as invalid
2843 // because we receive the wrong transactions for it.
2844 // Note that witness malleability is checked in ContextualCheckBlock, so no
2845 // checks that use witness data may be performed here.
2847 // Size limits
2848 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_BASE_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
2849 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2851 // First transaction must be coinbase, the rest must not be
2852 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2853 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2854 for (unsigned int i = 1; i < block.vtx.size(); i++)
2855 if (block.vtx[i]->IsCoinBase())
2856 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2858 // Check transactions
2859 for (const auto& tx : block.vtx)
2860 if (!CheckTransaction(*tx, state, false))
2861 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2862 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2864 unsigned int nSigOps = 0;
2865 for (const auto& tx : block.vtx)
2867 nSigOps += GetLegacySigOpCount(*tx);
2869 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2870 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2872 if (fCheckPOW && fCheckMerkleRoot)
2873 block.fChecked = true;
2875 return true;
2878 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2880 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2881 return true;
2883 int nHeight = pindexPrev->nHeight+1;
2884 // Don't accept any forks from the main chain prior to last checkpoint
2885 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2886 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2887 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2889 return true;
2892 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2894 LOCK(cs_main);
2895 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2898 // Compute at which vout of the block's coinbase transaction the witness
2899 // commitment occurs, or -1 if not found.
2900 static int GetWitnessCommitmentIndex(const CBlock& block)
2902 int commitpos = -1;
2903 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2904 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) {
2905 commitpos = o;
2908 return commitpos;
2911 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2913 int commitpos = GetWitnessCommitmentIndex(block);
2914 static const std::vector<unsigned char> nonce(32, 0x00);
2915 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2916 CMutableTransaction tx(*block.vtx[0]);
2917 tx.vin[0].scriptWitness.stack.resize(1);
2918 tx.vin[0].scriptWitness.stack[0] = nonce;
2919 block.vtx[0] = MakeTransactionRef(std::move(tx));
2923 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2925 std::vector<unsigned char> commitment;
2926 int commitpos = GetWitnessCommitmentIndex(block);
2927 std::vector<unsigned char> ret(32, 0x00);
2928 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2929 if (commitpos == -1) {
2930 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2931 CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2932 CTxOut out;
2933 out.nValue = 0;
2934 out.scriptPubKey.resize(38);
2935 out.scriptPubKey[0] = OP_RETURN;
2936 out.scriptPubKey[1] = 0x24;
2937 out.scriptPubKey[2] = 0xaa;
2938 out.scriptPubKey[3] = 0x21;
2939 out.scriptPubKey[4] = 0xa9;
2940 out.scriptPubKey[5] = 0xed;
2941 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2942 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2943 CMutableTransaction tx(*block.vtx[0]);
2944 tx.vout.push_back(out);
2945 block.vtx[0] = MakeTransactionRef(std::move(tx));
2948 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2949 return commitment;
2952 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2954 assert(pindexPrev != NULL);
2955 const int nHeight = pindexPrev->nHeight + 1;
2956 // Check proof of work
2957 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2958 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2960 // Check timestamp against prev
2961 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2962 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2964 // Check timestamp
2965 if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
2966 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2968 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2969 // check for version 2, 3 and 4 upgrades
2970 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2971 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2972 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2973 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2974 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2976 return true;
2979 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2981 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2983 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2984 int nLockTimeFlags = 0;
2985 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2986 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2989 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2990 ? pindexPrev->GetMedianTimePast()
2991 : block.GetBlockTime();
2993 // Check that all transactions are finalized
2994 for (const auto& tx : block.vtx) {
2995 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2996 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3000 // Enforce rule that the coinbase starts with serialized block height
3001 if (nHeight >= consensusParams.BIP34Height)
3003 CScript expect = CScript() << nHeight;
3004 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3005 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3006 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3010 // Validation for witness commitments.
3011 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3012 // coinbase (where 0x0000....0000 is used instead).
3013 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3014 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3015 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3016 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3017 // multiple, the last one is used.
3018 bool fHaveWitness = false;
3019 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3020 int commitpos = GetWitnessCommitmentIndex(block);
3021 if (commitpos != -1) {
3022 bool malleated = false;
3023 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3024 // The malleation check is ignored; as the transaction tree itself
3025 // already does not permit it, it is impossible to trigger in the
3026 // witness tree.
3027 if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3028 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3030 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3031 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3032 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3034 fHaveWitness = true;
3038 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3039 if (!fHaveWitness) {
3040 for (size_t i = 0; i < block.vtx.size(); i++) {
3041 if (block.vtx[i]->HasWitness()) {
3042 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3047 // After the coinbase witness nonce and commitment are verified,
3048 // we can check if the block weight passes (before we've checked the
3049 // coinbase witness, it would be possible for the weight to be too
3050 // large by filling up the coinbase witness, which doesn't change
3051 // the block hash, so we couldn't mark the block as permanently
3052 // failed).
3053 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3054 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3057 return true;
3060 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3062 AssertLockHeld(cs_main);
3063 // Check for duplicate
3064 uint256 hash = block.GetHash();
3065 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3066 CBlockIndex *pindex = NULL;
3067 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3069 if (miSelf != mapBlockIndex.end()) {
3070 // Block header is already known.
3071 pindex = miSelf->second;
3072 if (ppindex)
3073 *ppindex = pindex;
3074 if (pindex->nStatus & BLOCK_FAILED_MASK)
3075 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3076 return true;
3079 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3080 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3082 // Get prev block index
3083 CBlockIndex* pindexPrev = NULL;
3084 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3085 if (mi == mapBlockIndex.end())
3086 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3087 pindexPrev = (*mi).second;
3088 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3089 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3091 assert(pindexPrev);
3092 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3093 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3095 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3096 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3098 if (pindex == NULL)
3099 pindex = AddToBlockIndex(block);
3101 if (ppindex)
3102 *ppindex = pindex;
3104 CheckBlockIndex(chainparams.GetConsensus());
3106 return true;
3109 // Exposed wrapper for AcceptBlockHeader
3110 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3113 LOCK(cs_main);
3114 for (const CBlockHeader& header : headers) {
3115 CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
3116 if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3117 return false;
3119 if (ppindex) {
3120 *ppindex = pindex;
3124 NotifyHeaderTip();
3125 return true;
3128 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3129 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3131 const CBlock& block = *pblock;
3133 if (fNewBlock) *fNewBlock = false;
3134 AssertLockHeld(cs_main);
3136 CBlockIndex *pindexDummy = NULL;
3137 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3139 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3140 return false;
3142 // Try to process all requested blocks that we don't have, but only
3143 // process an unrequested block if it's new and has enough work to
3144 // advance our tip, and isn't too many blocks ahead.
3145 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3146 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3147 // Blocks that are too out-of-order needlessly limit the effectiveness of
3148 // pruning, because pruning will not delete block files that contain any
3149 // blocks which are too close in height to the tip. Apply this test
3150 // regardless of whether pruning is enabled; it should generally be safe to
3151 // not process unrequested blocks.
3152 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3154 // TODO: Decouple this function from the block download logic by removing fRequested
3155 // This requires some new chain datastructure to efficiently look up if a
3156 // block is in a chain leading to a candidate for best tip, despite not
3157 // being such a candidate itself.
3159 // TODO: deal better with return value and error conditions for duplicate
3160 // and unrequested blocks.
3161 if (fAlreadyHave) return true;
3162 if (!fRequested) { // If we didn't ask for it:
3163 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3164 if (!fHasMoreWork) return true; // Don't process less-work chains
3165 if (fTooFarAhead) return true; // Block height is too high
3167 if (fNewBlock) *fNewBlock = true;
3169 if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3170 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3171 if (state.IsInvalid() && !state.CorruptionPossible()) {
3172 pindex->nStatus |= BLOCK_FAILED_VALID;
3173 setDirtyBlockIndex.insert(pindex);
3175 return error("%s: %s", __func__, FormatStateMessage(state));
3178 // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3179 // (but if it does not build on our best tip, let the SendMessages loop relay it)
3180 if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3181 GetMainSignals().NewPoWValidBlock(pindex, pblock);
3183 int nHeight = pindex->nHeight;
3185 // Write block to history file
3186 try {
3187 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3188 CDiskBlockPos blockPos;
3189 if (dbp != NULL)
3190 blockPos = *dbp;
3191 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3192 return error("AcceptBlock(): FindBlockPos failed");
3193 if (dbp == NULL)
3194 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3195 AbortNode(state, "Failed to write block");
3196 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3197 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3198 } catch (const std::runtime_error& e) {
3199 return AbortNode(state, std::string("System error: ") + e.what());
3202 if (fCheckForPruning)
3203 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3205 return true;
3208 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3211 CBlockIndex *pindex = NULL;
3212 if (fNewBlock) *fNewBlock = false;
3213 CValidationState state;
3214 // Ensure that CheckBlock() passes before calling AcceptBlock, as
3215 // belt-and-suspenders.
3216 bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3218 LOCK(cs_main);
3220 if (ret) {
3221 // Store to disk
3222 ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3224 CheckBlockIndex(chainparams.GetConsensus());
3225 if (!ret) {
3226 GetMainSignals().BlockChecked(*pblock, state);
3227 return error("%s: AcceptBlock FAILED", __func__);
3231 NotifyHeaderTip();
3233 CValidationState state; // Only used to report errors, not invalidity - ignore it
3234 if (!ActivateBestChain(state, chainparams, pblock))
3235 return error("%s: ActivateBestChain failed", __func__);
3237 return true;
3240 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3242 AssertLockHeld(cs_main);
3243 assert(pindexPrev && pindexPrev == chainActive.Tip());
3244 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3245 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3247 CCoinsViewCache viewNew(pcoinsTip);
3248 CBlockIndex indexDummy(block);
3249 indexDummy.pprev = pindexPrev;
3250 indexDummy.nHeight = pindexPrev->nHeight + 1;
3252 // NOTE: CheckBlockHeader is called by CheckBlock
3253 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3254 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3255 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3256 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3257 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3258 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3259 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3260 return false;
3261 assert(state.IsValid());
3263 return true;
3267 * BLOCK PRUNING CODE
3270 /* Calculate the amount of disk space the block & undo files currently use */
3271 uint64_t CalculateCurrentUsage()
3273 uint64_t retval = 0;
3274 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3275 retval += file.nSize + file.nUndoSize;
3277 return retval;
3280 /* Prune a block file (modify associated database entries)*/
3281 void PruneOneBlockFile(const int fileNumber)
3283 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3284 CBlockIndex* pindex = it->second;
3285 if (pindex->nFile == fileNumber) {
3286 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3287 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3288 pindex->nFile = 0;
3289 pindex->nDataPos = 0;
3290 pindex->nUndoPos = 0;
3291 setDirtyBlockIndex.insert(pindex);
3293 // Prune from mapBlocksUnlinked -- any block we prune would have
3294 // to be downloaded again in order to consider its chain, at which
3295 // point it would be considered as a candidate for
3296 // mapBlocksUnlinked or setBlockIndexCandidates.
3297 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3298 while (range.first != range.second) {
3299 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3300 range.first++;
3301 if (_it->second == pindex) {
3302 mapBlocksUnlinked.erase(_it);
3308 vinfoBlockFile[fileNumber].SetNull();
3309 setDirtyFileInfo.insert(fileNumber);
3313 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3315 for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3316 CDiskBlockPos pos(*it, 0);
3317 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3318 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3319 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3323 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3324 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3326 assert(fPruneMode && nManualPruneHeight > 0);
3328 LOCK2(cs_main, cs_LastBlockFile);
3329 if (chainActive.Tip() == NULL)
3330 return;
3332 // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3333 unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3334 int count=0;
3335 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3336 if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3337 continue;
3338 PruneOneBlockFile(fileNumber);
3339 setFilesToPrune.insert(fileNumber);
3340 count++;
3342 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3345 /* This function is called from the RPC code for pruneblockchain */
3346 void PruneBlockFilesManual(int nManualPruneHeight)
3348 CValidationState state;
3349 FlushStateToDisk(state, FLUSH_STATE_NONE, nManualPruneHeight);
3352 /* Calculate the block/rev files that should be deleted to remain under target*/
3353 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3355 LOCK2(cs_main, cs_LastBlockFile);
3356 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3357 return;
3359 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3360 return;
3363 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3364 uint64_t nCurrentUsage = CalculateCurrentUsage();
3365 // We don't check to prune until after we've allocated new space for files
3366 // So we should leave a buffer under our target to account for another allocation
3367 // before the next pruning.
3368 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3369 uint64_t nBytesToPrune;
3370 int count=0;
3372 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3373 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3374 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3376 if (vinfoBlockFile[fileNumber].nSize == 0)
3377 continue;
3379 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3380 break;
3382 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3383 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3384 continue;
3386 PruneOneBlockFile(fileNumber);
3387 // Queue up the files for removal
3388 setFilesToPrune.insert(fileNumber);
3389 nCurrentUsage -= nBytesToPrune;
3390 count++;
3394 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3395 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3396 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3397 nLastBlockWeCanPrune, count);
3400 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3402 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3404 // Check for nMinDiskSpace bytes (currently 50MB)
3405 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3406 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3408 return true;
3411 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3413 if (pos.IsNull())
3414 return NULL;
3415 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3416 boost::filesystem::create_directories(path.parent_path());
3417 FILE* file = fopen(path.string().c_str(), "rb+");
3418 if (!file && !fReadOnly)
3419 file = fopen(path.string().c_str(), "wb+");
3420 if (!file) {
3421 LogPrintf("Unable to open file %s\n", path.string());
3422 return NULL;
3424 if (pos.nPos) {
3425 if (fseek(file, pos.nPos, SEEK_SET)) {
3426 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3427 fclose(file);
3428 return NULL;
3431 return file;
3434 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3435 return OpenDiskFile(pos, "blk", fReadOnly);
3438 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3439 return OpenDiskFile(pos, "rev", fReadOnly);
3442 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3444 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3447 CBlockIndex * InsertBlockIndex(uint256 hash)
3449 if (hash.IsNull())
3450 return NULL;
3452 // Return existing
3453 BlockMap::iterator mi = mapBlockIndex.find(hash);
3454 if (mi != mapBlockIndex.end())
3455 return (*mi).second;
3457 // Create new
3458 CBlockIndex* pindexNew = new CBlockIndex();
3459 if (!pindexNew)
3460 throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3461 mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3462 pindexNew->phashBlock = &((*mi).first);
3464 return pindexNew;
3467 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3469 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3470 return false;
3472 boost::this_thread::interruption_point();
3474 // Calculate nChainWork
3475 std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3476 vSortedByHeight.reserve(mapBlockIndex.size());
3477 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3479 CBlockIndex* pindex = item.second;
3480 vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3482 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3483 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3485 CBlockIndex* pindex = item.second;
3486 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3487 pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3488 // We can link the chain of blocks for which we've received transactions at some point.
3489 // Pruned nodes may have deleted the block.
3490 if (pindex->nTx > 0) {
3491 if (pindex->pprev) {
3492 if (pindex->pprev->nChainTx) {
3493 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3494 } else {
3495 pindex->nChainTx = 0;
3496 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3498 } else {
3499 pindex->nChainTx = pindex->nTx;
3502 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3503 setBlockIndexCandidates.insert(pindex);
3504 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3505 pindexBestInvalid = pindex;
3506 if (pindex->pprev)
3507 pindex->BuildSkip();
3508 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3509 pindexBestHeader = pindex;
3512 // Load block file info
3513 pblocktree->ReadLastBlockFile(nLastBlockFile);
3514 vinfoBlockFile.resize(nLastBlockFile + 1);
3515 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3516 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3517 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3519 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3520 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3521 CBlockFileInfo info;
3522 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3523 vinfoBlockFile.push_back(info);
3524 } else {
3525 break;
3529 // Check presence of blk files
3530 LogPrintf("Checking all blk files are present...\n");
3531 std::set<int> setBlkDataFiles;
3532 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3534 CBlockIndex* pindex = item.second;
3535 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3536 setBlkDataFiles.insert(pindex->nFile);
3539 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3541 CDiskBlockPos pos(*it, 0);
3542 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3543 return false;
3547 // Check whether we have ever pruned block & undo files
3548 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3549 if (fHavePruned)
3550 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3552 // Check whether we need to continue reindexing
3553 bool fReindexing = false;
3554 pblocktree->ReadReindexing(fReindexing);
3555 fReindex |= fReindexing;
3557 // Check whether we have a transaction index
3558 pblocktree->ReadFlag("txindex", fTxIndex);
3559 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3561 // Load pointer to end of best chain
3562 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3563 if (it == mapBlockIndex.end())
3564 return true;
3565 chainActive.SetTip(it->second);
3567 PruneBlockIndexCandidates();
3569 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3570 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3571 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3572 GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3574 return true;
3577 CVerifyDB::CVerifyDB()
3579 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3582 CVerifyDB::~CVerifyDB()
3584 uiInterface.ShowProgress("", 100);
3587 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3589 LOCK(cs_main);
3590 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3591 return true;
3593 // Verify blocks in the best chain
3594 if (nCheckDepth <= 0)
3595 nCheckDepth = 1000000000; // suffices until the year 19000
3596 if (nCheckDepth > chainActive.Height())
3597 nCheckDepth = chainActive.Height();
3598 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3599 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3600 CCoinsViewCache coins(coinsview);
3601 CBlockIndex* pindexState = chainActive.Tip();
3602 CBlockIndex* pindexFailure = NULL;
3603 int nGoodTransactions = 0;
3604 CValidationState state;
3605 int reportDone = 0;
3606 LogPrintf("[0%%]...");
3607 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3609 boost::this_thread::interruption_point();
3610 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3611 if (reportDone < percentageDone/10) {
3612 // report every 10% step
3613 LogPrintf("[%d%%]...", percentageDone);
3614 reportDone = percentageDone/10;
3616 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3617 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3618 break;
3619 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3620 // If pruning, only go back as far as we have data.
3621 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3622 break;
3624 CBlock block;
3625 // check level 0: read from disk
3626 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3627 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3628 // check level 1: verify block validity
3629 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3630 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3631 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3632 // check level 2: verify undo validity
3633 if (nCheckLevel >= 2 && pindex) {
3634 CBlockUndo undo;
3635 CDiskBlockPos pos = pindex->GetUndoPos();
3636 if (!pos.IsNull()) {
3637 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3638 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3641 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3642 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3643 bool fClean = true;
3644 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3645 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3646 pindexState = pindex->pprev;
3647 if (!fClean) {
3648 nGoodTransactions = 0;
3649 pindexFailure = pindex;
3650 } else
3651 nGoodTransactions += block.vtx.size();
3653 if (ShutdownRequested())
3654 return true;
3656 if (pindexFailure)
3657 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3659 // check level 4: try reconnecting blocks
3660 if (nCheckLevel >= 4) {
3661 CBlockIndex *pindex = pindexState;
3662 while (pindex != chainActive.Tip()) {
3663 boost::this_thread::interruption_point();
3664 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3665 pindex = chainActive.Next(pindex);
3666 CBlock block;
3667 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3668 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3669 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3670 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3674 LogPrintf("[DONE].\n");
3675 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3677 return true;
3680 bool RewindBlockIndex(const CChainParams& params)
3682 LOCK(cs_main);
3684 int nHeight = 1;
3685 while (nHeight <= chainActive.Height()) {
3686 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3687 break;
3689 nHeight++;
3692 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3693 CValidationState state;
3694 CBlockIndex* pindex = chainActive.Tip();
3695 while (chainActive.Height() >= nHeight) {
3696 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3697 // If pruning, don't try rewinding past the HAVE_DATA point;
3698 // since older blocks can't be served anyway, there's
3699 // no need to walk further, and trying to DisconnectTip()
3700 // will fail (and require a needless reindex/redownload
3701 // of the blockchain).
3702 break;
3704 if (!DisconnectTip(state, params, true)) {
3705 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3707 // Occasionally flush state to disk.
3708 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3709 return false;
3712 // Reduce validity flag and have-data flags.
3713 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3714 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3715 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3716 CBlockIndex* pindexIter = it->second;
3718 // Note: If we encounter an insufficiently validated block that
3719 // is on chainActive, it must be because we are a pruning node, and
3720 // this block or some successor doesn't HAVE_DATA, so we were unable to
3721 // rewind all the way. Blocks remaining on chainActive at this point
3722 // must not have their validity reduced.
3723 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3724 // Reduce validity
3725 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3726 // Remove have-data flags.
3727 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3728 // Remove storage location.
3729 pindexIter->nFile = 0;
3730 pindexIter->nDataPos = 0;
3731 pindexIter->nUndoPos = 0;
3732 // Remove various other things
3733 pindexIter->nTx = 0;
3734 pindexIter->nChainTx = 0;
3735 pindexIter->nSequenceId = 0;
3736 // Make sure it gets written.
3737 setDirtyBlockIndex.insert(pindexIter);
3738 // Update indexes
3739 setBlockIndexCandidates.erase(pindexIter);
3740 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3741 while (ret.first != ret.second) {
3742 if (ret.first->second == pindexIter) {
3743 mapBlocksUnlinked.erase(ret.first++);
3744 } else {
3745 ++ret.first;
3748 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3749 setBlockIndexCandidates.insert(pindexIter);
3753 PruneBlockIndexCandidates();
3755 CheckBlockIndex(params.GetConsensus());
3757 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3758 return false;
3761 return true;
3764 // May NOT be used after any connections are up as much
3765 // of the peer-processing logic assumes a consistent
3766 // block index state
3767 void UnloadBlockIndex()
3769 LOCK(cs_main);
3770 setBlockIndexCandidates.clear();
3771 chainActive.SetTip(NULL);
3772 pindexBestInvalid = NULL;
3773 pindexBestHeader = NULL;
3774 mempool.clear();
3775 mapBlocksUnlinked.clear();
3776 vinfoBlockFile.clear();
3777 nLastBlockFile = 0;
3778 nBlockSequenceId = 1;
3779 setDirtyBlockIndex.clear();
3780 setDirtyFileInfo.clear();
3781 versionbitscache.Clear();
3782 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3783 warningcache[b].clear();
3786 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3787 delete entry.second;
3789 mapBlockIndex.clear();
3790 fHavePruned = false;
3793 bool LoadBlockIndex(const CChainParams& chainparams)
3795 // Load block index from databases
3796 if (!fReindex && !LoadBlockIndexDB(chainparams))
3797 return false;
3798 return true;
3801 bool InitBlockIndex(const CChainParams& chainparams)
3803 LOCK(cs_main);
3805 // Check whether we're already initialized
3806 if (chainActive.Genesis() != NULL)
3807 return true;
3809 // Use the provided setting for -txindex in the new database
3810 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3811 pblocktree->WriteFlag("txindex", fTxIndex);
3812 LogPrintf("Initializing databases...\n");
3814 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3815 if (!fReindex) {
3816 try {
3817 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3818 // Start new block file
3819 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3820 CDiskBlockPos blockPos;
3821 CValidationState state;
3822 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3823 return error("LoadBlockIndex(): FindBlockPos failed");
3824 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3825 return error("LoadBlockIndex(): writing genesis block to disk failed");
3826 CBlockIndex *pindex = AddToBlockIndex(block);
3827 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3828 return error("LoadBlockIndex(): genesis block not accepted");
3829 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3830 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3831 } catch (const std::runtime_error& e) {
3832 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3836 return true;
3839 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3841 // Map of disk positions for blocks with unknown parent (only used for reindex)
3842 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3843 int64_t nStart = GetTimeMillis();
3845 int nLoaded = 0;
3846 try {
3847 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3848 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3849 uint64_t nRewind = blkdat.GetPos();
3850 while (!blkdat.eof()) {
3851 boost::this_thread::interruption_point();
3853 blkdat.SetPos(nRewind);
3854 nRewind++; // start one byte further next time, in case of failure
3855 blkdat.SetLimit(); // remove former limit
3856 unsigned int nSize = 0;
3857 try {
3858 // locate a header
3859 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3860 blkdat.FindByte(chainparams.MessageStart()[0]);
3861 nRewind = blkdat.GetPos()+1;
3862 blkdat >> FLATDATA(buf);
3863 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3864 continue;
3865 // read size
3866 blkdat >> nSize;
3867 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3868 continue;
3869 } catch (const std::exception&) {
3870 // no valid block header found; don't complain
3871 break;
3873 try {
3874 // read block
3875 uint64_t nBlockPos = blkdat.GetPos();
3876 if (dbp)
3877 dbp->nPos = nBlockPos;
3878 blkdat.SetLimit(nBlockPos + nSize);
3879 blkdat.SetPos(nBlockPos);
3880 std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3881 CBlock& block = *pblock;
3882 blkdat >> block;
3883 nRewind = blkdat.GetPos();
3885 // detect out of order blocks, and store them for later
3886 uint256 hash = block.GetHash();
3887 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3888 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3889 block.hashPrevBlock.ToString());
3890 if (dbp)
3891 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3892 continue;
3895 // process in case the block isn't known yet
3896 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3897 LOCK(cs_main);
3898 CValidationState state;
3899 if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3900 nLoaded++;
3901 if (state.IsError())
3902 break;
3903 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3904 LogPrint("reindex", "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3907 // Activate the genesis block so normal node progress can continue
3908 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3909 CValidationState state;
3910 if (!ActivateBestChain(state, chainparams)) {
3911 break;
3915 NotifyHeaderTip();
3917 // Recursively process earlier encountered successors of this block
3918 std::deque<uint256> queue;
3919 queue.push_back(hash);
3920 while (!queue.empty()) {
3921 uint256 head = queue.front();
3922 queue.pop_front();
3923 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3924 while (range.first != range.second) {
3925 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3926 std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
3927 if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
3929 LogPrint("reindex", "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
3930 head.ToString());
3931 LOCK(cs_main);
3932 CValidationState dummy;
3933 if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
3935 nLoaded++;
3936 queue.push_back(pblockrecursive->GetHash());
3939 range.first++;
3940 mapBlocksUnknownParent.erase(it);
3941 NotifyHeaderTip();
3944 } catch (const std::exception& e) {
3945 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3948 } catch (const std::runtime_error& e) {
3949 AbortNode(std::string("System error: ") + e.what());
3951 if (nLoaded > 0)
3952 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3953 return nLoaded > 0;
3956 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3958 if (!fCheckBlockIndex) {
3959 return;
3962 LOCK(cs_main);
3964 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3965 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3966 // iterating the block tree require that chainActive has been initialized.)
3967 if (chainActive.Height() < 0) {
3968 assert(mapBlockIndex.size() <= 1);
3969 return;
3972 // Build forward-pointing map of the entire block tree.
3973 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3974 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3975 forward.insert(std::make_pair(it->second->pprev, it->second));
3978 assert(forward.size() == mapBlockIndex.size());
3980 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3981 CBlockIndex *pindex = rangeGenesis.first->second;
3982 rangeGenesis.first++;
3983 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3985 // Iterate over the entire block tree, using depth-first search.
3986 // Along the way, remember whether there are blocks on the path from genesis
3987 // block being explored which are the first to have certain properties.
3988 size_t nNodes = 0;
3989 int nHeight = 0;
3990 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3991 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3992 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3993 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3994 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3995 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3996 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3997 while (pindex != NULL) {
3998 nNodes++;
3999 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4000 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4001 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4002 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4003 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4004 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4005 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4007 // Begin: actual consistency checks.
4008 if (pindex->pprev == NULL) {
4009 // Genesis block checks.
4010 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4011 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4013 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)
4014 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4015 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4016 if (!fHavePruned) {
4017 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4018 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4019 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4020 } else {
4021 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4022 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4024 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4025 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4026 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4027 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4028 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4029 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4030 assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4031 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4032 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4033 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4034 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4035 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4036 if (pindexFirstInvalid == NULL) {
4037 // Checks for not-invalid blocks.
4038 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4040 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4041 if (pindexFirstInvalid == NULL) {
4042 // If this block sorts at least as good as the current tip and
4043 // is valid and we have all data for its parents, it must be in
4044 // setBlockIndexCandidates. chainActive.Tip() must also be there
4045 // even if some data has been pruned.
4046 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4047 assert(setBlockIndexCandidates.count(pindex));
4049 // If some parent is missing, then it could be that this block was in
4050 // setBlockIndexCandidates but had to be removed because of the missing data.
4051 // In this case it must be in mapBlocksUnlinked -- see test below.
4053 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4054 assert(setBlockIndexCandidates.count(pindex) == 0);
4056 // Check whether this block is in mapBlocksUnlinked.
4057 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4058 bool foundInUnlinked = false;
4059 while (rangeUnlinked.first != rangeUnlinked.second) {
4060 assert(rangeUnlinked.first->first == pindex->pprev);
4061 if (rangeUnlinked.first->second == pindex) {
4062 foundInUnlinked = true;
4063 break;
4065 rangeUnlinked.first++;
4067 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4068 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4069 assert(foundInUnlinked);
4071 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4072 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4073 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4074 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4075 assert(fHavePruned); // We must have pruned.
4076 // This block may have entered mapBlocksUnlinked if:
4077 // - it has a descendant that at some point had more work than the
4078 // tip, and
4079 // - we tried switching to that descendant but were missing
4080 // data for some intermediate block between chainActive and the
4081 // tip.
4082 // So if this block is itself better than chainActive.Tip() and it wasn't in
4083 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4084 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4085 if (pindexFirstInvalid == NULL) {
4086 assert(foundInUnlinked);
4090 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4091 // End: actual consistency checks.
4093 // Try descending into the first subnode.
4094 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4095 if (range.first != range.second) {
4096 // A subnode was found.
4097 pindex = range.first->second;
4098 nHeight++;
4099 continue;
4101 // This is a leaf node.
4102 // Move upwards until we reach a node of which we have not yet visited the last child.
4103 while (pindex) {
4104 // We are going to either move to a parent or a sibling of pindex.
4105 // If pindex was the first with a certain property, unset the corresponding variable.
4106 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4107 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4108 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4109 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4110 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4111 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4112 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4113 // Find our parent.
4114 CBlockIndex* pindexPar = pindex->pprev;
4115 // Find which child we just visited.
4116 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4117 while (rangePar.first->second != pindex) {
4118 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4119 rangePar.first++;
4121 // Proceed to the next one.
4122 rangePar.first++;
4123 if (rangePar.first != rangePar.second) {
4124 // Move to the sibling.
4125 pindex = rangePar.first->second;
4126 break;
4127 } else {
4128 // Move up further.
4129 pindex = pindexPar;
4130 nHeight--;
4131 continue;
4136 // Check that we actually traversed the entire map.
4137 assert(nNodes == forward.size());
4140 std::string CBlockFileInfo::ToString() const
4142 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));
4145 CBlockFileInfo* GetBlockFileInfo(size_t n)
4147 return &vinfoBlockFile.at(n);
4150 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4152 LOCK(cs_main);
4153 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4156 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4158 LOCK(cs_main);
4159 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4162 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4164 bool LoadMempool(void)
4166 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4167 FILE* filestr = fopen((GetDataDir() / "mempool.dat").string().c_str(), "rb");
4168 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4169 if (file.IsNull()) {
4170 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4171 return false;
4174 int64_t count = 0;
4175 int64_t skipped = 0;
4176 int64_t failed = 0;
4177 int64_t nNow = GetTime();
4179 try {
4180 uint64_t version;
4181 file >> version;
4182 if (version != MEMPOOL_DUMP_VERSION) {
4183 return false;
4185 uint64_t num;
4186 file >> num;
4187 while (num--) {
4188 CTransactionRef tx;
4189 int64_t nTime;
4190 int64_t nFeeDelta;
4191 file >> tx;
4192 file >> nTime;
4193 file >> nFeeDelta;
4195 CAmount amountdelta = nFeeDelta;
4196 if (amountdelta) {
4197 mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4199 CValidationState state;
4200 if (nTime + nExpiryTimeout > nNow) {
4201 LOCK(cs_main);
4202 AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
4203 if (state.IsValid()) {
4204 ++count;
4205 } else {
4206 ++failed;
4208 } else {
4209 ++skipped;
4211 if (ShutdownRequested())
4212 return false;
4214 std::map<uint256, CAmount> mapDeltas;
4215 file >> mapDeltas;
4217 for (const auto& i : mapDeltas) {
4218 mempool.PrioritiseTransaction(i.first, i.second);
4220 } catch (const std::exception& e) {
4221 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4222 return false;
4225 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4226 return true;
4229 void DumpMempool(void)
4231 int64_t start = GetTimeMicros();
4233 std::map<uint256, CAmount> mapDeltas;
4234 std::vector<TxMempoolInfo> vinfo;
4237 LOCK(mempool.cs);
4238 for (const auto &i : mempool.mapDeltas) {
4239 mapDeltas[i.first] = i.second;
4241 vinfo = mempool.infoAll();
4244 int64_t mid = GetTimeMicros();
4246 try {
4247 FILE* filestr = fopen((GetDataDir() / "mempool.dat.new").string().c_str(), "wb");
4248 if (!filestr) {
4249 return;
4252 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4254 uint64_t version = MEMPOOL_DUMP_VERSION;
4255 file << version;
4257 file << (uint64_t)vinfo.size();
4258 for (const auto& i : vinfo) {
4259 file << *(i.tx);
4260 file << (int64_t)i.nTime;
4261 file << (int64_t)i.nFeeDelta;
4262 mapDeltas.erase(i.tx->GetHash());
4265 file << mapDeltas;
4266 FileCommit(file.Get());
4267 file.fclose();
4268 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4269 int64_t last = GetTimeMicros();
4270 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4271 } catch (const std::exception& e) {
4272 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4276 //! Guess how far we are in the verification process at the given block index
4277 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4278 if (pindex == NULL)
4279 return 0.0;
4281 int64_t nNow = time(NULL);
4283 double fTxTotal;
4285 if (pindex->nChainTx <= data.nTxCount) {
4286 fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4287 } else {
4288 fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4291 return pindex->nChainTx / fTxTotal;
4294 class CMainCleanup
4296 public:
4297 CMainCleanup() {}
4298 ~CMainCleanup() {
4299 // block headers
4300 BlockMap::iterator it1 = mapBlockIndex.begin();
4301 for (; it1 != mapBlockIndex.end(); it1++)
4302 delete (*it1).second;
4303 mapBlockIndex.clear();
4305 } instance_of_cmaincleanup;