Merge #9240: Remove txConflicted
[bitcoinplatinum.git] / src / validation.cpp
blob7163b99a6784f38fd4644b043cae30b8800a2be4
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"
38 #include <atomic>
39 #include <sstream>
41 #include <boost/algorithm/string/replace.hpp>
42 #include <boost/algorithm/string/join.hpp>
43 #include <boost/filesystem.hpp>
44 #include <boost/filesystem/fstream.hpp>
45 #include <boost/math/distributions/poisson.hpp>
46 #include <boost/thread.hpp>
48 using namespace std;
50 #if defined(NDEBUG)
51 # error "Bitcoin cannot be compiled without assertions."
52 #endif
54 /**
55 * Global state
58 CCriticalSection cs_main;
60 BlockMap mapBlockIndex;
61 CChain chainActive;
62 CBlockIndex *pindexBestHeader = NULL;
63 CWaitableCriticalSection csBestBlock;
64 CConditionVariable cvBlockChange;
65 int nScriptCheckThreads = 0;
66 std::atomic_bool fImporting(false);
67 bool fReindex = false;
68 bool fTxIndex = false;
69 bool fHavePruned = false;
70 bool fPruneMode = false;
71 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
72 bool fRequireStandard = true;
73 bool fCheckBlockIndex = false;
74 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
75 size_t nCoinCacheUsage = 5000 * 300;
76 uint64_t nPruneTarget = 0;
77 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
78 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
81 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
82 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
84 CTxMemPool mempool(::minRelayTxFee);
86 static void CheckBlockIndex(const Consensus::Params& consensusParams);
88 /** Constant stuff for coinbase transactions we create: */
89 CScript COINBASE_FLAGS;
91 const 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 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 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 set<CBlockIndex*> setDirtyBlockIndex;
154 /** Dirty block file entries. */
155 set<int> setDirtyFileInfo;
156 } // anon namespace
158 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
160 // Find the first block the caller has in the main chain
161 BOOST_FOREACH(const uint256& hash, locator.vHave) {
162 BlockMap::iterator mi = mapBlockIndex.find(hash);
163 if (mi != mapBlockIndex.end())
165 CBlockIndex* pindex = (*mi).second;
166 if (chain.Contains(pindex))
167 return pindex;
168 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
169 return chain.Tip();
173 return chain.Genesis();
176 CCoinsViewCache *pcoinsTip = NULL;
177 CBlockTreeDB *pblocktree = NULL;
179 enum FlushStateMode {
180 FLUSH_STATE_NONE,
181 FLUSH_STATE_IF_NEEDED,
182 FLUSH_STATE_PERIODIC,
183 FLUSH_STATE_ALWAYS
186 // See definition for documentation
187 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode);
189 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
191 if (tx.nLockTime == 0)
192 return true;
193 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
194 return true;
195 for (const auto& txin : tx.vin) {
196 if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
197 return false;
199 return true;
202 bool CheckFinalTx(const CTransaction &tx, int flags)
204 AssertLockHeld(cs_main);
206 // By convention a negative value for flags indicates that the
207 // current network-enforced consensus rules should be used. In
208 // a future soft-fork scenario that would mean checking which
209 // rules would be enforced for the next block and setting the
210 // appropriate flags. At the present time no soft-forks are
211 // scheduled, so no flags are set.
212 flags = std::max(flags, 0);
214 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
215 // nLockTime because when IsFinalTx() is called within
216 // CBlock::AcceptBlock(), the height of the block *being*
217 // evaluated is what is used. Thus if we want to know if a
218 // transaction can be part of the *next* block, we need to call
219 // IsFinalTx() with one more than chainActive.Height().
220 const int nBlockHeight = chainActive.Height() + 1;
222 // BIP113 will require that time-locked transactions have nLockTime set to
223 // less than the median time of the previous block they're contained in.
224 // When the next block is created its previous block will be the current
225 // chain tip, so we use that to calculate the median time passed to
226 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
227 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
228 ? chainActive.Tip()->GetMedianTimePast()
229 : GetAdjustedTime();
231 return IsFinalTx(tx, nBlockHeight, nBlockTime);
235 * Calculates the block height and previous block's median time past at
236 * which the transaction will be considered final in the context of BIP 68.
237 * Also removes from the vector of input heights any entries which did not
238 * correspond to sequence locked inputs as they do not affect the calculation.
240 static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
242 assert(prevHeights->size() == tx.vin.size());
244 // Will be set to the equivalent height- and time-based nLockTime
245 // values that would be necessary to satisfy all relative lock-
246 // time constraints given our view of block chain history.
247 // The semantics of nLockTime are the last invalid height/time, so
248 // use -1 to have the effect of any height or time being valid.
249 int nMinHeight = -1;
250 int64_t nMinTime = -1;
252 // tx.nVersion is signed integer so requires cast to unsigned otherwise
253 // we would be doing a signed comparison and half the range of nVersion
254 // wouldn't support BIP 68.
255 bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
256 && flags & LOCKTIME_VERIFY_SEQUENCE;
258 // Do not enforce sequence numbers as a relative lock time
259 // unless we have been instructed to
260 if (!fEnforceBIP68) {
261 return std::make_pair(nMinHeight, nMinTime);
264 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
265 const CTxIn& txin = tx.vin[txinIndex];
267 // Sequence numbers with the most significant bit set are not
268 // treated as relative lock-times, nor are they given any
269 // consensus-enforced meaning at this point.
270 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
271 // The height of this input is not relevant for sequence locks
272 (*prevHeights)[txinIndex] = 0;
273 continue;
276 int nCoinHeight = (*prevHeights)[txinIndex];
278 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
279 int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
280 // NOTE: Subtract 1 to maintain nLockTime semantics
281 // BIP 68 relative lock times have the semantics of calculating
282 // the first block or time at which the transaction would be
283 // valid. When calculating the effective block time or height
284 // for the entire transaction, we switch to using the
285 // semantics of nLockTime which is the last invalid block
286 // time or height. Thus we subtract 1 from the calculated
287 // time or height.
289 // Time-based relative lock-times are measured from the
290 // smallest allowed timestamp of the block containing the
291 // txout being spent, which is the median time past of the
292 // block prior.
293 nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
294 } else {
295 nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
299 return std::make_pair(nMinHeight, nMinTime);
302 static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
304 assert(block.pprev);
305 int64_t nBlockTime = block.pprev->GetMedianTimePast();
306 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
307 return false;
309 return true;
312 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
314 return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
317 bool TestLockPointValidity(const LockPoints* lp)
319 AssertLockHeld(cs_main);
320 assert(lp);
321 // If there are relative lock times then the maxInputBlock will be set
322 // If there are no relative lock times, the LockPoints don't depend on the chain
323 if (lp->maxInputBlock) {
324 // Check whether chainActive is an extension of the block at which the LockPoints
325 // calculation was valid. If not LockPoints are no longer valid
326 if (!chainActive.Contains(lp->maxInputBlock)) {
327 return false;
331 // LockPoints still valid
332 return true;
335 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
337 AssertLockHeld(cs_main);
338 AssertLockHeld(mempool.cs);
340 CBlockIndex* tip = chainActive.Tip();
341 CBlockIndex index;
342 index.pprev = tip;
343 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
344 // height based locks because when SequenceLocks() is called within
345 // ConnectBlock(), the height of the block *being*
346 // evaluated is what is used.
347 // Thus if we want to know if a transaction can be part of the
348 // *next* block, we need to use one more than chainActive.Height()
349 index.nHeight = tip->nHeight + 1;
351 std::pair<int, int64_t> lockPair;
352 if (useExistingLockPoints) {
353 assert(lp);
354 lockPair.first = lp->height;
355 lockPair.second = lp->time;
357 else {
358 // pcoinsTip contains the UTXO set for chainActive.Tip()
359 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
360 std::vector<int> prevheights;
361 prevheights.resize(tx.vin.size());
362 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
363 const CTxIn& txin = tx.vin[txinIndex];
364 CCoins coins;
365 if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
366 return error("%s: Missing input", __func__);
368 if (coins.nHeight == MEMPOOL_HEIGHT) {
369 // Assume all mempool transaction confirm in the next block
370 prevheights[txinIndex] = tip->nHeight + 1;
371 } else {
372 prevheights[txinIndex] = coins.nHeight;
375 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
376 if (lp) {
377 lp->height = lockPair.first;
378 lp->time = lockPair.second;
379 // Also store the hash of the block with the highest height of
380 // all the blocks which have sequence locked prevouts.
381 // This hash needs to still be on the chain
382 // for these LockPoint calculations to be valid
383 // Note: It is impossible to correctly calculate a maxInputBlock
384 // if any of the sequence locked inputs depend on unconfirmed txs,
385 // except in the special case where the relative lock time/height
386 // is 0, which is equivalent to no sequence lock. Since we assume
387 // input height of tip+1 for mempool txs and test the resulting
388 // lockPair from CalculateSequenceLocks against tip+1. We know
389 // EvaluateSequenceLocks will fail if there was a non-zero sequence
390 // lock on a mempool input, so we can use the return value of
391 // CheckSequenceLocks to indicate the LockPoints validity
392 int maxInputHeight = 0;
393 BOOST_FOREACH(int height, prevheights) {
394 // Can ignore mempool inputs since we'll fail if they had non-zero locks
395 if (height != tip->nHeight+1) {
396 maxInputHeight = std::max(maxInputHeight, height);
399 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
402 return EvaluateSequenceLocks(index, lockPair);
406 unsigned int GetLegacySigOpCount(const CTransaction& tx)
408 unsigned int nSigOps = 0;
409 for (const auto& txin : tx.vin)
411 nSigOps += txin.scriptSig.GetSigOpCount(false);
413 for (const auto& txout : tx.vout)
415 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
417 return nSigOps;
420 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
422 if (tx.IsCoinBase())
423 return 0;
425 unsigned int nSigOps = 0;
426 for (unsigned int i = 0; i < tx.vin.size(); i++)
428 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
429 if (prevout.scriptPubKey.IsPayToScriptHash())
430 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
432 return nSigOps;
435 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
437 int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
439 if (tx.IsCoinBase())
440 return nSigOps;
442 if (flags & SCRIPT_VERIFY_P2SH) {
443 nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
446 for (unsigned int i = 0; i < tx.vin.size(); i++)
448 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
449 nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, i < tx.wit.vtxinwit.size() ? &tx.wit.vtxinwit[i].scriptWitness : NULL, flags);
451 return nSigOps;
458 bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)
460 // Basic checks that don't depend on any context
461 if (tx.vin.empty())
462 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
463 if (tx.vout.empty())
464 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
465 // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
466 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
467 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
469 // Check for negative or overflow output values
470 CAmount nValueOut = 0;
471 for (const auto& txout : tx.vout)
473 if (txout.nValue < 0)
474 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
475 if (txout.nValue > MAX_MONEY)
476 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
477 nValueOut += txout.nValue;
478 if (!MoneyRange(nValueOut))
479 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
482 // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
483 if (fCheckDuplicateInputs) {
484 set<COutPoint> vInOutPoints;
485 for (const auto& txin : tx.vin)
487 if (!vInOutPoints.insert(txin.prevout).second)
488 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
492 if (tx.IsCoinBase())
494 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
495 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
497 else
499 for (const auto& txin : tx.vin)
500 if (txin.prevout.IsNull())
501 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
504 return true;
507 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
508 int expired = pool.Expire(GetTime() - age);
509 if (expired != 0)
510 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
512 std::vector<uint256> vNoSpendsRemaining;
513 pool.TrimToSize(limit, &vNoSpendsRemaining);
514 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
515 pcoinsTip->Uncache(removed);
518 /** Convert CValidationState to a human-readable message for logging */
519 std::string FormatStateMessage(const CValidationState &state)
521 return strprintf("%s%s (code %i)",
522 state.GetRejectReason(),
523 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
524 state.GetRejectCode());
527 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree,
528 bool* pfMissingInputs, int64_t nAcceptTime, bool fOverrideMempoolLimit, const CAmount& nAbsurdFee,
529 std::vector<uint256>& vHashTxnToUncache)
531 const uint256 hash = tx.GetHash();
532 AssertLockHeld(cs_main);
533 if (pfMissingInputs)
534 *pfMissingInputs = false;
536 if (!CheckTransaction(tx, state))
537 return false; // state filled in by CheckTransaction
539 // Coinbase is only valid in a block, not as a loose transaction
540 if (tx.IsCoinBase())
541 return state.DoS(100, false, REJECT_INVALID, "coinbase");
543 // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
544 bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus());
545 if (!GetBoolArg("-prematurewitness",false) && !tx.wit.IsNull() && !witnessEnabled) {
546 return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
549 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
550 string reason;
551 if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
552 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
554 // Only accept nLockTime-using transactions that can be mined in the next
555 // block; we don't want our mempool filled up with transactions that can't
556 // be mined yet.
557 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
558 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
560 // is it already in the memory pool?
561 if (pool.exists(hash))
562 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
564 // Check for conflicts with in-memory transactions
565 set<uint256> setConflicts;
567 LOCK(pool.cs); // protect pool.mapNextTx
568 BOOST_FOREACH(const CTxIn &txin, tx.vin)
570 auto itConflicting = pool.mapNextTx.find(txin.prevout);
571 if (itConflicting != pool.mapNextTx.end())
573 const CTransaction *ptxConflicting = itConflicting->second;
574 if (!setConflicts.count(ptxConflicting->GetHash()))
576 // Allow opt-out of transaction replacement by setting
577 // nSequence >= maxint-1 on all inputs.
579 // maxint-1 is picked to still allow use of nLockTime by
580 // non-replaceable transactions. All inputs rather than just one
581 // is for the sake of multi-party protocols, where we don't
582 // want a single party to be able to disable replacement.
584 // The opt-out ignores descendants as anyone relying on
585 // first-seen mempool behavior should be checking all
586 // unconfirmed ancestors anyway; doing otherwise is hopelessly
587 // insecure.
588 bool fReplacementOptOut = true;
589 if (fEnableReplacement)
591 BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
593 if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
595 fReplacementOptOut = false;
596 break;
600 if (fReplacementOptOut)
601 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
603 setConflicts.insert(ptxConflicting->GetHash());
610 CCoinsView dummy;
611 CCoinsViewCache view(&dummy);
613 CAmount nValueIn = 0;
614 LockPoints lp;
616 LOCK(pool.cs);
617 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
618 view.SetBackend(viewMemPool);
620 // do we already have it?
621 bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
622 if (view.HaveCoins(hash)) {
623 if (!fHadTxInCache)
624 vHashTxnToUncache.push_back(hash);
625 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
628 // do all inputs exist?
629 // Note that this does not check for the presence of actual outputs (see the next check for that),
630 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
631 BOOST_FOREACH(const CTxIn txin, tx.vin) {
632 if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
633 vHashTxnToUncache.push_back(txin.prevout.hash);
634 if (!view.HaveCoins(txin.prevout.hash)) {
635 if (pfMissingInputs)
636 *pfMissingInputs = true;
637 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
641 // are the actual inputs available?
642 if (!view.HaveInputs(tx))
643 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
645 // Bring the best block into scope
646 view.GetBestBlock();
648 nValueIn = view.GetValueIn(tx);
650 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
651 view.SetBackend(dummy);
653 // Only accept BIP68 sequence locked transactions that can be mined in the next
654 // block; we don't want our mempool filled up with transactions that can't
655 // be mined yet.
656 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
657 // CoinsViewCache instead of create its own
658 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
659 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
662 // Check for non-standard pay-to-script-hash in inputs
663 if (fRequireStandard && !AreInputsStandard(tx, view))
664 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
666 // Check for non-standard witness in P2WSH
667 if (!tx.wit.IsNull() && fRequireStandard && !IsWitnessStandard(tx, view))
668 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
670 int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
672 CAmount nValueOut = tx.GetValueOut();
673 CAmount nFees = nValueIn-nValueOut;
674 // nModifiedFees includes any fee deltas from PrioritiseTransaction
675 CAmount nModifiedFees = nFees;
676 double nPriorityDummy = 0;
677 pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
679 CAmount inChainInputValue;
680 double dPriority = view.GetPriority(tx, chainActive.Height(), inChainInputValue);
682 // Keep track of transactions that spend a coinbase, which we re-scan
683 // during reorgs to ensure COINBASE_MATURITY is still met.
684 bool fSpendsCoinbase = false;
685 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
686 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
687 if (coins->IsCoinBase()) {
688 fSpendsCoinbase = true;
689 break;
693 CTxMemPoolEntry entry(tx, nFees, nAcceptTime, dPriority, chainActive.Height(), pool.HasNoInputsOf(tx), inChainInputValue, fSpendsCoinbase, nSigOpsCost, lp);
694 unsigned int nSize = entry.GetTxSize();
696 // Check that the transaction doesn't have an excessive number of
697 // sigops, making it impossible to mine. Since the coinbase transaction
698 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
699 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
700 // merely non-standard transaction.
701 if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
702 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
703 strprintf("%d", nSigOpsCost));
705 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
706 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
707 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
708 } else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(chainActive.Height() + 1))) {
709 // Require that free transactions have sufficient priority to be mined in the next block.
710 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
713 // Continuously rate-limit free (really, very-low-fee) transactions
714 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
715 // be annoying or make others' transactions take longer to confirm.
716 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize))
718 static CCriticalSection csFreeLimiter;
719 static double dFreeCount;
720 static int64_t nLastTime;
721 int64_t nNow = GetTime();
723 LOCK(csFreeLimiter);
725 // Use an exponentially decaying ~10-minute window:
726 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
727 nLastTime = nNow;
728 // -limitfreerelay unit is thousand-bytes-per-minute
729 // At default rate it would take over a month to fill 1GB
730 if (dFreeCount + nSize >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
731 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
732 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
733 dFreeCount += nSize;
736 if (nAbsurdFee && nFees > nAbsurdFee)
737 return state.Invalid(false,
738 REJECT_HIGHFEE, "absurdly-high-fee",
739 strprintf("%d > %d", nFees, nAbsurdFee));
741 // Calculate in-mempool ancestors, up to a limit.
742 CTxMemPool::setEntries setAncestors;
743 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
744 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
745 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
746 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
747 std::string errString;
748 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
749 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
752 // A transaction that spends outputs that would be replaced by it is invalid. Now
753 // that we have the set of all ancestors we can detect this
754 // pathological case by making sure setConflicts and setAncestors don't
755 // intersect.
756 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
758 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
759 if (setConflicts.count(hashAncestor))
761 return state.DoS(10, false,
762 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
763 strprintf("%s spends conflicting transaction %s",
764 hash.ToString(),
765 hashAncestor.ToString()));
769 // Check if it's economically rational to mine this transaction rather
770 // than the ones it replaces.
771 CAmount nConflictingFees = 0;
772 size_t nConflictingSize = 0;
773 uint64_t nConflictingCount = 0;
774 CTxMemPool::setEntries allConflicting;
776 // If we don't hold the lock allConflicting might be incomplete; the
777 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
778 // mempool consistency for us.
779 LOCK(pool.cs);
780 if (setConflicts.size())
782 CFeeRate newFeeRate(nModifiedFees, nSize);
783 set<uint256> setConflictsParents;
784 const int maxDescendantsToVisit = 100;
785 CTxMemPool::setEntries setIterConflicting;
786 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
788 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
789 if (mi == pool.mapTx.end())
790 continue;
792 // Save these to avoid repeated lookups
793 setIterConflicting.insert(mi);
795 // Don't allow the replacement to reduce the feerate of the
796 // mempool.
798 // We usually don't want to accept replacements with lower
799 // feerates than what they replaced as that would lower the
800 // feerate of the next block. Requiring that the feerate always
801 // be increased is also an easy-to-reason about way to prevent
802 // DoS attacks via replacements.
804 // The mining code doesn't (currently) take children into
805 // account (CPFP) so we only consider the feerates of
806 // transactions being directly replaced, not their indirect
807 // descendants. While that does mean high feerate children are
808 // ignored when deciding whether or not to replace, we do
809 // require the replacement to pay more overall fees too,
810 // mitigating most cases.
811 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
812 if (newFeeRate <= oldFeeRate)
814 return state.DoS(0, false,
815 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
816 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
817 hash.ToString(),
818 newFeeRate.ToString(),
819 oldFeeRate.ToString()));
822 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
824 setConflictsParents.insert(txin.prevout.hash);
827 nConflictingCount += mi->GetCountWithDescendants();
829 // This potentially overestimates the number of actual descendants
830 // but we just want to be conservative to avoid doing too much
831 // work.
832 if (nConflictingCount <= maxDescendantsToVisit) {
833 // If not too many to replace, then calculate the set of
834 // transactions that would have to be evicted
835 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
836 pool.CalculateDescendants(it, allConflicting);
838 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
839 nConflictingFees += it->GetModifiedFee();
840 nConflictingSize += it->GetTxSize();
842 } else {
843 return state.DoS(0, false,
844 REJECT_NONSTANDARD, "too many potential replacements", false,
845 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
846 hash.ToString(),
847 nConflictingCount,
848 maxDescendantsToVisit));
851 for (unsigned int j = 0; j < tx.vin.size(); j++)
853 // We don't want to accept replacements that require low
854 // feerate junk to be mined first. Ideally we'd keep track of
855 // the ancestor feerates and make the decision based on that,
856 // but for now requiring all new inputs to be confirmed works.
857 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
859 // Rather than check the UTXO set - potentially expensive -
860 // it's cheaper to just check if the new input refers to a
861 // tx that's in the mempool.
862 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
863 return state.DoS(0, false,
864 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
865 strprintf("replacement %s adds unconfirmed input, idx %d",
866 hash.ToString(), j));
870 // The replacement must pay greater fees than the transactions it
871 // replaces - if we did the bandwidth used by those conflicting
872 // transactions would not be paid for.
873 if (nModifiedFees < nConflictingFees)
875 return state.DoS(0, false,
876 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
877 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
878 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
881 // Finally in addition to paying more fees than the conflicts the
882 // new transaction must pay for its own bandwidth.
883 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
884 if (nDeltaFees < ::minRelayTxFee.GetFee(nSize))
886 return state.DoS(0, false,
887 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
888 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
889 hash.ToString(),
890 FormatMoney(nDeltaFees),
891 FormatMoney(::minRelayTxFee.GetFee(nSize))));
895 unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
896 if (!Params().RequireStandard()) {
897 scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
900 // Check against previous transactions
901 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
902 PrecomputedTransactionData txdata(tx);
903 if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
904 // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
905 // need to turn both off, and compare against just turning off CLEANSTACK
906 // to see if the failure is specifically due to witness validation.
907 if (tx.wit.IsNull() && CheckInputs(tx, state, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
908 !CheckInputs(tx, state, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
909 // Only the witness is missing, so the transaction itself may be fine.
910 state.SetCorruptionPossible();
912 return false;
915 // Check again against just the consensus-critical mandatory script
916 // verification flags, in case of bugs in the standard flags that cause
917 // transactions to pass as valid when they're actually invalid. For
918 // instance the STRICTENC flag was incorrectly allowing certain
919 // CHECKSIG NOT scripts to pass, even though they were invalid.
921 // There is a similar check in CreateNewBlock() to prevent creating
922 // invalid blocks, however allowing such transactions into the mempool
923 // can be exploited as a DoS attack.
924 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
926 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
927 __func__, hash.ToString(), FormatStateMessage(state));
930 // Remove conflicting transactions from the mempool
931 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
933 LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
934 it->GetTx().GetHash().ToString(),
935 hash.ToString(),
936 FormatMoney(nModifiedFees - nConflictingFees),
937 (int)nSize - (int)nConflictingSize);
939 pool.RemoveStaged(allConflicting, false);
941 // Store transaction in memory
942 pool.addUnchecked(hash, entry, setAncestors, !IsInitialBlockDownload());
944 // trim mempool and check if tx was trimmed
945 if (!fOverrideMempoolLimit) {
946 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
947 if (!pool.exists(hash))
948 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
952 GetMainSignals().SyncTransaction(tx, NULL, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
954 return true;
957 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
958 bool* pfMissingInputs, int64_t nAcceptTime, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
960 std::vector<uint256> vHashTxToUncache;
961 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
962 if (!res) {
963 BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
964 pcoinsTip->Uncache(hashTx);
966 // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
967 CValidationState stateDummy;
968 FlushStateToDisk(stateDummy, FLUSH_STATE_PERIODIC);
969 return res;
972 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
973 bool* pfMissingInputs, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
975 return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), fOverrideMempoolLimit, nAbsurdFee);
978 /** Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock */
979 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
981 CBlockIndex *pindexSlow = NULL;
983 LOCK(cs_main);
985 CTransactionRef ptx = mempool.get(hash);
986 if (ptx)
988 txOut = ptx;
989 return true;
992 if (fTxIndex) {
993 CDiskTxPos postx;
994 if (pblocktree->ReadTxIndex(hash, postx)) {
995 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
996 if (file.IsNull())
997 return error("%s: OpenBlockFile failed", __func__);
998 CBlockHeader header;
999 try {
1000 file >> header;
1001 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1002 file >> txOut;
1003 } catch (const std::exception& e) {
1004 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1006 hashBlock = header.GetHash();
1007 if (txOut->GetHash() != hash)
1008 return error("%s: txid mismatch", __func__);
1009 return true;
1013 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1014 int nHeight = -1;
1016 const CCoinsViewCache& view = *pcoinsTip;
1017 const CCoins* coins = view.AccessCoins(hash);
1018 if (coins)
1019 nHeight = coins->nHeight;
1021 if (nHeight > 0)
1022 pindexSlow = chainActive[nHeight];
1025 if (pindexSlow) {
1026 CBlock block;
1027 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1028 for (const auto& tx : block.vtx) {
1029 if (tx->GetHash() == hash) {
1030 txOut = tx;
1031 hashBlock = pindexSlow->GetBlockHash();
1032 return true;
1038 return false;
1046 //////////////////////////////////////////////////////////////////////////////
1048 // CBlock and CBlockIndex
1051 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1053 // Open history file to append
1054 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1055 if (fileout.IsNull())
1056 return error("WriteBlockToDisk: OpenBlockFile failed");
1058 // Write index header
1059 unsigned int nSize = GetSerializeSize(fileout, block);
1060 fileout << FLATDATA(messageStart) << nSize;
1062 // Write block
1063 long fileOutPos = ftell(fileout.Get());
1064 if (fileOutPos < 0)
1065 return error("WriteBlockToDisk: ftell failed");
1066 pos.nPos = (unsigned int)fileOutPos;
1067 fileout << block;
1069 return true;
1072 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1074 block.SetNull();
1076 // Open history file to read
1077 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1078 if (filein.IsNull())
1079 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1081 // Read block
1082 try {
1083 filein >> block;
1085 catch (const std::exception& e) {
1086 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1089 // Check the header
1090 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1091 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1093 return true;
1096 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1098 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1099 return false;
1100 if (block.GetHash() != pindex->GetBlockHash())
1101 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1102 pindex->ToString(), pindex->GetBlockPos().ToString());
1103 return true;
1106 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1108 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1109 // Force block reward to zero when right shift is undefined.
1110 if (halvings >= 64)
1111 return 0;
1113 CAmount nSubsidy = 50 * COIN;
1114 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1115 nSubsidy >>= halvings;
1116 return nSubsidy;
1119 bool IsInitialBlockDownload()
1121 const CChainParams& chainParams = Params();
1123 // Once this function has returned false, it must remain false.
1124 static std::atomic<bool> latchToFalse{false};
1125 // Optimization: pre-test latch before taking the lock.
1126 if (latchToFalse.load(std::memory_order_relaxed))
1127 return false;
1129 LOCK(cs_main);
1130 if (latchToFalse.load(std::memory_order_relaxed))
1131 return false;
1132 if (fImporting || fReindex)
1133 return true;
1134 if (chainActive.Tip() == NULL)
1135 return true;
1136 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1137 return true;
1138 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1139 return true;
1140 latchToFalse.store(true, std::memory_order_relaxed);
1141 return false;
1144 bool fLargeWorkForkFound = false;
1145 bool fLargeWorkInvalidChainFound = false;
1146 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1148 static void AlertNotify(const std::string& strMessage)
1150 uiInterface.NotifyAlertChanged();
1151 std::string strCmd = GetArg("-alertnotify", "");
1152 if (strCmd.empty()) return;
1154 // Alert text should be plain ascii coming from a trusted source, but to
1155 // be safe we first strip anything not in safeChars, then add single quotes around
1156 // the whole string before passing it to the shell:
1157 std::string singleQuote("'");
1158 std::string safeStatus = SanitizeString(strMessage);
1159 safeStatus = singleQuote+safeStatus+singleQuote;
1160 boost::replace_all(strCmd, "%s", safeStatus);
1162 boost::thread t(runCommand, strCmd); // thread runs free
1165 void CheckForkWarningConditions()
1167 AssertLockHeld(cs_main);
1168 // Before we get past initial download, we cannot reliably alert about forks
1169 // (we assume we don't get stuck on a fork before finishing our initial sync)
1170 if (IsInitialBlockDownload())
1171 return;
1173 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1174 // of our head, drop it
1175 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1176 pindexBestForkTip = NULL;
1178 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1180 if (!fLargeWorkForkFound && pindexBestForkBase)
1182 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1183 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1184 AlertNotify(warning);
1186 if (pindexBestForkTip && pindexBestForkBase)
1188 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__,
1189 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1190 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1191 fLargeWorkForkFound = true;
1193 else
1195 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1196 fLargeWorkInvalidChainFound = true;
1199 else
1201 fLargeWorkForkFound = false;
1202 fLargeWorkInvalidChainFound = false;
1206 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1208 AssertLockHeld(cs_main);
1209 // If we are on a fork that is sufficiently large, set a warning flag
1210 CBlockIndex* pfork = pindexNewForkTip;
1211 CBlockIndex* plonger = chainActive.Tip();
1212 while (pfork && pfork != plonger)
1214 while (plonger && plonger->nHeight > pfork->nHeight)
1215 plonger = plonger->pprev;
1216 if (pfork == plonger)
1217 break;
1218 pfork = pfork->pprev;
1221 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1222 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1223 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1224 // hash rate operating on the fork.
1225 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1226 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1227 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1228 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1229 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1230 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1232 pindexBestForkTip = pindexNewForkTip;
1233 pindexBestForkBase = pfork;
1236 CheckForkWarningConditions();
1239 void static InvalidChainFound(CBlockIndex* pindexNew)
1241 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1242 pindexBestInvalid = pindexNew;
1244 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1245 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1246 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1247 pindexNew->GetBlockTime()));
1248 CBlockIndex *tip = chainActive.Tip();
1249 assert (tip);
1250 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1251 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1252 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1253 CheckForkWarningConditions();
1256 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1257 if (!state.CorruptionPossible()) {
1258 pindex->nStatus |= BLOCK_FAILED_VALID;
1259 setDirtyBlockIndex.insert(pindex);
1260 setBlockIndexCandidates.erase(pindex);
1261 InvalidChainFound(pindex);
1265 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1267 // mark inputs spent
1268 if (!tx.IsCoinBase()) {
1269 txundo.vprevout.reserve(tx.vin.size());
1270 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1271 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1272 unsigned nPos = txin.prevout.n;
1274 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1275 assert(false);
1276 // mark an outpoint spent, and construct undo information
1277 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1278 coins->Spend(nPos);
1279 if (coins->vout.size() == 0) {
1280 CTxInUndo& undo = txundo.vprevout.back();
1281 undo.nHeight = coins->nHeight;
1282 undo.fCoinBase = coins->fCoinBase;
1283 undo.nVersion = coins->nVersion;
1287 // add outputs
1288 inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1291 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1293 CTxUndo txundo;
1294 UpdateCoins(tx, inputs, txundo, nHeight);
1297 bool CScriptCheck::operator()() {
1298 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1299 const CScriptWitness *witness = (nIn < ptxTo->wit.vtxinwit.size()) ? &ptxTo->wit.vtxinwit[nIn].scriptWitness : NULL;
1300 if (!VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error)) {
1301 return false;
1303 return true;
1306 int GetSpendHeight(const CCoinsViewCache& inputs)
1308 LOCK(cs_main);
1309 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1310 return pindexPrev->nHeight + 1;
1313 namespace Consensus {
1314 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1316 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1317 // for an attacker to attempt to split the network.
1318 if (!inputs.HaveInputs(tx))
1319 return state.Invalid(false, 0, "", "Inputs unavailable");
1321 CAmount nValueIn = 0;
1322 CAmount nFees = 0;
1323 for (unsigned int i = 0; i < tx.vin.size(); i++)
1325 const COutPoint &prevout = tx.vin[i].prevout;
1326 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1327 assert(coins);
1329 // If prev is coinbase, check that it's matured
1330 if (coins->IsCoinBase()) {
1331 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1332 return state.Invalid(false,
1333 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1334 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1337 // Check for negative or overflow input values
1338 nValueIn += coins->vout[prevout.n].nValue;
1339 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1340 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1344 if (nValueIn < tx.GetValueOut())
1345 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1346 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1348 // Tally transaction fees
1349 CAmount nTxFee = nValueIn - tx.GetValueOut();
1350 if (nTxFee < 0)
1351 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1352 nFees += nTxFee;
1353 if (!MoneyRange(nFees))
1354 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1355 return true;
1357 }// namespace Consensus
1359 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1361 if (!tx.IsCoinBase())
1363 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1364 return false;
1366 if (pvChecks)
1367 pvChecks->reserve(tx.vin.size());
1369 // The first loop above does all the inexpensive checks.
1370 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1371 // Helps prevent CPU exhaustion attacks.
1373 // Skip ECDSA signature verification when connecting blocks before the
1374 // last block chain checkpoint. Assuming the checkpoints are valid this
1375 // is safe because block merkle hashes are still computed and checked,
1376 // and any change will be caught at the next checkpoint. Of course, if
1377 // the checkpoint is for a chain that's invalid due to false scriptSigs
1378 // this optimization would allow an invalid chain to be accepted.
1379 if (fScriptChecks) {
1380 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1381 const COutPoint &prevout = tx.vin[i].prevout;
1382 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1383 assert(coins);
1385 // Verify signature
1386 CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1387 if (pvChecks) {
1388 pvChecks->push_back(CScriptCheck());
1389 check.swap(pvChecks->back());
1390 } else if (!check()) {
1391 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1392 // Check whether the failure was caused by a
1393 // non-mandatory script verification check, such as
1394 // non-standard DER encodings or non-null dummy
1395 // arguments; if so, don't trigger DoS protection to
1396 // avoid splitting the network between upgraded and
1397 // non-upgraded nodes.
1398 CScriptCheck check2(*coins, tx, i,
1399 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1400 if (check2())
1401 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1403 // Failures of other flags indicate a transaction that is
1404 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1405 // such nodes as they are not following the protocol. That
1406 // said during an upgrade careful thought should be taken
1407 // as to the correct behavior - we may want to continue
1408 // peering with non-upgraded nodes even after soft-fork
1409 // super-majority signaling has occurred.
1410 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1416 return true;
1419 namespace {
1421 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1423 // Open history file to append
1424 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1425 if (fileout.IsNull())
1426 return error("%s: OpenUndoFile failed", __func__);
1428 // Write index header
1429 unsigned int nSize = GetSerializeSize(fileout, blockundo);
1430 fileout << FLATDATA(messageStart) << nSize;
1432 // Write undo data
1433 long fileOutPos = ftell(fileout.Get());
1434 if (fileOutPos < 0)
1435 return error("%s: ftell failed", __func__);
1436 pos.nPos = (unsigned int)fileOutPos;
1437 fileout << blockundo;
1439 // calculate & write checksum
1440 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1441 hasher << hashBlock;
1442 hasher << blockundo;
1443 fileout << hasher.GetHash();
1445 return true;
1448 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1450 // Open history file to read
1451 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1452 if (filein.IsNull())
1453 return error("%s: OpenUndoFile failed", __func__);
1455 // Read block
1456 uint256 hashChecksum;
1457 try {
1458 filein >> blockundo;
1459 filein >> hashChecksum;
1461 catch (const std::exception& e) {
1462 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1465 // Verify checksum
1466 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1467 hasher << hashBlock;
1468 hasher << blockundo;
1469 if (hashChecksum != hasher.GetHash())
1470 return error("%s: Checksum mismatch", __func__);
1472 return true;
1475 /** Abort with a message */
1476 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1478 strMiscWarning = strMessage;
1479 LogPrintf("*** %s\n", strMessage);
1480 uiInterface.ThreadSafeMessageBox(
1481 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1482 "", CClientUIInterface::MSG_ERROR);
1483 StartShutdown();
1484 return false;
1487 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1489 AbortNode(strMessage, userMessage);
1490 return state.Error(strMessage);
1493 } // anon namespace
1496 * Apply the undo operation of a CTxInUndo to the given chain state.
1497 * @param undo The undo object.
1498 * @param view The coins view to which to apply the changes.
1499 * @param out The out point that corresponds to the tx input.
1500 * @return True on success.
1502 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1504 bool fClean = true;
1506 CCoinsModifier coins = view.ModifyCoins(out.hash);
1507 if (undo.nHeight != 0) {
1508 // undo data contains height: this is the last output of the prevout tx being spent
1509 if (!coins->IsPruned())
1510 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1511 coins->Clear();
1512 coins->fCoinBase = undo.fCoinBase;
1513 coins->nHeight = undo.nHeight;
1514 coins->nVersion = undo.nVersion;
1515 } else {
1516 if (coins->IsPruned())
1517 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1519 if (coins->IsAvailable(out.n))
1520 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1521 if (coins->vout.size() < out.n+1)
1522 coins->vout.resize(out.n+1);
1523 coins->vout[out.n] = undo.txout;
1525 return fClean;
1528 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1530 assert(pindex->GetBlockHash() == view.GetBestBlock());
1532 if (pfClean)
1533 *pfClean = false;
1535 bool fClean = true;
1537 CBlockUndo blockUndo;
1538 CDiskBlockPos pos = pindex->GetUndoPos();
1539 if (pos.IsNull())
1540 return error("DisconnectBlock(): no undo data available");
1541 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1542 return error("DisconnectBlock(): failure reading undo data");
1544 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1545 return error("DisconnectBlock(): block and undo data inconsistent");
1547 // undo transactions in reverse order
1548 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1549 const CTransaction &tx = *(block.vtx[i]);
1550 uint256 hash = tx.GetHash();
1552 // Check that all outputs are available and match the outputs in the block itself
1553 // exactly.
1555 CCoinsModifier outs = view.ModifyCoins(hash);
1556 outs->ClearUnspendable();
1558 CCoins outsBlock(tx, pindex->nHeight);
1559 // The CCoins serialization does not serialize negative numbers.
1560 // No network rules currently depend on the version here, so an inconsistency is harmless
1561 // but it must be corrected before txout nversion ever influences a network rule.
1562 if (outsBlock.nVersion < 0)
1563 outs->nVersion = outsBlock.nVersion;
1564 if (*outs != outsBlock)
1565 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1567 // remove outputs
1568 outs->Clear();
1571 // restore inputs
1572 if (i > 0) { // not coinbases
1573 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1574 if (txundo.vprevout.size() != tx.vin.size())
1575 return error("DisconnectBlock(): transaction and undo data inconsistent");
1576 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1577 const COutPoint &out = tx.vin[j].prevout;
1578 const CTxInUndo &undo = txundo.vprevout[j];
1579 if (!ApplyTxInUndo(undo, view, out))
1580 fClean = false;
1585 // move best block pointer to prevout block
1586 view.SetBestBlock(pindex->pprev->GetBlockHash());
1588 if (pfClean) {
1589 *pfClean = fClean;
1590 return true;
1593 return fClean;
1596 void static FlushBlockFile(bool fFinalize = false)
1598 LOCK(cs_LastBlockFile);
1600 CDiskBlockPos posOld(nLastBlockFile, 0);
1602 FILE *fileOld = OpenBlockFile(posOld);
1603 if (fileOld) {
1604 if (fFinalize)
1605 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1606 FileCommit(fileOld);
1607 fclose(fileOld);
1610 fileOld = OpenUndoFile(posOld);
1611 if (fileOld) {
1612 if (fFinalize)
1613 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1614 FileCommit(fileOld);
1615 fclose(fileOld);
1619 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1621 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1623 void ThreadScriptCheck() {
1624 RenameThread("bitcoin-scriptch");
1625 scriptcheckqueue.Thread();
1628 // Protected by cs_main
1629 VersionBitsCache versionbitscache;
1631 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1633 LOCK(cs_main);
1634 int32_t nVersion = VERSIONBITS_TOP_BITS;
1636 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1637 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1638 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1639 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1643 return nVersion;
1647 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
1649 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
1651 private:
1652 int bit;
1654 public:
1655 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1657 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1658 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1659 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1660 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1662 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1664 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1665 ((pindex->nVersion >> bit) & 1) != 0 &&
1666 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1670 // Protected by cs_main
1671 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1673 static int64_t nTimeCheck = 0;
1674 static int64_t nTimeForks = 0;
1675 static int64_t nTimeVerify = 0;
1676 static int64_t nTimeConnect = 0;
1677 static int64_t nTimeIndex = 0;
1678 static int64_t nTimeCallbacks = 0;
1679 static int64_t nTimeTotal = 0;
1681 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1682 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1684 AssertLockHeld(cs_main);
1686 int64_t nTimeStart = GetTimeMicros();
1688 // Check it again in case a previous version let a bad block in
1689 if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1690 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1692 // verify that the view's current state corresponds to the previous block
1693 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1694 assert(hashPrevBlock == view.GetBestBlock());
1696 // Special case for the genesis block, skipping connection of its transactions
1697 // (its coinbase is unspendable)
1698 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1699 if (!fJustCheck)
1700 view.SetBestBlock(pindex->GetBlockHash());
1701 return true;
1704 bool fScriptChecks = true;
1705 if (fCheckpointsEnabled) {
1706 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
1707 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
1708 // This block is an ancestor of a checkpoint: disable script checks
1709 fScriptChecks = false;
1713 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1714 LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1716 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1717 // unless those are already completely spent.
1718 // If such overwrites are allowed, coinbases and transactions depending upon those
1719 // can be duplicated to remove the ability to spend the first instance -- even after
1720 // being sent to another address.
1721 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1722 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1723 // already refuses previously-known transaction ids entirely.
1724 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1725 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1726 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1727 // initial block download.
1728 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1729 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1730 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1732 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1733 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1734 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1735 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1736 // duplicate transactions descending from the known pairs either.
1737 // 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.
1738 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1739 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1740 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1742 if (fEnforceBIP30) {
1743 for (const auto& tx : block.vtx) {
1744 const CCoins* coins = view.AccessCoins(tx->GetHash());
1745 if (coins && !coins->IsPruned())
1746 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1747 REJECT_INVALID, "bad-txns-BIP30");
1751 // BIP16 didn't become active until Apr 1 2012
1752 int64_t nBIP16SwitchTime = 1333238400;
1753 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1755 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1757 // Start enforcing the DERSIG (BIP66) rule
1758 if (pindex->nHeight >= chainparams.GetConsensus().BIP66Height) {
1759 flags |= SCRIPT_VERIFY_DERSIG;
1762 // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1763 if (pindex->nHeight >= chainparams.GetConsensus().BIP65Height) {
1764 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1767 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1768 int nLockTimeFlags = 0;
1769 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1770 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1771 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1774 // Start enforcing WITNESS rules using versionbits logic.
1775 if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus())) {
1776 flags |= SCRIPT_VERIFY_WITNESS;
1777 flags |= SCRIPT_VERIFY_NULLDUMMY;
1780 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1781 LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1783 CBlockUndo blockundo;
1785 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1787 std::vector<int> prevheights;
1788 CAmount nFees = 0;
1789 int nInputs = 0;
1790 int64_t nSigOpsCost = 0;
1791 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1792 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1793 vPos.reserve(block.vtx.size());
1794 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1795 std::vector<PrecomputedTransactionData> txdata;
1796 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1797 for (unsigned int i = 0; i < block.vtx.size(); i++)
1799 const CTransaction &tx = *(block.vtx[i]);
1801 nInputs += tx.vin.size();
1803 if (!tx.IsCoinBase())
1805 if (!view.HaveInputs(tx))
1806 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1807 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1809 // Check that transaction is BIP68 final
1810 // BIP68 lock checks (as opposed to nLockTime checks) must
1811 // be in ConnectBlock because they require the UTXO set
1812 prevheights.resize(tx.vin.size());
1813 for (size_t j = 0; j < tx.vin.size(); j++) {
1814 prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
1817 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1818 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1819 REJECT_INVALID, "bad-txns-nonfinal");
1823 // GetTransactionSigOpCost counts 3 types of sigops:
1824 // * legacy (always)
1825 // * p2sh (when P2SH enabled in flags and excludes coinbase)
1826 // * witness (when witness enabled in flags and excludes coinbase)
1827 nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1828 if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1829 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1830 REJECT_INVALID, "bad-blk-sigops");
1832 txdata.emplace_back(tx);
1833 if (!tx.IsCoinBase())
1835 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1837 std::vector<CScriptCheck> vChecks;
1838 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1839 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1840 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1841 tx.GetHash().ToString(), FormatStateMessage(state));
1842 control.Add(vChecks);
1845 CTxUndo undoDummy;
1846 if (i > 0) {
1847 blockundo.vtxundo.push_back(CTxUndo());
1849 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1851 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1852 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1854 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1855 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);
1857 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1858 if (block.vtx[0]->GetValueOut() > blockReward)
1859 return state.DoS(100,
1860 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1861 block.vtx[0]->GetValueOut(), blockReward),
1862 REJECT_INVALID, "bad-cb-amount");
1864 if (!control.Wait())
1865 return state.DoS(100, false);
1866 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1867 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);
1869 if (fJustCheck)
1870 return true;
1872 // Write undo information to disk
1873 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1875 if (pindex->GetUndoPos().IsNull()) {
1876 CDiskBlockPos _pos;
1877 if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1878 return error("ConnectBlock(): FindUndoPos failed");
1879 if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1880 return AbortNode(state, "Failed to write undo data");
1882 // update nUndoPos in block index
1883 pindex->nUndoPos = _pos.nPos;
1884 pindex->nStatus |= BLOCK_HAVE_UNDO;
1887 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1888 setDirtyBlockIndex.insert(pindex);
1891 if (fTxIndex)
1892 if (!pblocktree->WriteTxIndex(vPos))
1893 return AbortNode(state, "Failed to write transaction index");
1895 // add this block to the view's block chain
1896 view.SetBestBlock(pindex->GetBlockHash());
1898 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1899 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1901 // Watch for changes to the previous coinbase transaction.
1902 static uint256 hashPrevBestCoinBase;
1903 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1904 hashPrevBestCoinBase = block.vtx[0]->GetHash();
1907 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1908 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1910 return true;
1914 * Update the on-disk chain state.
1915 * The caches and indexes are flushed depending on the mode we're called with
1916 * if they're too large, if it's been a while since the last write,
1917 * or always and in all cases if we're in prune mode and are deleting files.
1919 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1920 const CChainParams& chainparams = Params();
1921 LOCK2(cs_main, cs_LastBlockFile);
1922 static int64_t nLastWrite = 0;
1923 static int64_t nLastFlush = 0;
1924 static int64_t nLastSetChain = 0;
1925 std::set<int> setFilesToPrune;
1926 bool fFlushForPrune = false;
1927 try {
1928 if (fPruneMode && fCheckForPruning && !fReindex) {
1929 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
1930 fCheckForPruning = false;
1931 if (!setFilesToPrune.empty()) {
1932 fFlushForPrune = true;
1933 if (!fHavePruned) {
1934 pblocktree->WriteFlag("prunedblockfiles", true);
1935 fHavePruned = true;
1939 int64_t nNow = GetTimeMicros();
1940 // Avoid writing/flushing immediately after startup.
1941 if (nLastWrite == 0) {
1942 nLastWrite = nNow;
1944 if (nLastFlush == 0) {
1945 nLastFlush = nNow;
1947 if (nLastSetChain == 0) {
1948 nLastSetChain = nNow;
1950 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1951 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1952 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
1953 // The cache is over the limit, we have to write now.
1954 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
1955 // 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.
1956 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1957 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1958 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1959 // Combine all conditions that result in a full cache flush.
1960 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1961 // Write blocks and block index to disk.
1962 if (fDoFullFlush || fPeriodicWrite) {
1963 // Depend on nMinDiskSpace to ensure we can write block index
1964 if (!CheckDiskSpace(0))
1965 return state.Error("out of disk space");
1966 // First make sure all block and undo data is flushed to disk.
1967 FlushBlockFile();
1968 // Then update all block file information (which may refer to block and undo files).
1970 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1971 vFiles.reserve(setDirtyFileInfo.size());
1972 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1973 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
1974 setDirtyFileInfo.erase(it++);
1976 std::vector<const CBlockIndex*> vBlocks;
1977 vBlocks.reserve(setDirtyBlockIndex.size());
1978 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1979 vBlocks.push_back(*it);
1980 setDirtyBlockIndex.erase(it++);
1982 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1983 return AbortNode(state, "Files to write to block index database");
1986 // Finally remove any pruned files
1987 if (fFlushForPrune)
1988 UnlinkPrunedFiles(setFilesToPrune);
1989 nLastWrite = nNow;
1991 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1992 if (fDoFullFlush) {
1993 // Typical CCoins structures on disk are around 128 bytes in size.
1994 // Pushing a new one to the database can cause it to be written
1995 // twice (once in the log, and once in the tables). This is already
1996 // an overestimation, as most will delete an existing entry or
1997 // overwrite one. Still, use a conservative safety factor of 2.
1998 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
1999 return state.Error("out of disk space");
2000 // Flush the chainstate (which may refer to block index entries).
2001 if (!pcoinsTip->Flush())
2002 return AbortNode(state, "Failed to write to coin database");
2003 nLastFlush = nNow;
2005 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2006 // Update best block in wallet (so we can detect restored wallets).
2007 GetMainSignals().SetBestChain(chainActive.GetLocator());
2008 nLastSetChain = nNow;
2010 } catch (const std::runtime_error& e) {
2011 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2013 return true;
2016 void FlushStateToDisk() {
2017 CValidationState state;
2018 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2021 void PruneAndFlush() {
2022 CValidationState state;
2023 fCheckForPruning = true;
2024 FlushStateToDisk(state, FLUSH_STATE_NONE);
2027 /** Update chainActive and related internal data structures. */
2028 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2029 chainActive.SetTip(pindexNew);
2031 // New best block
2032 mempool.AddTransactionsUpdated(1);
2034 cvBlockChange.notify_all();
2036 static bool fWarned = false;
2037 std::vector<std::string> warningMessages;
2038 if (!IsInitialBlockDownload())
2040 int nUpgraded = 0;
2041 const CBlockIndex* pindex = chainActive.Tip();
2042 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2043 WarningBitsConditionChecker checker(bit);
2044 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2045 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2046 if (state == THRESHOLD_ACTIVE) {
2047 strMiscWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2048 if (!fWarned) {
2049 AlertNotify(strMiscWarning);
2050 fWarned = true;
2052 } else {
2053 warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
2057 // Check the version of the last 100 blocks to see if we need to upgrade:
2058 for (int i = 0; i < 100 && pindex != NULL; i++)
2060 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2061 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2062 ++nUpgraded;
2063 pindex = pindex->pprev;
2065 if (nUpgraded > 0)
2066 warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
2067 if (nUpgraded > 100/2)
2069 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2070 strMiscWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2071 if (!fWarned) {
2072 AlertNotify(strMiscWarning);
2073 fWarned = true;
2077 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
2078 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2079 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2080 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2081 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2082 if (!warningMessages.empty())
2083 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2084 LogPrintf("\n");
2088 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
2089 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
2091 CBlockIndex *pindexDelete = chainActive.Tip();
2092 assert(pindexDelete);
2093 // Read block from disk.
2094 CBlock block;
2095 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2096 return AbortNode(state, "Failed to read block");
2097 // Apply the block atomically to the chain state.
2098 int64_t nStart = GetTimeMicros();
2100 CCoinsViewCache view(pcoinsTip);
2101 if (!DisconnectBlock(block, state, pindexDelete, view))
2102 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2103 assert(view.Flush());
2105 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2106 // Write the chain state to disk, if necessary.
2107 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2108 return false;
2110 if (!fBare) {
2111 // Resurrect mempool transactions from the disconnected block.
2112 std::vector<uint256> vHashUpdate;
2113 for (const auto& it : block.vtx) {
2114 const CTransaction& tx = *it;
2115 // ignore validation errors in resurrected transactions
2116 CValidationState stateDummy;
2117 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL, true)) {
2118 mempool.removeRecursive(tx);
2119 } else if (mempool.exists(tx.GetHash())) {
2120 vHashUpdate.push_back(tx.GetHash());
2123 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2124 // no in-mempool children, which is generally not true when adding
2125 // previously-confirmed transactions back to the mempool.
2126 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2127 // block that were added back and cleans up the mempool state.
2128 mempool.UpdateTransactionsFromBlock(vHashUpdate);
2131 // Update chainActive and related variables.
2132 UpdateTip(pindexDelete->pprev, chainparams);
2133 // Let wallets know transactions went from 1-confirmed to
2134 // 0-confirmed or conflicted:
2135 for (const auto& tx : block.vtx) {
2136 GetMainSignals().SyncTransaction(*tx, pindexDelete->pprev, CMainSignals::SYNC_TRANSACTION_NOT_IN_BLOCK);
2138 return true;
2141 static int64_t nTimeReadFromDisk = 0;
2142 static int64_t nTimeConnectTotal = 0;
2143 static int64_t nTimeFlush = 0;
2144 static int64_t nTimeChainState = 0;
2145 static int64_t nTimePostConnect = 0;
2148 * Used to track blocks whose transactions were applied to the UTXO state as a
2149 * part of a single ActivateBestChainStep call.
2151 struct ConnectTrace {
2152 std::vector<std::pair<CBlockIndex*, std::shared_ptr<const CBlock> > > blocksConnected;
2156 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2157 * corresponding to pindexNew, to bypass loading it again from disk.
2159 * The block is always added to connectTrace (either after loading from disk or by copying
2160 * pblock) - if that is not intended, care must be taken to remove the last entry in
2161 * blocksConnected in case of failure.
2163 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2165 assert(pindexNew->pprev == chainActive.Tip());
2166 // Read block from disk.
2167 int64_t nTime1 = GetTimeMicros();
2168 if (!pblock) {
2169 std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2170 connectTrace.blocksConnected.emplace_back(pindexNew, pblockNew);
2171 if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2172 return AbortNode(state, "Failed to read block");
2173 } else {
2174 connectTrace.blocksConnected.emplace_back(pindexNew, pblock);
2176 const CBlock& blockConnecting = *connectTrace.blocksConnected.back().second;
2177 // Apply the block atomically to the chain state.
2178 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2179 int64_t nTime3;
2180 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2182 CCoinsViewCache view(pcoinsTip);
2183 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2184 GetMainSignals().BlockChecked(blockConnecting, state);
2185 if (!rv) {
2186 if (state.IsInvalid())
2187 InvalidBlockFound(pindexNew, state);
2188 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2190 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2191 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2192 assert(view.Flush());
2194 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2195 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2196 // Write the chain state to disk, if necessary.
2197 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2198 return false;
2199 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2200 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2201 // Remove conflicting transactions from the mempool.;
2202 mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight, !IsInitialBlockDownload());
2203 // Update chainActive & related variables.
2204 UpdateTip(pindexNew, chainparams);
2206 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2207 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2208 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2209 return true;
2213 * Return the tip of the chain with the most work in it, that isn't
2214 * known to be invalid (it's however far from certain to be valid).
2216 static CBlockIndex* FindMostWorkChain() {
2217 do {
2218 CBlockIndex *pindexNew = NULL;
2220 // Find the best candidate header.
2222 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2223 if (it == setBlockIndexCandidates.rend())
2224 return NULL;
2225 pindexNew = *it;
2228 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2229 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2230 CBlockIndex *pindexTest = pindexNew;
2231 bool fInvalidAncestor = false;
2232 while (pindexTest && !chainActive.Contains(pindexTest)) {
2233 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2235 // Pruned nodes may have entries in setBlockIndexCandidates for
2236 // which block files have been deleted. Remove those as candidates
2237 // for the most work chain if we come across them; we can't switch
2238 // to a chain unless we have all the non-active-chain parent blocks.
2239 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2240 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2241 if (fFailedChain || fMissingData) {
2242 // Candidate chain is not usable (either invalid or missing data)
2243 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2244 pindexBestInvalid = pindexNew;
2245 CBlockIndex *pindexFailed = pindexNew;
2246 // Remove the entire chain from the set.
2247 while (pindexTest != pindexFailed) {
2248 if (fFailedChain) {
2249 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2250 } else if (fMissingData) {
2251 // If we're missing data, then add back to mapBlocksUnlinked,
2252 // so that if the block arrives in the future we can try adding
2253 // to setBlockIndexCandidates again.
2254 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2256 setBlockIndexCandidates.erase(pindexFailed);
2257 pindexFailed = pindexFailed->pprev;
2259 setBlockIndexCandidates.erase(pindexTest);
2260 fInvalidAncestor = true;
2261 break;
2263 pindexTest = pindexTest->pprev;
2265 if (!fInvalidAncestor)
2266 return pindexNew;
2267 } while(true);
2270 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2271 static void PruneBlockIndexCandidates() {
2272 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2273 // reorganization to a better block fails.
2274 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2275 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2276 setBlockIndexCandidates.erase(it++);
2278 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2279 assert(!setBlockIndexCandidates.empty());
2283 * Try to make some progress towards making pindexMostWork the active block.
2284 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2286 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2288 AssertLockHeld(cs_main);
2289 const CBlockIndex *pindexOldTip = chainActive.Tip();
2290 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2292 // Disconnect active blocks which are no longer in the best chain.
2293 bool fBlocksDisconnected = false;
2294 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2295 if (!DisconnectTip(state, chainparams))
2296 return false;
2297 fBlocksDisconnected = true;
2300 // Build list of new blocks to connect.
2301 std::vector<CBlockIndex*> vpindexToConnect;
2302 bool fContinue = true;
2303 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2304 while (fContinue && nHeight != pindexMostWork->nHeight) {
2305 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2306 // a few blocks along the way.
2307 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2308 vpindexToConnect.clear();
2309 vpindexToConnect.reserve(nTargetHeight - nHeight);
2310 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2311 while (pindexIter && pindexIter->nHeight != nHeight) {
2312 vpindexToConnect.push_back(pindexIter);
2313 pindexIter = pindexIter->pprev;
2315 nHeight = nTargetHeight;
2317 // Connect new blocks.
2318 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2319 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2320 if (state.IsInvalid()) {
2321 // The block violates a consensus rule.
2322 if (!state.CorruptionPossible())
2323 InvalidChainFound(vpindexToConnect.back());
2324 state = CValidationState();
2325 fInvalidFound = true;
2326 fContinue = false;
2327 // If we didn't actually connect the block, don't notify listeners about it
2328 connectTrace.blocksConnected.pop_back();
2329 break;
2330 } else {
2331 // A system error occurred (disk space, database error, ...).
2332 return false;
2334 } else {
2335 PruneBlockIndexCandidates();
2336 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2337 // We're in a better position than we were. Return temporarily to release the lock.
2338 fContinue = false;
2339 break;
2345 if (fBlocksDisconnected) {
2346 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2347 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2349 mempool.check(pcoinsTip);
2351 // Callbacks/notifications for a new best chain.
2352 if (fInvalidFound)
2353 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2354 else
2355 CheckForkWarningConditions();
2357 return true;
2360 static void NotifyHeaderTip() {
2361 bool fNotify = false;
2362 bool fInitialBlockDownload = false;
2363 static CBlockIndex* pindexHeaderOld = NULL;
2364 CBlockIndex* pindexHeader = NULL;
2366 LOCK(cs_main);
2367 pindexHeader = pindexBestHeader;
2369 if (pindexHeader != pindexHeaderOld) {
2370 fNotify = true;
2371 fInitialBlockDownload = IsInitialBlockDownload();
2372 pindexHeaderOld = pindexHeader;
2375 // Send block tip changed notifications without cs_main
2376 if (fNotify) {
2377 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2382 * Make the best chain active, in multiple steps. The result is either failure
2383 * or an activated best chain. pblock is either NULL or a pointer to a block
2384 * that is already loaded (to avoid loading it again from disk).
2386 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2387 CBlockIndex *pindexMostWork = NULL;
2388 CBlockIndex *pindexNewTip = NULL;
2389 do {
2390 boost::this_thread::interruption_point();
2391 if (ShutdownRequested())
2392 break;
2394 const CBlockIndex *pindexFork;
2395 ConnectTrace connectTrace;
2396 bool fInitialDownload;
2398 LOCK(cs_main);
2399 CBlockIndex *pindexOldTip = chainActive.Tip();
2400 if (pindexMostWork == NULL) {
2401 pindexMostWork = FindMostWorkChain();
2404 // Whether we have anything to do at all.
2405 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2406 return true;
2408 bool fInvalidFound = false;
2409 std::shared_ptr<const CBlock> nullBlockPtr;
2410 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2411 return false;
2413 if (fInvalidFound) {
2414 // Wipe cache, we may need another branch now.
2415 pindexMostWork = NULL;
2417 pindexNewTip = chainActive.Tip();
2418 pindexFork = chainActive.FindFork(pindexOldTip);
2419 fInitialDownload = IsInitialBlockDownload();
2421 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2423 // Notifications/callbacks that can run without cs_main
2425 // throw all transactions though the signal-interface
2426 // while _not_ holding the cs_main lock
2427 for (const auto& pair : connectTrace.blocksConnected) {
2428 assert(pair.second);
2429 const CBlock& block = *(pair.second);
2430 for (unsigned int i = 0; i < block.vtx.size(); i++)
2431 GetMainSignals().SyncTransaction(*block.vtx[i], pair.first, i);
2434 // Notify external listeners about the new tip.
2435 GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2437 // Always notify the UI if a new block tip was connected
2438 if (pindexFork != pindexNewTip) {
2439 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2441 } while (pindexNewTip != pindexMostWork);
2442 CheckBlockIndex(chainparams.GetConsensus());
2444 // Write changes periodically to disk, after relay.
2445 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2446 return false;
2449 return true;
2453 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2456 LOCK(cs_main);
2457 if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2458 // Nothing to do, this block is not at the tip.
2459 return true;
2461 if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2462 // The chain has been extended since the last call, reset the counter.
2463 nBlockReverseSequenceId = -1;
2465 nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2466 setBlockIndexCandidates.erase(pindex);
2467 pindex->nSequenceId = nBlockReverseSequenceId;
2468 if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2469 // We can't keep reducing the counter if somebody really wants to
2470 // call preciousblock 2**31-1 times on the same set of tips...
2471 nBlockReverseSequenceId--;
2473 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2474 setBlockIndexCandidates.insert(pindex);
2475 PruneBlockIndexCandidates();
2479 return ActivateBestChain(state, params);
2482 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2484 AssertLockHeld(cs_main);
2486 // Mark the block itself as invalid.
2487 pindex->nStatus |= BLOCK_FAILED_VALID;
2488 setDirtyBlockIndex.insert(pindex);
2489 setBlockIndexCandidates.erase(pindex);
2491 while (chainActive.Contains(pindex)) {
2492 CBlockIndex *pindexWalk = chainActive.Tip();
2493 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2494 setDirtyBlockIndex.insert(pindexWalk);
2495 setBlockIndexCandidates.erase(pindexWalk);
2496 // ActivateBestChain considers blocks already in chainActive
2497 // unconditionally valid already, so force disconnect away from it.
2498 if (!DisconnectTip(state, chainparams)) {
2499 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2500 return false;
2504 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2506 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2507 // add it again.
2508 BlockMap::iterator it = mapBlockIndex.begin();
2509 while (it != mapBlockIndex.end()) {
2510 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2511 setBlockIndexCandidates.insert(it->second);
2513 it++;
2516 InvalidChainFound(pindex);
2517 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2518 uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
2519 return true;
2522 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
2523 AssertLockHeld(cs_main);
2525 int nHeight = pindex->nHeight;
2527 // Remove the invalidity flag from this block and all its descendants.
2528 BlockMap::iterator it = mapBlockIndex.begin();
2529 while (it != mapBlockIndex.end()) {
2530 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2531 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2532 setDirtyBlockIndex.insert(it->second);
2533 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2534 setBlockIndexCandidates.insert(it->second);
2536 if (it->second == pindexBestInvalid) {
2537 // Reset invalid block marker if it was pointing to one of those.
2538 pindexBestInvalid = NULL;
2541 it++;
2544 // Remove the invalidity flag from all ancestors too.
2545 while (pindex != NULL) {
2546 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2547 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2548 setDirtyBlockIndex.insert(pindex);
2550 pindex = pindex->pprev;
2552 return true;
2555 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2557 // Check for duplicate
2558 uint256 hash = block.GetHash();
2559 BlockMap::iterator it = mapBlockIndex.find(hash);
2560 if (it != mapBlockIndex.end())
2561 return it->second;
2563 // Construct new block index object
2564 CBlockIndex* pindexNew = new CBlockIndex(block);
2565 assert(pindexNew);
2566 // We assign the sequence id to blocks only when the full data is available,
2567 // to avoid miners withholding blocks but broadcasting headers, to get a
2568 // competitive advantage.
2569 pindexNew->nSequenceId = 0;
2570 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2571 pindexNew->phashBlock = &((*mi).first);
2572 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2573 if (miPrev != mapBlockIndex.end())
2575 pindexNew->pprev = (*miPrev).second;
2576 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2577 pindexNew->BuildSkip();
2579 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2580 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2581 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2582 pindexBestHeader = pindexNew;
2584 setDirtyBlockIndex.insert(pindexNew);
2586 return pindexNew;
2589 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2590 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2592 pindexNew->nTx = block.vtx.size();
2593 pindexNew->nChainTx = 0;
2594 pindexNew->nFile = pos.nFile;
2595 pindexNew->nDataPos = pos.nPos;
2596 pindexNew->nUndoPos = 0;
2597 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2598 if (IsWitnessEnabled(pindexNew->pprev, Params().GetConsensus())) {
2599 pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2601 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2602 setDirtyBlockIndex.insert(pindexNew);
2604 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2605 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2606 deque<CBlockIndex*> queue;
2607 queue.push_back(pindexNew);
2609 // Recursively process any descendant blocks that now may be eligible to be connected.
2610 while (!queue.empty()) {
2611 CBlockIndex *pindex = queue.front();
2612 queue.pop_front();
2613 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2615 LOCK(cs_nBlockSequenceId);
2616 pindex->nSequenceId = nBlockSequenceId++;
2618 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2619 setBlockIndexCandidates.insert(pindex);
2621 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2622 while (range.first != range.second) {
2623 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2624 queue.push_back(it->second);
2625 range.first++;
2626 mapBlocksUnlinked.erase(it);
2629 } else {
2630 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2631 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2635 return true;
2638 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2640 LOCK(cs_LastBlockFile);
2642 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2643 if (vinfoBlockFile.size() <= nFile) {
2644 vinfoBlockFile.resize(nFile + 1);
2647 if (!fKnown) {
2648 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2649 nFile++;
2650 if (vinfoBlockFile.size() <= nFile) {
2651 vinfoBlockFile.resize(nFile + 1);
2654 pos.nFile = nFile;
2655 pos.nPos = vinfoBlockFile[nFile].nSize;
2658 if ((int)nFile != nLastBlockFile) {
2659 if (!fKnown) {
2660 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2662 FlushBlockFile(!fKnown);
2663 nLastBlockFile = nFile;
2666 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2667 if (fKnown)
2668 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2669 else
2670 vinfoBlockFile[nFile].nSize += nAddSize;
2672 if (!fKnown) {
2673 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2674 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2675 if (nNewChunks > nOldChunks) {
2676 if (fPruneMode)
2677 fCheckForPruning = true;
2678 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2679 FILE *file = OpenBlockFile(pos);
2680 if (file) {
2681 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2682 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2683 fclose(file);
2686 else
2687 return state.Error("out of disk space");
2691 setDirtyFileInfo.insert(nFile);
2692 return true;
2695 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2697 pos.nFile = nFile;
2699 LOCK(cs_LastBlockFile);
2701 unsigned int nNewSize;
2702 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2703 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2704 setDirtyFileInfo.insert(nFile);
2706 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2707 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2708 if (nNewChunks > nOldChunks) {
2709 if (fPruneMode)
2710 fCheckForPruning = true;
2711 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2712 FILE *file = OpenUndoFile(pos);
2713 if (file) {
2714 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2715 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2716 fclose(file);
2719 else
2720 return state.Error("out of disk space");
2723 return true;
2726 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW)
2728 // Check proof of work matches claimed amount
2729 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
2730 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2732 return true;
2735 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
2737 // These are checks that are independent of context.
2739 if (block.fChecked)
2740 return true;
2742 // Check that the header is valid (particularly PoW). This is mostly
2743 // redundant with the call in AcceptBlockHeader.
2744 if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
2745 return false;
2747 // Check the merkle root.
2748 if (fCheckMerkleRoot) {
2749 bool mutated;
2750 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2751 if (block.hashMerkleRoot != hashMerkleRoot2)
2752 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2754 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2755 // of transactions in a block without affecting the merkle root of a block,
2756 // while still invalidating it.
2757 if (mutated)
2758 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2761 // All potential-corruption validation must be done before we do any
2762 // transaction validation, as otherwise we may mark the header as invalid
2763 // because we receive the wrong transactions for it.
2764 // Note that witness malleability is checked in ContextualCheckBlock, so no
2765 // checks that use witness data may be performed here.
2767 // Size limits
2768 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)
2769 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2771 // First transaction must be coinbase, the rest must not be
2772 if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2773 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2774 for (unsigned int i = 1; i < block.vtx.size(); i++)
2775 if (block.vtx[i]->IsCoinBase())
2776 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2778 // Check transactions
2779 for (const auto& tx : block.vtx)
2780 if (!CheckTransaction(*tx, state, false))
2781 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2782 strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2784 unsigned int nSigOps = 0;
2785 for (const auto& tx : block.vtx)
2787 nSigOps += GetLegacySigOpCount(*tx);
2789 if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2790 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2792 if (fCheckPOW && fCheckMerkleRoot)
2793 block.fChecked = true;
2795 return true;
2798 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2800 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2801 return true;
2803 int nHeight = pindexPrev->nHeight+1;
2804 // Don't accept any forks from the main chain prior to last checkpoint
2805 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2806 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2807 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2809 return true;
2812 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2814 LOCK(cs_main);
2815 return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2818 // Compute at which vout of the block's coinbase transaction the witness
2819 // commitment occurs, or -1 if not found.
2820 static int GetWitnessCommitmentIndex(const CBlock& block)
2822 int commitpos = -1;
2823 for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2824 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) {
2825 commitpos = o;
2828 return commitpos;
2831 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2833 int commitpos = GetWitnessCommitmentIndex(block);
2834 static const std::vector<unsigned char> nonce(32, 0x00);
2835 if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && block.vtx[0]->wit.IsEmpty()) {
2836 CMutableTransaction tx(*block.vtx[0]);
2837 tx.wit.vtxinwit.resize(1);
2838 tx.wit.vtxinwit[0].scriptWitness.stack.resize(1);
2839 tx.wit.vtxinwit[0].scriptWitness.stack[0] = nonce;
2840 block.vtx[0] = MakeTransactionRef(std::move(tx));
2844 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2846 std::vector<unsigned char> commitment;
2847 int commitpos = GetWitnessCommitmentIndex(block);
2848 std::vector<unsigned char> ret(32, 0x00);
2849 if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2850 if (commitpos == -1) {
2851 uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2852 CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2853 CTxOut out;
2854 out.nValue = 0;
2855 out.scriptPubKey.resize(38);
2856 out.scriptPubKey[0] = OP_RETURN;
2857 out.scriptPubKey[1] = 0x24;
2858 out.scriptPubKey[2] = 0xaa;
2859 out.scriptPubKey[3] = 0x21;
2860 out.scriptPubKey[4] = 0xa9;
2861 out.scriptPubKey[5] = 0xed;
2862 memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2863 commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2864 CMutableTransaction tx(*block.vtx[0]);
2865 tx.vout.push_back(out);
2866 block.vtx[0] = MakeTransactionRef(std::move(tx));
2869 UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
2870 return commitment;
2873 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
2875 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2876 // Check proof of work
2877 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2878 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
2880 // Check timestamp against prev
2881 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2882 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
2884 // Check timestamp
2885 if (block.GetBlockTime() > nAdjustedTime + 2 * 60 * 60)
2886 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
2888 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
2889 // check for version 2, 3 and 4 upgrades
2890 if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
2891 (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
2892 (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
2893 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
2894 strprintf("rejected nVersion=0x%08x block", block.nVersion));
2896 return true;
2899 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
2901 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2903 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
2904 int nLockTimeFlags = 0;
2905 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2906 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
2909 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2910 ? pindexPrev->GetMedianTimePast()
2911 : block.GetBlockTime();
2913 // Check that all transactions are finalized
2914 for (const auto& tx : block.vtx) {
2915 if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
2916 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
2920 // Enforce rule that the coinbase starts with serialized block height
2921 if (nHeight >= consensusParams.BIP34Height)
2923 CScript expect = CScript() << nHeight;
2924 if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
2925 !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
2926 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
2930 // Validation for witness commitments.
2931 // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
2932 // coinbase (where 0x0000....0000 is used instead).
2933 // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
2934 // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
2935 // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
2936 // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
2937 // multiple, the last one is used.
2938 bool fHaveWitness = false;
2939 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
2940 int commitpos = GetWitnessCommitmentIndex(block);
2941 if (commitpos != -1) {
2942 bool malleated = false;
2943 uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
2944 // The malleation check is ignored; as the transaction tree itself
2945 // already does not permit it, it is impossible to trigger in the
2946 // witness tree.
2947 if (block.vtx[0]->wit.vtxinwit.size() != 1 || block.vtx[0]->wit.vtxinwit[0].scriptWitness.stack.size() != 1 || block.vtx[0]->wit.vtxinwit[0].scriptWitness.stack[0].size() != 32) {
2948 return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
2950 CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->wit.vtxinwit[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
2951 if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
2952 return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
2954 fHaveWitness = true;
2958 // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
2959 if (!fHaveWitness) {
2960 for (size_t i = 0; i < block.vtx.size(); i++) {
2961 if (!block.vtx[i]->wit.IsNull()) {
2962 return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
2967 // After the coinbase witness nonce and commitment are verified,
2968 // we can check if the block weight passes (before we've checked the
2969 // coinbase witness, it would be possible for the weight to be too
2970 // large by filling up the coinbase witness, which doesn't change
2971 // the block hash, so we couldn't mark the block as permanently
2972 // failed).
2973 if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
2974 return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
2977 return true;
2980 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
2982 AssertLockHeld(cs_main);
2983 // Check for duplicate
2984 uint256 hash = block.GetHash();
2985 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2986 CBlockIndex *pindex = NULL;
2987 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2989 if (miSelf != mapBlockIndex.end()) {
2990 // Block header is already known.
2991 pindex = miSelf->second;
2992 if (ppindex)
2993 *ppindex = pindex;
2994 if (pindex->nStatus & BLOCK_FAILED_MASK)
2995 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
2996 return true;
2999 if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3000 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3002 // Get prev block index
3003 CBlockIndex* pindexPrev = NULL;
3004 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3005 if (mi == mapBlockIndex.end())
3006 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3007 pindexPrev = (*mi).second;
3008 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3009 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3011 assert(pindexPrev);
3012 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3013 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3015 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3016 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3018 if (pindex == NULL)
3019 pindex = AddToBlockIndex(block);
3021 if (ppindex)
3022 *ppindex = pindex;
3024 CheckBlockIndex(chainparams.GetConsensus());
3026 return true;
3029 // Exposed wrapper for AcceptBlockHeader
3030 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3033 LOCK(cs_main);
3034 for (const CBlockHeader& header : headers) {
3035 if (!AcceptBlockHeader(header, state, chainparams, ppindex)) {
3036 return false;
3040 NotifyHeaderTip();
3041 return true;
3044 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3045 static bool AcceptBlock(const CBlock& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3047 if (fNewBlock) *fNewBlock = false;
3048 AssertLockHeld(cs_main);
3050 CBlockIndex *pindexDummy = NULL;
3051 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3053 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3054 return false;
3056 // Try to process all requested blocks that we don't have, but only
3057 // process an unrequested block if it's new and has enough work to
3058 // advance our tip, and isn't too many blocks ahead.
3059 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3060 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3061 // Blocks that are too out-of-order needlessly limit the effectiveness of
3062 // pruning, because pruning will not delete block files that contain any
3063 // blocks which are too close in height to the tip. Apply this test
3064 // regardless of whether pruning is enabled; it should generally be safe to
3065 // not process unrequested blocks.
3066 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3068 // TODO: Decouple this function from the block download logic by removing fRequested
3069 // This requires some new chain datastructure to efficiently look up if a
3070 // block is in a chain leading to a candidate for best tip, despite not
3071 // being such a candidate itself.
3073 // TODO: deal better with return value and error conditions for duplicate
3074 // and unrequested blocks.
3075 if (fAlreadyHave) return true;
3076 if (!fRequested) { // If we didn't ask for it:
3077 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3078 if (!fHasMoreWork) return true; // Don't process less-work chains
3079 if (fTooFarAhead) return true; // Block height is too high
3081 if (fNewBlock) *fNewBlock = true;
3083 if (!CheckBlock(block, state, chainparams.GetConsensus(), GetAdjustedTime()) ||
3084 !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3085 if (state.IsInvalid() && !state.CorruptionPossible()) {
3086 pindex->nStatus |= BLOCK_FAILED_VALID;
3087 setDirtyBlockIndex.insert(pindex);
3089 return error("%s: %s", __func__, FormatStateMessage(state));
3092 int nHeight = pindex->nHeight;
3094 // Write block to history file
3095 try {
3096 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3097 CDiskBlockPos blockPos;
3098 if (dbp != NULL)
3099 blockPos = *dbp;
3100 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3101 return error("AcceptBlock(): FindBlockPos failed");
3102 if (dbp == NULL)
3103 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3104 AbortNode(state, "Failed to write block");
3105 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3106 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3107 } catch (const std::runtime_error& e) {
3108 return AbortNode(state, std::string("System error: ") + e.what());
3111 if (fCheckForPruning)
3112 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3114 return true;
3117 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, const CDiskBlockPos* dbp, bool *fNewBlock)
3120 LOCK(cs_main);
3122 // Store to disk
3123 CBlockIndex *pindex = NULL;
3124 if (fNewBlock) *fNewBlock = false;
3125 CValidationState state;
3126 bool ret = AcceptBlock(*pblock, state, chainparams, &pindex, fForceProcessing, dbp, fNewBlock);
3127 CheckBlockIndex(chainparams.GetConsensus());
3128 if (!ret) {
3129 GetMainSignals().BlockChecked(*pblock, state);
3130 return error("%s: AcceptBlock FAILED", __func__);
3134 NotifyHeaderTip();
3136 CValidationState state; // Only used to report errors, not invalidity - ignore it
3137 if (!ActivateBestChain(state, chainparams, pblock))
3138 return error("%s: ActivateBestChain failed", __func__);
3140 return true;
3143 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3145 AssertLockHeld(cs_main);
3146 assert(pindexPrev && pindexPrev == chainActive.Tip());
3147 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3148 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3150 CCoinsViewCache viewNew(pcoinsTip);
3151 CBlockIndex indexDummy(block);
3152 indexDummy.pprev = pindexPrev;
3153 indexDummy.nHeight = pindexPrev->nHeight + 1;
3155 // NOTE: CheckBlockHeader is called by CheckBlock
3156 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev, GetAdjustedTime()))
3157 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3158 if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3159 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3160 if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3161 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3162 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3163 return false;
3164 assert(state.IsValid());
3166 return true;
3170 * BLOCK PRUNING CODE
3173 /* Calculate the amount of disk space the block & undo files currently use */
3174 uint64_t CalculateCurrentUsage()
3176 uint64_t retval = 0;
3177 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3178 retval += file.nSize + file.nUndoSize;
3180 return retval;
3183 /* Prune a block file (modify associated database entries)*/
3184 void PruneOneBlockFile(const int fileNumber)
3186 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3187 CBlockIndex* pindex = it->second;
3188 if (pindex->nFile == fileNumber) {
3189 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3190 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3191 pindex->nFile = 0;
3192 pindex->nDataPos = 0;
3193 pindex->nUndoPos = 0;
3194 setDirtyBlockIndex.insert(pindex);
3196 // Prune from mapBlocksUnlinked -- any block we prune would have
3197 // to be downloaded again in order to consider its chain, at which
3198 // point it would be considered as a candidate for
3199 // mapBlocksUnlinked or setBlockIndexCandidates.
3200 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3201 while (range.first != range.second) {
3202 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3203 range.first++;
3204 if (_it->second == pindex) {
3205 mapBlocksUnlinked.erase(_it);
3211 vinfoBlockFile[fileNumber].SetNull();
3212 setDirtyFileInfo.insert(fileNumber);
3216 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3218 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3219 CDiskBlockPos pos(*it, 0);
3220 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3221 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3222 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3226 /* Calculate the block/rev files that should be deleted to remain under target*/
3227 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3229 LOCK2(cs_main, cs_LastBlockFile);
3230 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3231 return;
3233 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3234 return;
3237 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3238 uint64_t nCurrentUsage = CalculateCurrentUsage();
3239 // We don't check to prune until after we've allocated new space for files
3240 // So we should leave a buffer under our target to account for another allocation
3241 // before the next pruning.
3242 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3243 uint64_t nBytesToPrune;
3244 int count=0;
3246 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3247 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3248 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3250 if (vinfoBlockFile[fileNumber].nSize == 0)
3251 continue;
3253 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3254 break;
3256 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3257 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3258 continue;
3260 PruneOneBlockFile(fileNumber);
3261 // Queue up the files for removal
3262 setFilesToPrune.insert(fileNumber);
3263 nCurrentUsage -= nBytesToPrune;
3264 count++;
3268 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3269 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3270 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3271 nLastBlockWeCanPrune, count);
3274 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3276 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3278 // Check for nMinDiskSpace bytes (currently 50MB)
3279 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3280 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3282 return true;
3285 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3287 if (pos.IsNull())
3288 return NULL;
3289 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3290 boost::filesystem::create_directories(path.parent_path());
3291 FILE* file = fopen(path.string().c_str(), "rb+");
3292 if (!file && !fReadOnly)
3293 file = fopen(path.string().c_str(), "wb+");
3294 if (!file) {
3295 LogPrintf("Unable to open file %s\n", path.string());
3296 return NULL;
3298 if (pos.nPos) {
3299 if (fseek(file, pos.nPos, SEEK_SET)) {
3300 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3301 fclose(file);
3302 return NULL;
3305 return file;
3308 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3309 return OpenDiskFile(pos, "blk", fReadOnly);
3312 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3313 return OpenDiskFile(pos, "rev", fReadOnly);
3316 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3318 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3321 CBlockIndex * InsertBlockIndex(uint256 hash)
3323 if (hash.IsNull())
3324 return NULL;
3326 // Return existing
3327 BlockMap::iterator mi = mapBlockIndex.find(hash);
3328 if (mi != mapBlockIndex.end())
3329 return (*mi).second;
3331 // Create new
3332 CBlockIndex* pindexNew = new CBlockIndex();
3333 if (!pindexNew)
3334 throw runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3335 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3336 pindexNew->phashBlock = &((*mi).first);
3338 return pindexNew;
3341 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3343 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3344 return false;
3346 boost::this_thread::interruption_point();
3348 // Calculate nChainWork
3349 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3350 vSortedByHeight.reserve(mapBlockIndex.size());
3351 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3353 CBlockIndex* pindex = item.second;
3354 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3356 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3357 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3359 CBlockIndex* pindex = item.second;
3360 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3361 // We can link the chain of blocks for which we've received transactions at some point.
3362 // Pruned nodes may have deleted the block.
3363 if (pindex->nTx > 0) {
3364 if (pindex->pprev) {
3365 if (pindex->pprev->nChainTx) {
3366 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3367 } else {
3368 pindex->nChainTx = 0;
3369 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3371 } else {
3372 pindex->nChainTx = pindex->nTx;
3375 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3376 setBlockIndexCandidates.insert(pindex);
3377 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3378 pindexBestInvalid = pindex;
3379 if (pindex->pprev)
3380 pindex->BuildSkip();
3381 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3382 pindexBestHeader = pindex;
3385 // Load block file info
3386 pblocktree->ReadLastBlockFile(nLastBlockFile);
3387 vinfoBlockFile.resize(nLastBlockFile + 1);
3388 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3389 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3390 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3392 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3393 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3394 CBlockFileInfo info;
3395 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3396 vinfoBlockFile.push_back(info);
3397 } else {
3398 break;
3402 // Check presence of blk files
3403 LogPrintf("Checking all blk files are present...\n");
3404 set<int> setBlkDataFiles;
3405 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3407 CBlockIndex* pindex = item.second;
3408 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3409 setBlkDataFiles.insert(pindex->nFile);
3412 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3414 CDiskBlockPos pos(*it, 0);
3415 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3416 return false;
3420 // Check whether we have ever pruned block & undo files
3421 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3422 if (fHavePruned)
3423 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3425 // Check whether we need to continue reindexing
3426 bool fReindexing = false;
3427 pblocktree->ReadReindexing(fReindexing);
3428 fReindex |= fReindexing;
3430 // Check whether we have a transaction index
3431 pblocktree->ReadFlag("txindex", fTxIndex);
3432 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3434 // Load pointer to end of best chain
3435 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3436 if (it == mapBlockIndex.end())
3437 return true;
3438 chainActive.SetTip(it->second);
3440 PruneBlockIndexCandidates();
3442 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3443 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3444 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3445 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3447 return true;
3450 CVerifyDB::CVerifyDB()
3452 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3455 CVerifyDB::~CVerifyDB()
3457 uiInterface.ShowProgress("", 100);
3460 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3462 LOCK(cs_main);
3463 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3464 return true;
3466 // Verify blocks in the best chain
3467 if (nCheckDepth <= 0)
3468 nCheckDepth = 1000000000; // suffices until the year 19000
3469 if (nCheckDepth > chainActive.Height())
3470 nCheckDepth = chainActive.Height();
3471 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3472 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3473 CCoinsViewCache coins(coinsview);
3474 CBlockIndex* pindexState = chainActive.Tip();
3475 CBlockIndex* pindexFailure = NULL;
3476 int nGoodTransactions = 0;
3477 CValidationState state;
3478 int reportDone = 0;
3479 LogPrintf("[0%%]...");
3480 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3482 boost::this_thread::interruption_point();
3483 int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3484 if (reportDone < percentageDone/10) {
3485 // report every 10% step
3486 LogPrintf("[%d%%]...", percentageDone);
3487 reportDone = percentageDone/10;
3489 uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3490 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3491 break;
3492 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3493 // If pruning, only go back as far as we have data.
3494 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3495 break;
3497 CBlock block;
3498 // check level 0: read from disk
3499 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3500 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3501 // check level 1: verify block validity
3502 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
3503 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3504 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3505 // check level 2: verify undo validity
3506 if (nCheckLevel >= 2 && pindex) {
3507 CBlockUndo undo;
3508 CDiskBlockPos pos = pindex->GetUndoPos();
3509 if (!pos.IsNull()) {
3510 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3511 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3514 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3515 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3516 bool fClean = true;
3517 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3518 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3519 pindexState = pindex->pprev;
3520 if (!fClean) {
3521 nGoodTransactions = 0;
3522 pindexFailure = pindex;
3523 } else
3524 nGoodTransactions += block.vtx.size();
3526 if (ShutdownRequested())
3527 return true;
3529 if (pindexFailure)
3530 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3532 // check level 4: try reconnecting blocks
3533 if (nCheckLevel >= 4) {
3534 CBlockIndex *pindex = pindexState;
3535 while (pindex != chainActive.Tip()) {
3536 boost::this_thread::interruption_point();
3537 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3538 pindex = chainActive.Next(pindex);
3539 CBlock block;
3540 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3541 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3542 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3543 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3547 LogPrintf("[DONE].\n");
3548 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3550 return true;
3553 bool RewindBlockIndex(const CChainParams& params)
3555 LOCK(cs_main);
3557 int nHeight = 1;
3558 while (nHeight <= chainActive.Height()) {
3559 if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3560 break;
3562 nHeight++;
3565 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3566 CValidationState state;
3567 CBlockIndex* pindex = chainActive.Tip();
3568 while (chainActive.Height() >= nHeight) {
3569 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3570 // If pruning, don't try rewinding past the HAVE_DATA point;
3571 // since older blocks can't be served anyway, there's
3572 // no need to walk further, and trying to DisconnectTip()
3573 // will fail (and require a needless reindex/redownload
3574 // of the blockchain).
3575 break;
3577 if (!DisconnectTip(state, params, true)) {
3578 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3580 // Occasionally flush state to disk.
3581 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3582 return false;
3585 // Reduce validity flag and have-data flags.
3586 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3587 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3588 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3589 CBlockIndex* pindexIter = it->second;
3591 // Note: If we encounter an insufficiently validated block that
3592 // is on chainActive, it must be because we are a pruning node, and
3593 // this block or some successor doesn't HAVE_DATA, so we were unable to
3594 // rewind all the way. Blocks remaining on chainActive at this point
3595 // must not have their validity reduced.
3596 if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3597 // Reduce validity
3598 pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3599 // Remove have-data flags.
3600 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3601 // Remove storage location.
3602 pindexIter->nFile = 0;
3603 pindexIter->nDataPos = 0;
3604 pindexIter->nUndoPos = 0;
3605 // Remove various other things
3606 pindexIter->nTx = 0;
3607 pindexIter->nChainTx = 0;
3608 pindexIter->nSequenceId = 0;
3609 // Make sure it gets written.
3610 setDirtyBlockIndex.insert(pindexIter);
3611 // Update indexes
3612 setBlockIndexCandidates.erase(pindexIter);
3613 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3614 while (ret.first != ret.second) {
3615 if (ret.first->second == pindexIter) {
3616 mapBlocksUnlinked.erase(ret.first++);
3617 } else {
3618 ++ret.first;
3621 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3622 setBlockIndexCandidates.insert(pindexIter);
3626 PruneBlockIndexCandidates();
3628 CheckBlockIndex(params.GetConsensus());
3630 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3631 return false;
3634 return true;
3637 // May NOT be used after any connections are up as much
3638 // of the peer-processing logic assumes a consistent
3639 // block index state
3640 void UnloadBlockIndex()
3642 LOCK(cs_main);
3643 setBlockIndexCandidates.clear();
3644 chainActive.SetTip(NULL);
3645 pindexBestInvalid = NULL;
3646 pindexBestHeader = NULL;
3647 mempool.clear();
3648 mapBlocksUnlinked.clear();
3649 vinfoBlockFile.clear();
3650 nLastBlockFile = 0;
3651 nBlockSequenceId = 1;
3652 setDirtyBlockIndex.clear();
3653 setDirtyFileInfo.clear();
3654 versionbitscache.Clear();
3655 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3656 warningcache[b].clear();
3659 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3660 delete entry.second;
3662 mapBlockIndex.clear();
3663 fHavePruned = false;
3666 bool LoadBlockIndex(const CChainParams& chainparams)
3668 // Load block index from databases
3669 if (!fReindex && !LoadBlockIndexDB(chainparams))
3670 return false;
3671 return true;
3674 bool InitBlockIndex(const CChainParams& chainparams)
3676 LOCK(cs_main);
3678 // Check whether we're already initialized
3679 if (chainActive.Genesis() != NULL)
3680 return true;
3682 // Use the provided setting for -txindex in the new database
3683 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3684 pblocktree->WriteFlag("txindex", fTxIndex);
3685 LogPrintf("Initializing databases...\n");
3687 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3688 if (!fReindex) {
3689 try {
3690 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3691 // Start new block file
3692 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3693 CDiskBlockPos blockPos;
3694 CValidationState state;
3695 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3696 return error("LoadBlockIndex(): FindBlockPos failed");
3697 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3698 return error("LoadBlockIndex(): writing genesis block to disk failed");
3699 CBlockIndex *pindex = AddToBlockIndex(block);
3700 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3701 return error("LoadBlockIndex(): genesis block not accepted");
3702 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3703 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3704 } catch (const std::runtime_error& e) {
3705 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3709 return true;
3712 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3714 // Map of disk positions for blocks with unknown parent (only used for reindex)
3715 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3716 int64_t nStart = GetTimeMillis();
3718 int nLoaded = 0;
3719 try {
3720 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3721 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3722 uint64_t nRewind = blkdat.GetPos();
3723 while (!blkdat.eof()) {
3724 boost::this_thread::interruption_point();
3726 blkdat.SetPos(nRewind);
3727 nRewind++; // start one byte further next time, in case of failure
3728 blkdat.SetLimit(); // remove former limit
3729 unsigned int nSize = 0;
3730 try {
3731 // locate a header
3732 unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3733 blkdat.FindByte(chainparams.MessageStart()[0]);
3734 nRewind = blkdat.GetPos()+1;
3735 blkdat >> FLATDATA(buf);
3736 if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3737 continue;
3738 // read size
3739 blkdat >> nSize;
3740 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3741 continue;
3742 } catch (const std::exception&) {
3743 // no valid block header found; don't complain
3744 break;
3746 try {
3747 // read block
3748 uint64_t nBlockPos = blkdat.GetPos();
3749 if (dbp)
3750 dbp->nPos = nBlockPos;
3751 blkdat.SetLimit(nBlockPos + nSize);
3752 blkdat.SetPos(nBlockPos);
3753 CBlock block;
3754 blkdat >> block;
3755 nRewind = blkdat.GetPos();
3757 // detect out of order blocks, and store them for later
3758 uint256 hash = block.GetHash();
3759 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3760 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3761 block.hashPrevBlock.ToString());
3762 if (dbp)
3763 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3764 continue;
3767 // process in case the block isn't known yet
3768 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3769 LOCK(cs_main);
3770 CValidationState state;
3771 if (AcceptBlock(block, state, chainparams, NULL, true, dbp, NULL))
3772 nLoaded++;
3773 if (state.IsError())
3774 break;
3775 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3776 LogPrint("reindex", "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3779 // Activate the genesis block so normal node progress can continue
3780 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
3781 CValidationState state;
3782 if (!ActivateBestChain(state, chainparams)) {
3783 break;
3787 NotifyHeaderTip();
3789 // Recursively process earlier encountered successors of this block
3790 deque<uint256> queue;
3791 queue.push_back(hash);
3792 while (!queue.empty()) {
3793 uint256 head = queue.front();
3794 queue.pop_front();
3795 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3796 while (range.first != range.second) {
3797 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3798 if (ReadBlockFromDisk(block, it->second, chainparams.GetConsensus()))
3800 LogPrint("reindex", "%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3801 head.ToString());
3802 LOCK(cs_main);
3803 CValidationState dummy;
3804 if (AcceptBlock(block, dummy, chainparams, NULL, true, &it->second, NULL))
3806 nLoaded++;
3807 queue.push_back(block.GetHash());
3810 range.first++;
3811 mapBlocksUnknownParent.erase(it);
3812 NotifyHeaderTip();
3815 } catch (const std::exception& e) {
3816 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3819 } catch (const std::runtime_error& e) {
3820 AbortNode(std::string("System error: ") + e.what());
3822 if (nLoaded > 0)
3823 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3824 return nLoaded > 0;
3827 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3829 if (!fCheckBlockIndex) {
3830 return;
3833 LOCK(cs_main);
3835 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3836 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3837 // iterating the block tree require that chainActive has been initialized.)
3838 if (chainActive.Height() < 0) {
3839 assert(mapBlockIndex.size() <= 1);
3840 return;
3843 // Build forward-pointing map of the entire block tree.
3844 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3845 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3846 forward.insert(std::make_pair(it->second->pprev, it->second));
3849 assert(forward.size() == mapBlockIndex.size());
3851 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3852 CBlockIndex *pindex = rangeGenesis.first->second;
3853 rangeGenesis.first++;
3854 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3856 // Iterate over the entire block tree, using depth-first search.
3857 // Along the way, remember whether there are blocks on the path from genesis
3858 // block being explored which are the first to have certain properties.
3859 size_t nNodes = 0;
3860 int nHeight = 0;
3861 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3862 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3863 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3864 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3865 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3866 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3867 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3868 while (pindex != NULL) {
3869 nNodes++;
3870 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3871 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3872 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3873 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3874 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3875 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3876 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3878 // Begin: actual consistency checks.
3879 if (pindex->pprev == NULL) {
3880 // Genesis block checks.
3881 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3882 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3884 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)
3885 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3886 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3887 if (!fHavePruned) {
3888 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3889 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3890 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3891 } else {
3892 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3893 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3895 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3896 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3897 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3898 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3899 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3900 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3901 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.
3902 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3903 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3904 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3905 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3906 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3907 if (pindexFirstInvalid == NULL) {
3908 // Checks for not-invalid blocks.
3909 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3911 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3912 if (pindexFirstInvalid == NULL) {
3913 // If this block sorts at least as good as the current tip and
3914 // is valid and we have all data for its parents, it must be in
3915 // setBlockIndexCandidates. chainActive.Tip() must also be there
3916 // even if some data has been pruned.
3917 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3918 assert(setBlockIndexCandidates.count(pindex));
3920 // If some parent is missing, then it could be that this block was in
3921 // setBlockIndexCandidates but had to be removed because of the missing data.
3922 // In this case it must be in mapBlocksUnlinked -- see test below.
3924 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3925 assert(setBlockIndexCandidates.count(pindex) == 0);
3927 // Check whether this block is in mapBlocksUnlinked.
3928 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3929 bool foundInUnlinked = false;
3930 while (rangeUnlinked.first != rangeUnlinked.second) {
3931 assert(rangeUnlinked.first->first == pindex->pprev);
3932 if (rangeUnlinked.first->second == pindex) {
3933 foundInUnlinked = true;
3934 break;
3936 rangeUnlinked.first++;
3938 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3939 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3940 assert(foundInUnlinked);
3942 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3943 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3944 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3945 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3946 assert(fHavePruned); // We must have pruned.
3947 // This block may have entered mapBlocksUnlinked if:
3948 // - it has a descendant that at some point had more work than the
3949 // tip, and
3950 // - we tried switching to that descendant but were missing
3951 // data for some intermediate block between chainActive and the
3952 // tip.
3953 // So if this block is itself better than chainActive.Tip() and it wasn't in
3954 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3955 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3956 if (pindexFirstInvalid == NULL) {
3957 assert(foundInUnlinked);
3961 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3962 // End: actual consistency checks.
3964 // Try descending into the first subnode.
3965 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3966 if (range.first != range.second) {
3967 // A subnode was found.
3968 pindex = range.first->second;
3969 nHeight++;
3970 continue;
3972 // This is a leaf node.
3973 // Move upwards until we reach a node of which we have not yet visited the last child.
3974 while (pindex) {
3975 // We are going to either move to a parent or a sibling of pindex.
3976 // If pindex was the first with a certain property, unset the corresponding variable.
3977 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3978 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3979 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3980 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3981 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3982 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3983 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3984 // Find our parent.
3985 CBlockIndex* pindexPar = pindex->pprev;
3986 // Find which child we just visited.
3987 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3988 while (rangePar.first->second != pindex) {
3989 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3990 rangePar.first++;
3992 // Proceed to the next one.
3993 rangePar.first++;
3994 if (rangePar.first != rangePar.second) {
3995 // Move to the sibling.
3996 pindex = rangePar.first->second;
3997 break;
3998 } else {
3999 // Move up further.
4000 pindex = pindexPar;
4001 nHeight--;
4002 continue;
4007 // Check that we actually traversed the entire map.
4008 assert(nNodes == forward.size());
4011 std::string GetWarnings(const std::string& strFor)
4013 string strStatusBar;
4014 string strRPC;
4015 string strGUI;
4016 const string uiAlertSeperator = "<hr />";
4018 if (!CLIENT_VERSION_IS_RELEASE) {
4019 strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
4020 strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4023 if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
4024 strStatusBar = strRPC = strGUI = "testsafemode enabled";
4026 // Misc warnings like out of disk space and clock is wrong
4027 if (strMiscWarning != "")
4029 strStatusBar = strMiscWarning;
4030 strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + strMiscWarning;
4033 if (fLargeWorkForkFound)
4035 strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
4036 strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4038 else if (fLargeWorkInvalidChainFound)
4040 strStatusBar = strRPC = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
4041 strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
4044 if (strFor == "gui")
4045 return strGUI;
4046 else if (strFor == "statusbar")
4047 return strStatusBar;
4048 else if (strFor == "rpc")
4049 return strRPC;
4050 assert(!"GetWarnings(): invalid parameter");
4051 return "error";
4053 std::string CBlockFileInfo::ToString() const {
4054 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));
4057 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
4059 LOCK(cs_main);
4060 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4063 int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
4065 LOCK(cs_main);
4066 return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
4069 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4071 bool LoadMempool(void)
4073 int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4074 FILE* filestr = fopen((GetDataDir() / "mempool.dat").string().c_str(), "r");
4075 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4076 if (file.IsNull()) {
4077 LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4078 return false;
4081 int64_t count = 0;
4082 int64_t skipped = 0;
4083 int64_t failed = 0;
4084 int64_t nNow = GetTime();
4086 try {
4087 uint64_t version;
4088 file >> version;
4089 if (version != MEMPOOL_DUMP_VERSION) {
4090 return false;
4092 uint64_t num;
4093 file >> num;
4094 double prioritydummy = 0;
4095 while (num--) {
4096 int64_t nTime;
4097 int64_t nFeeDelta;
4098 CTransaction tx(deserialize, file);
4099 file >> nTime;
4100 file >> nFeeDelta;
4102 CAmount amountdelta = nFeeDelta;
4103 if (amountdelta) {
4104 mempool.PrioritiseTransaction(tx.GetHash(), tx.GetHash().ToString(), prioritydummy, amountdelta);
4106 CValidationState state;
4107 if (nTime + nExpiryTimeout > nNow) {
4108 LOCK(cs_main);
4109 AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
4110 if (state.IsValid()) {
4111 ++count;
4112 } else {
4113 ++failed;
4115 } else {
4116 ++skipped;
4119 std::map<uint256, CAmount> mapDeltas;
4120 file >> mapDeltas;
4122 for (const auto& i : mapDeltas) {
4123 mempool.PrioritiseTransaction(i.first, i.first.ToString(), prioritydummy, i.second);
4125 } catch (const std::exception& e) {
4126 LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4127 return false;
4130 LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4131 return true;
4134 void DumpMempool(void)
4136 int64_t start = GetTimeMicros();
4138 std::map<uint256, CAmount> mapDeltas;
4139 std::vector<TxMempoolInfo> vinfo;
4142 LOCK(mempool.cs);
4143 for (const auto &i : mempool.mapDeltas) {
4144 mapDeltas[i.first] = i.second.first;
4146 vinfo = mempool.infoAll();
4149 int64_t mid = GetTimeMicros();
4151 try {
4152 FILE* filestr = fopen((GetDataDir() / "mempool.dat.new").string().c_str(), "w");
4153 if (!filestr) {
4154 return;
4157 CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4159 uint64_t version = MEMPOOL_DUMP_VERSION;
4160 file << version;
4162 file << (uint64_t)vinfo.size();
4163 for (const auto& i : vinfo) {
4164 file << *(i.tx);
4165 file << (int64_t)i.nTime;
4166 file << (int64_t)i.nFeeDelta;
4167 mapDeltas.erase(i.tx->GetHash());
4170 file << mapDeltas;
4171 FileCommit(file.Get());
4172 file.fclose();
4173 RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4174 int64_t last = GetTimeMicros();
4175 LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4176 } catch (const std::exception& e) {
4177 LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4181 class CMainCleanup
4183 public:
4184 CMainCleanup() {}
4185 ~CMainCleanup() {
4186 // block headers
4187 BlockMap::iterator it1 = mapBlockIndex.begin();
4188 for (; it1 != mapBlockIndex.end(); it1++)
4189 delete (*it1).second;
4190 mapBlockIndex.clear();
4192 } instance_of_cmaincleanup;