Dogecoin Core  1.14.2
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
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.
5 
6 #include "validation.h"
7 
8 #include "alert.h"
9 #include "arith_uint256.h"
10 #include "chainparams.h"
11 #include "checkpoints.h"
12 #include "checkqueue.h"
13 #include "consensus/consensus.h"
14 #include "consensus/merkle.h"
15 #include "consensus/validation.h"
16 #include "dogecoin.h"
17 #include "hash.h"
18 #include "init.h"
19 #include "policy/fees.h"
20 #include "policy/policy.h"
21 #include "pow.h"
22 #include "primitives/block.h"
23 #include "primitives/pureheader.h"
24 #include "primitives/transaction.h"
25 #include "random.h"
26 #include "script/script.h"
27 #include "script/sigcache.h"
28 #include "script/standard.h"
29 #include "timedata.h"
30 #include "tinyformat.h"
31 #include "txdb.h"
32 #include "txmempool.h"
33 #include "ui_interface.h"
34 #include "undo.h"
35 #include "util.h"
36 #include "utilmoneystr.h"
37 #include "utilstrencodings.h"
38 #include "validationinterface.h"
39 #include "versionbits.h"
40 #include "warnings.h"
41 
42 #include <atomic>
43 #include <sstream>
44 
45 #include <boost/algorithm/string/replace.hpp>
46 #include <boost/algorithm/string/join.hpp>
47 #include <boost/bind/bind.hpp>
48 #include <boost/filesystem.hpp>
49 #include <boost/filesystem/fstream.hpp>
50 #include <boost/math/distributions/poisson.hpp>
51 #include <boost/thread.hpp>
52 
53 #if defined(NDEBUG)
54 # error "Dogecoin cannot be compiled without assertions."
55 #endif
56 
62 
69 std::atomic_bool fImporting(false);
70 bool fReindex = false;
71 bool fTxIndex = false;
72 bool fHavePruned = false;
73 bool fPruneMode = false;
74 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
75 bool fRequireStandard = true;
76 bool fCheckBlockIndex = false;
77 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
78 size_t nCoinCacheUsage = 5000 * 300;
79 uint64_t nPruneTarget = 0;
80 bool fAlerts = DEFAULT_ALERTS;
81 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
82 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
83 
85 
86 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
87 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
88 
90 
95 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
96 static void CheckBlockIndex(const Consensus::Params& consensusParams);
97 
100 
101 const std::string strMessageMagic = "Dogecoin Signed Message:\n";
102 
103 // Internal stuff
104 namespace {
105 
106  struct CBlockIndexWorkComparator
107  {
108  bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
109  // First sort by most total work, ...
110  if (pa->nChainWork > pb->nChainWork) return false;
111  if (pa->nChainWork < pb->nChainWork) return true;
112 
113  // ... then by earliest time received, ...
114  if (pa->nSequenceId < pb->nSequenceId) return false;
115  if (pa->nSequenceId > pb->nSequenceId) return true;
116 
117  // Use pointer address as tie breaker (should only happen with blocks
118  // loaded from disk, as those all have id 0).
119  if (pa < pb) return false;
120  if (pa > pb) return true;
121 
122  // Identical blocks.
123  return false;
124  }
125  };
126 
127  CBlockIndex *pindexBestInvalid;
128 
134  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
138  std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
139 
140  CCriticalSection cs_LastBlockFile;
141  std::vector<CBlockFileInfo> vinfoBlockFile;
142  int nLastBlockFile = 0;
147  bool fCheckForPruning = false;
148 
153  CCriticalSection cs_nBlockSequenceId;
155  int32_t nBlockSequenceId = 1;
157  int32_t nBlockReverseSequenceId = -1;
159  arith_uint256 nLastPreciousChainwork = 0;
160 
162  std::set<CBlockIndex*> setDirtyBlockIndex;
163 
165  std::set<int> setDirtyFileInfo;
166 } // anon namespace
167 
168 /* Use this class to start tracking transactions that are removed from the
169  * mempool and pass all those transactions through SyncTransaction when the
170  * object goes out of scope. This is currently only used to call SyncTransaction
171  * on conflicts removed from the mempool during block connection. Applied in
172  * ActivateBestChain around ActivateBestStep which in turn calls:
173  * ConnectTip->removeForBlock->removeConflicts
174  */
176 {
177 private:
178  std::vector<CTransactionRef> conflictedTxs;
180 
181 public:
184  this, boost::placeholders::_1,
185  boost::placeholders::_2));
186  }
187 
189  if (reason == MemPoolRemovalReason::CONFLICT) {
190  conflictedTxs.push_back(txRemoved);
191  }
192  }
193 
196  this, boost::placeholders::_1,
197  boost::placeholders::_2));
198  for (const auto& tx : conflictedTxs) {
200  }
201  conflictedTxs.clear();
202  }
203 };
204 
206 {
207  // Find the first block the caller has in the main chain
208  BOOST_FOREACH(const uint256& hash, locator.vHave) {
209  BlockMap::iterator mi = mapBlockIndex.find(hash);
210  if (mi != mapBlockIndex.end())
211  {
212  CBlockIndex* pindex = (*mi).second;
213  if (chain.Contains(pindex))
214  return pindex;
215  if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
216  return chain.Tip();
217  }
218  }
219  }
220  return chain.Genesis();
221 }
222 
225 
231 };
232 
233 // See definition for documentation
234 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
235 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
236 
237 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
238 {
239  if (tx.nLockTime == 0)
240  return true;
241  if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
242  return true;
243  for (const auto& txin : tx.vin) {
244  if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
245  return false;
246  }
247  return true;
248 }
249 
250 bool CheckFinalTx(const CTransaction &tx, int flags)
251 {
253 
254  // By convention a negative value for flags indicates that the
255  // current network-enforced consensus rules should be used. In
256  // a future soft-fork scenario that would mean checking which
257  // rules would be enforced for the next block and setting the
258  // appropriate flags. At the present time no soft-forks are
259  // scheduled, so no flags are set.
260  flags = std::max(flags, 0);
261 
262  // CheckFinalTx() uses chainActive.Height()+1 to evaluate
263  // nLockTime because when IsFinalTx() is called within
264  // CBlock::AcceptBlock(), the height of the block *being*
265  // evaluated is what is used. Thus if we want to know if a
266  // transaction can be part of the *next* block, we need to call
267  // IsFinalTx() with one more than chainActive.Height().
268  const int nBlockHeight = chainActive.Height() + 1;
269 
270  // BIP113 will require that time-locked transactions have nLockTime set to
271  // less than the median time of the previous block they're contained in.
272  // When the next block is created its previous block will be the current
273  // chain tip, so we use that to calculate the median time passed to
274  // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
275  const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
277  : GetAdjustedTime();
278 
279  return IsFinalTx(tx, nBlockHeight, nBlockTime);
280 }
281 
288 static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
289 {
290  assert(prevHeights->size() == tx.vin.size());
291 
292  // Will be set to the equivalent height- and time-based nLockTime
293  // values that would be necessary to satisfy all relative lock-
294  // time constraints given our view of block chain history.
295  // The semantics of nLockTime are the last invalid height/time, so
296  // use -1 to have the effect of any height or time being valid.
297  int nMinHeight = -1;
298  int64_t nMinTime = -1;
299 
300  // tx.nVersion is signed integer so requires cast to unsigned otherwise
301  // we would be doing a signed comparison and half the range of nVersion
302  // wouldn't support BIP 68.
303  bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
305 
306  // Do not enforce sequence numbers as a relative lock time
307  // unless we have been instructed to
308  if (!fEnforceBIP68) {
309  return std::make_pair(nMinHeight, nMinTime);
310  }
311 
312  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
313  const CTxIn& txin = tx.vin[txinIndex];
314 
315  // Sequence numbers with the most significant bit set are not
316  // treated as relative lock-times, nor are they given any
317  // consensus-enforced meaning at this point.
319  // The height of this input is not relevant for sequence locks
320  (*prevHeights)[txinIndex] = 0;
321  continue;
322  }
323 
324  int nCoinHeight = (*prevHeights)[txinIndex];
325 
327  int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
328  // NOTE: Subtract 1 to maintain nLockTime semantics
329  // BIP 68 relative lock times have the semantics of calculating
330  // the first block or time at which the transaction would be
331  // valid. When calculating the effective block time or height
332  // for the entire transaction, we switch to using the
333  // semantics of nLockTime which is the last invalid block
334  // time or height. Thus we subtract 1 from the calculated
335  // time or height.
336 
337  // Time-based relative lock-times are measured from the
338  // smallest allowed timestamp of the block containing the
339  // txout being spent, which is the median time past of the
340  // block prior.
341  nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
342  } else {
343  nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
344  }
345  }
346 
347  return std::make_pair(nMinHeight, nMinTime);
348 }
349 
350 static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
351 {
352  assert(block.pprev);
353  int64_t nBlockTime = block.pprev->GetMedianTimePast();
354  if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
355  return false;
356 
357  return true;
358 }
359 
360 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
361 {
362  return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
363 }
364 
366 {
368  assert(lp);
369  // If there are relative lock times then the maxInputBlock will be set
370  // If there are no relative lock times, the LockPoints don't depend on the chain
371  if (lp->maxInputBlock) {
372  // Check whether chainActive is an extension of the block at which the LockPoints
373  // calculation was valid. If not LockPoints are no longer valid
374  if (!chainActive.Contains(lp->maxInputBlock)) {
375  return false;
376  }
377  }
378 
379  // LockPoints still valid
380  return true;
381 }
382 
383 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
384 {
387 
388  CBlockIndex* tip = chainActive.Tip();
389  CBlockIndex index;
390  index.pprev = tip;
391  // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
392  // height based locks because when SequenceLocks() is called within
393  // ConnectBlock(), the height of the block *being*
394  // evaluated is what is used.
395  // Thus if we want to know if a transaction can be part of the
396  // *next* block, we need to use one more than chainActive.Height()
397  index.nHeight = tip->nHeight + 1;
398 
399  std::pair<int, int64_t> lockPair;
400  if (useExistingLockPoints) {
401  assert(lp);
402  lockPair.first = lp->height;
403  lockPair.second = lp->time;
404  }
405  else {
406  // pcoinsTip contains the UTXO set for chainActive.Tip()
407  CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
408  std::vector<int> prevheights;
409  prevheights.resize(tx.vin.size());
410  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
411  const CTxIn& txin = tx.vin[txinIndex];
412  CCoins coins;
413  if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
414  return error("%s: Missing input", __func__);
415  }
416  if (coins.nHeight == MEMPOOL_HEIGHT) {
417  // Assume all mempool transaction confirm in the next block
418  prevheights[txinIndex] = tip->nHeight + 1;
419  } else {
420  prevheights[txinIndex] = coins.nHeight;
421  }
422  }
423  lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
424  if (lp) {
425  lp->height = lockPair.first;
426  lp->time = lockPair.second;
427  // Also store the hash of the block with the highest height of
428  // all the blocks which have sequence locked prevouts.
429  // This hash needs to still be on the chain
430  // for these LockPoint calculations to be valid
431  // Note: It is impossible to correctly calculate a maxInputBlock
432  // if any of the sequence locked inputs depend on unconfirmed txs,
433  // except in the special case where the relative lock time/height
434  // is 0, which is equivalent to no sequence lock. Since we assume
435  // input height of tip+1 for mempool txs and test the resulting
436  // lockPair from CalculateSequenceLocks against tip+1. We know
437  // EvaluateSequenceLocks will fail if there was a non-zero sequence
438  // lock on a mempool input, so we can use the return value of
439  // CheckSequenceLocks to indicate the LockPoints validity
440  int maxInputHeight = 0;
441  BOOST_FOREACH(int height, prevheights) {
442  // Can ignore mempool inputs since we'll fail if they had non-zero locks
443  if (height != tip->nHeight+1) {
444  maxInputHeight = std::max(maxInputHeight, height);
445  }
446  }
447  lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
448  }
449  }
450  return EvaluateSequenceLocks(index, lockPair);
451 }
452 
453 
454 unsigned int GetLegacySigOpCount(const CTransaction& tx)
455 {
456  unsigned int nSigOps = 0;
457  for (const auto& txin : tx.vin)
458  {
459  nSigOps += txin.scriptSig.GetSigOpCount(false);
460  }
461  for (const auto& txout : tx.vout)
462  {
463  nSigOps += txout.scriptPubKey.GetSigOpCount(false);
464  }
465  return nSigOps;
466 }
467 
468 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
469 {
470  if (tx.IsCoinBase())
471  return 0;
472 
473  unsigned int nSigOps = 0;
474  for (unsigned int i = 0; i < tx.vin.size(); i++)
475  {
476  const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
477  if (prevout.scriptPubKey.IsPayToScriptHash())
478  nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
479  }
480  return nSigOps;
481 }
482 
483 int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
484 {
485  int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
486 
487  if (tx.IsCoinBase())
488  return nSigOps;
489 
490  if (flags & SCRIPT_VERIFY_P2SH) {
491  nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
492  }
493 
494  for (unsigned int i = 0; i < tx.vin.size(); i++)
495  {
496  const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
497  nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
498  }
499  return nSigOps;
500 }
501 
502 
503 
504 
505 
506 bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)
507 {
508  // Basic checks that don't depend on any context
509  if (tx.vin.empty())
510  return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
511  if (tx.vout.empty())
512  return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
513  // Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)
514  if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > MAX_BLOCK_BASE_SIZE)
515  return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
516 
517  // Check for negative or overflow output values
518  CAmount nValueOut = 0;
519  for (const auto& txout : tx.vout)
520  {
521  if (txout.nValue < 0)
522  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
523  if (txout.nValue > MAX_MONEY)
524  return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
525  nValueOut += txout.nValue;
526  if (!MoneyRange(nValueOut))
527  return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
528  }
529 
530  // Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock
531  if (fCheckDuplicateInputs) {
532  std::set<COutPoint> vInOutPoints;
533  for (const auto& txin : tx.vin)
534  {
535  if (!vInOutPoints.insert(txin.prevout).second)
536  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
537  }
538  }
539 
540  if (tx.IsCoinBase())
541  {
542  if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
543  return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
544  }
545  else
546  {
547  for (const auto& txin : tx.vin)
548  if (txin.prevout.IsNull())
549  return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
550  }
551 
552  return true;
553 }
554 
555 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
556  int expired = pool.Expire(GetTime() - age);
557  if (expired != 0)
558  LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
559 
560  std::vector<uint256> vNoSpendsRemaining;
561  pool.TrimToSize(limit, &vNoSpendsRemaining);
562  BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
563  pcoinsTip->Uncache(removed);
564 }
565 
567 std::string FormatStateMessage(const CValidationState &state)
568 {
569  return strprintf("%s%s (code %i)",
570  state.GetRejectReason(),
571  state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
572  state.GetRejectCode());
573 }
574 
575 static bool IsCurrentForFeeEstimation()
576 {
579  return false;
580  if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
581  return false;
583  return false;
584  return true;
585 }
586 
587 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
588  bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
589  bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<uint256>& vHashTxnToUncache)
590 {
591  const CTransaction& tx = *ptx;
592  const uint256 hash = tx.GetHash();
594  if (pfMissingInputs)
595  *pfMissingInputs = false;
596 
597  if (!CheckTransaction(tx, state))
598  return false; // state filled in by CheckTransaction
599 
600  // Coinbase is only valid in a block, not as a loose transaction
601  if (tx.IsCoinBase())
602  return state.DoS(100, false, REJECT_INVALID, "coinbase");
603 
604  // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
605  bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus(chainActive.Height()));
606  if (!GetBoolArg("-prematurewitness",false) && tx.HasWitness() && !witnessEnabled) {
607  return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
608  }
609 
610  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
611  std::string reason;
612  if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
613  return state.DoS(0, false, REJECT_NONSTANDARD, reason);
614 
615  // Only accept nLockTime-using transactions that can be mined in the next
616  // block; we don't want our mempool filled up with transactions that can't
617  // be mined yet.
618  if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
619  return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
620 
621  // is it already in the memory pool?
622  if (pool.exists(hash))
623  return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
624 
625  // Check for conflicts with in-memory transactions
626  std::set<uint256> setConflicts;
627  {
628  LOCK(pool.cs); // protect pool.mapNextTx
629  BOOST_FOREACH(const CTxIn &txin, tx.vin)
630  {
631  auto itConflicting = pool.mapNextTx.find(txin.prevout);
632  if (itConflicting != pool.mapNextTx.end())
633  {
634  const CTransaction *ptxConflicting = itConflicting->second;
635  if (!setConflicts.count(ptxConflicting->GetHash()))
636  {
637  // Allow opt-out of transaction replacement by setting
638  // nSequence >= maxint-1 on all inputs.
639  //
640  // maxint-1 is picked to still allow use of nLockTime by
641  // non-replaceable transactions. All inputs rather than just one
642  // is for the sake of multi-party protocols, where we don't
643  // want a single party to be able to disable replacement.
644  //
645  // The opt-out ignores descendants as anyone relying on
646  // first-seen mempool behavior should be checking all
647  // unconfirmed ancestors anyway; doing otherwise is hopelessly
648  // insecure.
649  bool fReplacementOptOut = true;
650  if (fEnableReplacement)
651  {
652  BOOST_FOREACH(const CTxIn &_txin, ptxConflicting->vin)
653  {
654  if (_txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
655  {
656  fReplacementOptOut = false;
657  break;
658  }
659  }
660  }
661  if (fReplacementOptOut)
662  return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
663 
664  setConflicts.insert(ptxConflicting->GetHash());
665  }
666  }
667  }
668  }
669 
670  {
671  CCoinsView dummy;
672  CCoinsViewCache view(&dummy);
673 
674  CAmount nValueIn = 0;
675  LockPoints lp;
676  {
677  LOCK(pool.cs);
678  CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
679  view.SetBackend(viewMemPool);
680 
681  // do we already have it?
682  bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
683  if (view.HaveCoins(hash)) {
684  if (!fHadTxInCache)
685  vHashTxnToUncache.push_back(hash);
686  return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
687  }
688 
689  // do all inputs exist?
690  // Note that this does not check for the presence of actual outputs (see the next check for that),
691  // and only helps with filling in pfMissingInputs (to determine missing vs spent).
692  BOOST_FOREACH(const CTxIn txin, tx.vin) {
694  vHashTxnToUncache.push_back(txin.prevout.hash);
695  if (!view.HaveCoins(txin.prevout.hash)) {
696  if (pfMissingInputs)
697  *pfMissingInputs = true;
698  return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
699  }
700  }
701 
702  // are the actual inputs available?
703  if (!view.HaveInputs(tx))
704  return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
705 
706  // Bring the best block into scope
707  view.GetBestBlock();
708 
709  nValueIn = view.GetValueIn(tx);
710 
711  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
712  view.SetBackend(dummy);
713 
714  // Only accept BIP68 sequence locked transactions that can be mined in the next
715  // block; we don't want our mempool filled up with transactions that can't
716  // be mined yet.
717  // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
718  // CoinsViewCache instead of create its own
719  if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
720  return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
721  }
722 
723  // Check for non-standard pay-to-script-hash in inputs
724  if (fRequireStandard && !AreInputsStandard(tx, view))
725  return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
726 
727  // Check for non-standard witness in P2WSH
728  if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
729  return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
730 
731  int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
732 
733  CAmount nValueOut = tx.GetValueOut();
734  CAmount nFees = nValueIn-nValueOut;
735  // nModifiedFees includes any fee deltas from PrioritiseTransaction
736  CAmount nModifiedFees = nFees;
737  double nPriorityDummy = 0;
738  pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
739 
740  CAmount inChainInputValue;
741  double dPriority = view.GetPriority(tx, chainActive.Height(), inChainInputValue);
742 
743  // Keep track of transactions that spend a coinbase, which we re-scan
744  // during reorgs to ensure COINBASE_MATURITY is still met.
745  bool fSpendsCoinbase = false;
746  BOOST_FOREACH(const CTxIn &txin, tx.vin) {
747  const CCoins *coins = view.AccessCoins(txin.prevout.hash);
748  if (coins->IsCoinBase()) {
749  fSpendsCoinbase = true;
750  break;
751  }
752  }
753 
754  CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, dPriority, chainActive.Height(),
755  inChainInputValue, fSpendsCoinbase, nSigOpsCost, lp);
756  unsigned int nSize = entry.GetTxSize();
757 
758  // Check that the transaction doesn't have an excessive number of
759  // sigops, making it impossible to mine. Since the coinbase transaction
760  // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
761  // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
762  // merely non-standard transaction.
763  if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
764  return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
765  strprintf("%d", nSigOpsCost));
766 
767  CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
768  if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
769  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
770  } else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(chainActive.Height() + 1))) {
771  // Require that free transactions have sufficient priority to be mined in the next block.
772  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
773  }
774 
775  // Continuously rate-limit free (really, very-low-fee) transactions
776  // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
777  // be annoying or make others' transactions take longer to confirm.
778  if (fLimitFree && nModifiedFees < GetDogecoinMinRelayFee(tx, nSize, !fLimitFree))
779  {
780  static CCriticalSection csFreeLimiter;
781  static double dFreeCount;
782  static int64_t nLastTime;
783  int64_t nNow = GetTime();
784 
785  LOCK(csFreeLimiter);
786 
787  // Use an exponentially decaying ~10-minute window:
788  dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
789  nLastTime = nNow;
790  // -limitfreerelay unit is thousand-bytes-per-minute
791  // At default rate it would take over a month to fill 1GB
792  if (dFreeCount + nSize >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
793  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
794  LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
795  dFreeCount += nSize;
796  }
797 
798  if (nAbsurdFee && nFees > nAbsurdFee)
799  return state.Invalid(false,
800  REJECT_HIGHFEE, "absurdly-high-fee",
801  strprintf("%d > %d", nFees, nAbsurdFee));
802 
803  // Calculate in-mempool ancestors, up to a limit.
804  CTxMemPool::setEntries setAncestors;
805  size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
806  size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
807  size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
808  size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
809  std::string errString;
810  if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
811  return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
812  }
813 
814  // A transaction that spends outputs that would be replaced by it is invalid. Now
815  // that we have the set of all ancestors we can detect this
816  // pathological case by making sure setConflicts and setAncestors don't
817  // intersect.
818  BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
819  {
820  const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
821  if (setConflicts.count(hashAncestor))
822  {
823  return state.DoS(10, false,
824  REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
825  strprintf("%s spends conflicting transaction %s",
826  hash.ToString(),
827  hashAncestor.ToString()));
828  }
829  }
830 
831  // Check if it's economically rational to mine this transaction rather
832  // than the ones it replaces.
833  CAmount nConflictingFees = 0;
834  size_t nConflictingSize = 0;
835  uint64_t nConflictingCount = 0;
836  CTxMemPool::setEntries allConflicting;
837 
838  // If we don't hold the lock allConflicting might be incomplete; the
839  // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
840  // mempool consistency for us.
841  LOCK(pool.cs);
842  const bool fReplacementTransaction = setConflicts.size();
843  if (fReplacementTransaction)
844  {
845  CFeeRate newFeeRate(nModifiedFees, nSize);
846  std::set<uint256> setConflictsParents;
847  const int maxDescendantsToVisit = 100;
848  CTxMemPool::setEntries setIterConflicting;
849  BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
850  {
851  CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
852  if (mi == pool.mapTx.end())
853  continue;
854 
855  // Save these to avoid repeated lookups
856  setIterConflicting.insert(mi);
857 
858  // Don't allow the replacement to reduce the feerate of the
859  // mempool.
860  //
861  // We usually don't want to accept replacements with lower
862  // feerates than what they replaced as that would lower the
863  // feerate of the next block. Requiring that the feerate always
864  // be increased is also an easy-to-reason about way to prevent
865  // DoS attacks via replacements.
866  //
867  // The mining code doesn't (currently) take children into
868  // account (CPFP) so we only consider the feerates of
869  // transactions being directly replaced, not their indirect
870  // descendants. While that does mean high feerate children are
871  // ignored when deciding whether or not to replace, we do
872  // require the replacement to pay more overall fees too,
873  // mitigating most cases.
874  CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
875  if (newFeeRate <= oldFeeRate)
876  {
877  return state.DoS(0, false,
878  REJECT_INSUFFICIENTFEE, "insufficient fee", false,
879  strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
880  hash.ToString(),
881  newFeeRate.ToString(),
882  oldFeeRate.ToString()));
883  }
884 
885  BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
886  {
887  setConflictsParents.insert(txin.prevout.hash);
888  }
889 
890  nConflictingCount += mi->GetCountWithDescendants();
891  }
892  // This potentially overestimates the number of actual descendants
893  // but we just want to be conservative to avoid doing too much
894  // work.
895  if (nConflictingCount <= maxDescendantsToVisit) {
896  // If not too many to replace, then calculate the set of
897  // transactions that would have to be evicted
898  BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
899  pool.CalculateDescendants(it, allConflicting);
900  }
901  BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
902  nConflictingFees += it->GetModifiedFee();
903  nConflictingSize += it->GetTxSize();
904  }
905  } else {
906  return state.DoS(0, false,
907  REJECT_NONSTANDARD, "too many potential replacements", false,
908  strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
909  hash.ToString(),
910  nConflictingCount,
911  maxDescendantsToVisit));
912  }
913 
914  for (unsigned int j = 0; j < tx.vin.size(); j++)
915  {
916  // We don't want to accept replacements that require low
917  // feerate junk to be mined first. Ideally we'd keep track of
918  // the ancestor feerates and make the decision based on that,
919  // but for now requiring all new inputs to be confirmed works.
920  if (!setConflictsParents.count(tx.vin[j].prevout.hash))
921  {
922  // Rather than check the UTXO set - potentially expensive -
923  // it's cheaper to just check if the new input refers to a
924  // tx that's in the mempool.
925  if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
926  return state.DoS(0, false,
927  REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
928  strprintf("replacement %s adds unconfirmed input, idx %d",
929  hash.ToString(), j));
930  }
931  }
932 
933  // The replacement must pay greater fees than the transactions it
934  // replaces - if we did the bandwidth used by those conflicting
935  // transactions would not be paid for.
936  if (nModifiedFees < nConflictingFees)
937  {
938  return state.DoS(0, false,
939  REJECT_INSUFFICIENTFEE, "insufficient fee", false,
940  strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
941  hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
942  }
943 
944  // Finally in addition to paying more fees than the conflicts the
945  // new transaction must pay for its own bandwidth.
946  CAmount nDeltaFees = nModifiedFees - nConflictingFees;
947  if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
948  {
949  return state.DoS(0, false,
950  REJECT_INSUFFICIENTFEE, "insufficient fee", false,
951  strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
952  hash.ToString(),
953  FormatMoney(nDeltaFees),
955  }
956  }
957 
958  unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
959  if (!Params().RequireStandard()) {
960  scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
961  }
962 
963  // Check against previous transactions
964  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
965  PrecomputedTransactionData txdata(tx);
966  if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, txdata)) {
967  // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
968  // need to turn both off, and compare against just turning off CLEANSTACK
969  // to see if the failure is specifically due to witness validation.
970  CValidationState stateDummy; // Want reported failures to be from first CheckInputs
971  if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, txdata) &&
972  !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, txdata)) {
973  // Only the witness is missing, so the transaction itself may be fine.
974  state.SetCorruptionPossible();
975  }
976  return false; // state filled in by CheckInputs
977  }
978 
979  // Check again against just the consensus-critical mandatory script
980  // verification flags, in case of bugs in the standard flags that cause
981  // transactions to pass as valid when they're actually invalid. For
982  // instance the STRICTENC flag was incorrectly allowing certain
983  // CHECKSIG NOT scripts to pass, even though they were invalid.
984  //
985  // There is a similar check in CreateNewBlock() to prevent creating
986  // invalid blocks, however allowing such transactions into the mempool
987  // can be exploited as a DoS attack.
988  if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata))
989  {
990  return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
991  __func__, hash.ToString(), FormatStateMessage(state));
992  }
993 
994  // Remove conflicting transactions from the mempool
995  BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
996  {
997  LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
998  it->GetTx().GetHash().ToString(),
999  hash.ToString(),
1000  FormatMoney(nModifiedFees - nConflictingFees),
1001  (int)nSize - (int)nConflictingSize);
1002  if (plTxnReplaced)
1003  plTxnReplaced->push_back(it->GetSharedTx());
1004  }
1005  pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
1006 
1007  // This transaction should only count for fee estimation if it isn't a
1008  // BIP 125 replacement transaction (may not be widely supported), the
1009  // node is not behind, and the transaction is not dependent on any other
1010  // transactions in the mempool.
1011  bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
1012 
1013  // Store transaction in memory
1014  pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
1015 
1016  // trim mempool and check if tx was trimmed
1017  if (!fOverrideMempoolLimit) {
1018  LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
1019  if (!pool.exists(hash))
1020  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
1021  }
1022  }
1023 
1025 
1026  return true;
1027 }
1028 
1029 bool AcceptToMemoryPoolWithTime(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
1030  bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
1031  bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
1032 {
1033  std::vector<uint256> vHashTxToUncache;
1034  bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
1035  if (!res) {
1036  BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
1037  pcoinsTip->Uncache(hashTx);
1038  }
1039  // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1040  CValidationState stateDummy;
1042  return res;
1043 }
1044 
1045 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
1046  bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
1047  bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
1048 {
1049  return AcceptToMemoryPoolWithTime(pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee);
1050 }
1051 
1053 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
1054 {
1055  CBlockIndex *pindexSlow = NULL;
1056 
1057  LOCK(cs_main);
1058 
1059  CTransactionRef ptx = mempool.get(hash);
1060  if (ptx)
1061  {
1062  txOut = ptx;
1063  return true;
1064  }
1065 
1066  if (fTxIndex) {
1067  CDiskTxPos postx;
1068  if (pblocktree->ReadTxIndex(hash, postx)) {
1069  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1070  if (file.IsNull())
1071  return error("%s: OpenBlockFile failed", __func__);
1072  CBlockHeader header;
1073  try {
1074  file >> header;
1075  fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1076  file >> txOut;
1077  } catch (const std::exception& e) {
1078  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1079  }
1080  hashBlock = header.GetHash();
1081  if (txOut->GetHash() != hash)
1082  return error("%s: txid mismatch", __func__);
1083  return true;
1084  }
1085  }
1086 
1087  if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1088  int nHeight = -1;
1089  {
1090  const CCoinsViewCache& view = *pcoinsTip;
1091  const CCoins* coins = view.AccessCoins(hash);
1092  if (coins)
1093  nHeight = coins->nHeight;
1094  }
1095  if (nHeight > 0)
1096  pindexSlow = chainActive[nHeight];
1097  }
1098 
1099  if (pindexSlow) {
1100  CBlock block;
1101  if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1102  for (const auto& tx : block.vtx) {
1103  if (tx->GetHash() == hash) {
1104  txOut = tx;
1105  hashBlock = pindexSlow->GetBlockHash();
1106  return true;
1107  }
1108  }
1109  }
1110  }
1111 
1112  return false;
1113 }
1114 
1115 
1116 
1117 
1118 
1119 
1121 //
1122 // CBlock and CBlockIndex
1123 //
1124 
1125 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1126 {
1127  // Open history file to append
1128  CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1129  if (fileout.IsNull())
1130  return error("WriteBlockToDisk: OpenBlockFile failed");
1131 
1132  // Write index header
1133  unsigned int nSize = GetSerializeSize(fileout, block);
1134  fileout << FLATDATA(messageStart) << nSize;
1135 
1136  // Write block
1137  long fileOutPos = ftell(fileout.Get());
1138  if (fileOutPos < 0)
1139  return error("WriteBlockToDisk: ftell failed");
1140  pos.nPos = (unsigned int)fileOutPos;
1141  fileout << block;
1142 
1143  return true;
1144 }
1145 
1146 /* Generic implementation of block reading that can handle
1147  both a block and its header. */
1148 
1149 template<typename T>
1150 static bool ReadBlockOrHeader(T& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams, bool fCheckPOW)
1151 {
1152  block.SetNull();
1153 
1154  // Open history file to read
1155  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1156  if (filein.IsNull())
1157  return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1158 
1159  // Read block
1160  try {
1161  filein >> block;
1162  }
1163  catch (const std::exception& e) {
1164  return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1165  }
1166 
1167  // Check the header
1168  if (fCheckPOW && !CheckAuxPowProofOfWork(block, consensusParams))
1169  return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1170 
1171  return true;
1172 }
1173 
1174 template<typename T>
1175 static bool ReadBlockOrHeader(T& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams, bool fCheckPOW)
1176 {
1177  if (!ReadBlockOrHeader(block, pindex->GetBlockPos(), consensusParams, fCheckPOW))
1178  return false;
1179  if (block.GetHash() != pindex->GetBlockHash())
1180  return error("ReadBlockOrHeader(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1181  pindex->ToString(), pindex->GetBlockPos().ToString());
1182  return true;
1183 }
1184 
1185 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams, bool fCheckPOW)
1186 {
1187  return ReadBlockOrHeader(block, pos, consensusParams, fCheckPOW);
1188 }
1189 
1190 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams, bool fCheckPOW)
1191 {
1192  return ReadBlockOrHeader(block, pindex, consensusParams, fCheckPOW);
1193 }
1194 
1195 bool ReadBlockHeaderFromDisk(CBlockHeader& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams, bool fCheckPOW)
1196 {
1197  return ReadBlockOrHeader(block, pindex, consensusParams, fCheckPOW);
1198 }
1199 
1200 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1201 {
1202  int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1203  // Force block reward to zero when right shift is undefined.
1204  if (halvings >= 64)
1205  return 0;
1206 
1207  CAmount nSubsidy = 50 * COIN;
1208  // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1209  nSubsidy >>= halvings;
1210  return nSubsidy;
1211 }
1212 
1214 {
1215  const CChainParams& chainParams = Params();
1216 
1217  // Once this function has returned false, it must remain false.
1218  static std::atomic<bool> latchToFalse{false};
1219  // Optimization: pre-test latch before taking the lock.
1220  if (latchToFalse.load(std::memory_order_relaxed))
1221  return false;
1222 
1223  LOCK(cs_main);
1224  if (latchToFalse.load(std::memory_order_relaxed))
1225  return false;
1226  if (fImporting || fReindex)
1227  return true;
1228  if (chainActive.Tip() == NULL)
1229  return true;
1231  return true;
1232  if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1233  return true;
1234  latchToFalse.store(true, std::memory_order_relaxed);
1235  return false;
1236 }
1237 
1239 
1240 static void AlertNotify(const std::string& strMessage)
1241 {
1242  CAlert::Notify(strMessage);
1243 }
1244 
1246 {
1248  // Before we get past initial download, we cannot reliably alert about forks
1249  // (we assume we don't get stuck on a fork before finishing our initial sync)
1250  if (IsInitialBlockDownload())
1251  return;
1252 
1253  // If our best fork is no longer within 360 blocks (+/- 6 hours if no one mines it)
1254  // of our head, drop it
1256  pindexBestForkTip = NULL;
1257 
1258  if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 30)))
1259  {
1261  {
1262  std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1263  pindexBestForkBase->phashBlock->ToString() + std::string("'");
1264  AlertNotify(warning);
1265  }
1267  {
1268  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__,
1271  SetfLargeWorkForkFound(true);
1272  }
1273  else
1274  {
1275  LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1277  }
1278  }
1279  else
1280  {
1281  SetfLargeWorkForkFound(false);
1283  }
1284 }
1285 
1287 {
1289  // If we are on a fork that is sufficiently large, set a warning flag
1290  CBlockIndex* pfork = pindexNewForkTip;
1291  CBlockIndex* plonger = chainActive.Tip();
1292  while (pfork && pfork != plonger)
1293  {
1294  while (plonger && plonger->nHeight > pfork->nHeight)
1295  plonger = plonger->pprev;
1296  if (pfork == plonger)
1297  break;
1298  pfork = pfork->pprev;
1299  }
1300 
1301  // We define a condition where we should warn the user about as a fork of at least 7 blocks
1302  // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1303  // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1304  // hash rate operating on the fork.
1305  // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1306  // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1307  // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1308  if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1309  pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1310  chainActive.Height() - pindexNewForkTip->nHeight < 72)
1311  {
1312  pindexBestForkTip = pindexNewForkTip;
1313  pindexBestForkBase = pfork;
1314  }
1315 
1317 }
1318 
1319 void static InvalidChainFound(CBlockIndex* pindexNew)
1320 {
1321  if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1322  pindexBestInvalid = pindexNew;
1323 
1324  LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1325  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1326  log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1327  pindexNew->GetBlockTime()));
1328  CBlockIndex *tip = chainActive.Tip();
1329  assert (tip);
1330  LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1331  tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1332  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1334 }
1335 
1336 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1337  if (!state.CorruptionPossible()) {
1338  pindex->nStatus |= BLOCK_FAILED_VALID;
1339  setDirtyBlockIndex.insert(pindex);
1340  setBlockIndexCandidates.erase(pindex);
1341  InvalidChainFound(pindex);
1342  }
1343 }
1344 
1345 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1346 {
1347  // mark inputs spent
1348  if (!tx.IsCoinBase()) {
1349  txundo.vprevout.reserve(tx.vin.size());
1350  BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1351  CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1352  unsigned nPos = txin.prevout.n;
1353 
1354  if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1355  assert(false);
1356  // mark an outpoint spent, and construct undo information
1357  txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1358  coins->Spend(nPos);
1359  if (coins->vout.size() == 0) {
1360  CTxInUndo& undo = txundo.vprevout.back();
1361  undo.nHeight = coins->nHeight;
1362  undo.fCoinBase = coins->fCoinBase;
1363  undo.nVersion = coins->nVersion;
1364  }
1365  }
1366  }
1367  // add outputs
1368  inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1369 }
1370 
1371 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1372 {
1373  CTxUndo txundo;
1374  UpdateCoins(tx, inputs, txundo, nHeight);
1375 }
1376 
1378  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1379  const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1381  return false;
1382  }
1383  return true;
1384 }
1385 
1387 {
1388  LOCK(cs_main);
1389  CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1390  return pindexPrev->nHeight + 1;
1391 }
1392 
1393 namespace Consensus {
1394 bool CheckTxInputs(const CChainParams& params, const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1395 {
1396  // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1397  // for an attacker to attempt to split the network.
1398  if (!inputs.HaveInputs(tx))
1399  return state.Invalid(false, 0, "", "Inputs unavailable");
1400 
1401  CAmount nValueIn = 0;
1402  CAmount nFees = 0;
1403  for (unsigned int i = 0; i < tx.vin.size(); i++)
1404  {
1405  const COutPoint &prevout = tx.vin[i].prevout;
1406  const CCoins *coins = inputs.AccessCoins(prevout.hash);
1407  assert(coins);
1408 
1409  // If prev is coinbase, check that it's matured
1410  if (coins->IsCoinBase()) {
1411  // Dogecoin: Switch maturity at depth 145,000
1412  int nCoinbaseMaturity = params.GetConsensus(coins->nHeight).nCoinbaseMaturity;
1413  if (nSpendHeight - coins->nHeight < nCoinbaseMaturity)
1414  return state.Invalid(false,
1415  REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1416  strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1417  }
1418 
1419  // Check for negative or overflow input values
1420  nValueIn += coins->vout[prevout.n].nValue;
1421  if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1422  return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1423 
1424  }
1425 
1426  if (nValueIn < tx.GetValueOut())
1427  return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1428  strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1429 
1430  // Tally transaction fees
1431  CAmount nTxFee = nValueIn - tx.GetValueOut();
1432  if (nTxFee < 0)
1433  return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1434  nFees += nTxFee;
1435  if (!MoneyRange(nFees))
1436  return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1437  return true;
1438 }
1439 }// namespace Consensus
1440 
1441 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1442 {
1443  if (!tx.IsCoinBase())
1444  {
1445  if (!Consensus::CheckTxInputs(Params(), tx, state, inputs, GetSpendHeight(inputs)))
1446  return false;
1447 
1448  if (pvChecks)
1449  pvChecks->reserve(tx.vin.size());
1450 
1451  // The first loop above does all the inexpensive checks.
1452  // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1453  // Helps prevent CPU exhaustion attacks.
1454 
1455  // Skip script verification when connecting blocks under the
1456  // assumedvalid block. Assuming the assumedvalid block is valid this
1457  // is safe because block merkle hashes are still computed and checked,
1458  // Of course, if an assumed valid block is invalid due to false scriptSigs
1459  // this optimization would allow an invalid chain to be accepted.
1460  if (fScriptChecks) {
1461  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1462  const COutPoint &prevout = tx.vin[i].prevout;
1463  const CCoins* coins = inputs.AccessCoins(prevout.hash);
1464  assert(coins);
1465 
1466  // Verify signature
1467  CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1468  if (pvChecks) {
1469  pvChecks->push_back(CScriptCheck());
1470  check.swap(pvChecks->back());
1471  } else if (!check()) {
1472  if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1473  // Check whether the failure was caused by a
1474  // non-mandatory script verification check, such as
1475  // non-standard DER encodings or non-null dummy
1476  // arguments; if so, don't trigger DoS protection to
1477  // avoid splitting the network between upgraded and
1478  // non-upgraded nodes.
1479  CScriptCheck check2(*coins, tx, i,
1480  flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1481  if (check2())
1482  return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1483  }
1484  // Failures of other flags indicate a transaction that is
1485  // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1486  // such nodes as they are not following the protocol. That
1487  // said during an upgrade careful thought should be taken
1488  // as to the correct behavior - we may want to continue
1489  // peering with non-upgraded nodes even after soft-fork
1490  // super-majority signaling has occurred.
1491  return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1492  }
1493  }
1494  }
1495  }
1496 
1497  return true;
1498 }
1499 
1500 namespace {
1501 
1502 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1503 {
1504  // Open history file to append
1505  CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1506  if (fileout.IsNull())
1507  return error("%s: OpenUndoFile failed", __func__);
1508 
1509  // Write index header
1510  unsigned int nSize = GetSerializeSize(fileout, blockundo);
1511  fileout << FLATDATA(messageStart) << nSize;
1512 
1513  // Write undo data
1514  long fileOutPos = ftell(fileout.Get());
1515  if (fileOutPos < 0)
1516  return error("%s: ftell failed", __func__);
1517  pos.nPos = (unsigned int)fileOutPos;
1518  fileout << blockundo;
1519 
1520  // calculate & write checksum
1521  CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1522  hasher << hashBlock;
1523  hasher << blockundo;
1524  fileout << hasher.GetHash();
1525 
1526  return true;
1527 }
1528 
1529 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1530 {
1531  // Open history file to read
1532  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1533  if (filein.IsNull())
1534  return error("%s: OpenUndoFile failed", __func__);
1535 
1536  // Read block
1537  uint256 hashChecksum;
1538  try {
1539  filein >> blockundo;
1540  filein >> hashChecksum;
1541  }
1542  catch (const std::exception& e) {
1543  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1544  }
1545 
1546  // Verify checksum
1547  CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1548  hasher << hashBlock;
1549  hasher << blockundo;
1550  if (hashChecksum != hasher.GetHash())
1551  return error("%s: Checksum mismatch", __func__);
1552 
1553  return true;
1554 }
1555 
1557 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1558 {
1559  SetMiscWarning(strMessage);
1560  LogPrintf("*** %s\n", strMessage);
1562  userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1564  StartShutdown();
1565  return false;
1566 }
1567 
1568 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1569 {
1570  AbortNode(strMessage, userMessage);
1571  return state.Error(strMessage);
1572 }
1573 
1574 } // anon namespace
1575 
1583 bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1584 {
1585  bool fClean = true;
1586 
1587  CCoinsModifier coins = view.ModifyCoins(out.hash);
1588  if (undo.nHeight != 0) {
1589  // undo data contains height: this is the last output of the prevout tx being spent
1590  if (!coins->IsPruned())
1591  fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1592  coins->Clear();
1593  coins->fCoinBase = undo.fCoinBase;
1594  coins->nHeight = undo.nHeight;
1595  coins->nVersion = undo.nVersion;
1596  } else {
1597  if (coins->IsPruned())
1598  fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1599  }
1600  if (coins->IsAvailable(out.n))
1601  fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1602  if (coins->vout.size() < out.n+1)
1603  coins->vout.resize(out.n+1);
1604  coins->vout[out.n] = undo.txout;
1605 
1606  return fClean;
1607 }
1608 
1609 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1610 {
1611  assert(pindex->GetBlockHash() == view.GetBestBlock());
1612 
1613  if (pfClean)
1614  *pfClean = false;
1615 
1616  bool fClean = true;
1617 
1618  CBlockUndo blockUndo;
1619  CDiskBlockPos pos = pindex->GetUndoPos();
1620  if (pos.IsNull())
1621  return error("DisconnectBlock(): no undo data available");
1622  if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1623  return error("DisconnectBlock(): failure reading undo data");
1624 
1625  if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1626  return error("DisconnectBlock(): block and undo data inconsistent");
1627 
1628  // undo transactions in reverse order
1629  for (int i = block.vtx.size() - 1; i >= 0; i--) {
1630  const CTransaction &tx = *(block.vtx[i]);
1631  uint256 hash = tx.GetHash();
1632 
1633  // Check that all outputs are available and match the outputs in the block itself
1634  // exactly.
1635  {
1636  CCoinsModifier outs = view.ModifyCoins(hash);
1637  outs->ClearUnspendable();
1638 
1639  CCoins outsBlock(tx, pindex->nHeight);
1640  // The CCoins serialization does not serialize negative numbers.
1641  // No network rules currently depend on the version here, so an inconsistency is harmless
1642  // but it must be corrected before txout nversion ever influences a network rule.
1643  if (outsBlock.nVersion < 0)
1644  outs->nVersion = outsBlock.nVersion;
1645  if (*outs != outsBlock)
1646  fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1647 
1648  // remove outputs
1649  outs->Clear();
1650  }
1651 
1652  // restore inputs
1653  if (i > 0) { // not coinbases
1654  const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1655  if (txundo.vprevout.size() != tx.vin.size())
1656  return error("DisconnectBlock(): transaction and undo data inconsistent");
1657  for (unsigned int j = tx.vin.size(); j-- > 0;) {
1658  const COutPoint &out = tx.vin[j].prevout;
1659  const CTxInUndo &undo = txundo.vprevout[j];
1660  if (!ApplyTxInUndo(undo, view, out))
1661  fClean = false;
1662  }
1663  }
1664  }
1665 
1666  // move best block pointer to prevout block
1667  view.SetBestBlock(pindex->pprev->GetBlockHash());
1668 
1669  if (pfClean) {
1670  *pfClean = fClean;
1671  return true;
1672  }
1673 
1674  return fClean;
1675 }
1676 
1677 void static FlushBlockFile(bool fFinalize = false)
1678 {
1679  LOCK(cs_LastBlockFile);
1680 
1681  CDiskBlockPos posOld(nLastBlockFile, 0);
1682 
1683  FILE *fileOld = OpenBlockFile(posOld);
1684  if (fileOld) {
1685  if (fFinalize)
1686  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1687  FileCommit(fileOld);
1688  fclose(fileOld);
1689  }
1690 
1691  fileOld = OpenUndoFile(posOld);
1692  if (fileOld) {
1693  if (fFinalize)
1694  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1695  FileCommit(fileOld);
1696  fclose(fileOld);
1697  }
1698 }
1699 
1700 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1701 
1702 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1703 
1705  RenameThread("dogecoin-scriptch");
1706  scriptcheckqueue.Thread();
1707 }
1708 
1709 // Protected by cs_main
1711 
1712 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1713 {
1714  LOCK(cs_main);
1715  int32_t nVersion = VERSIONBITS_TOP_BITS;
1716 
1717  for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1719  if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1720  nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1721  }
1722  }
1723 
1724  return nVersion;
1725 }
1726 
1731 {
1732 private:
1733  int bit;
1734 
1735 public:
1736  WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1737 
1738  int64_t BeginTime(const Consensus::Params& params) const { return 0; }
1739  int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
1740  int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
1741  int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
1742 
1743  bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
1744  {
1745  return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1746  ((pindex->nVersion >> bit) & 1) != 0 &&
1747  ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1748  }
1749 };
1750 
1751 // Protected by cs_main
1752 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1753 
1754 static int64_t nTimeCheck = 0;
1755 static int64_t nTimeForks = 0;
1756 static int64_t nTimeVerify = 0;
1757 static int64_t nTimeConnect = 0;
1758 static int64_t nTimeIndex = 0;
1759 static int64_t nTimeCallbacks = 0;
1760 static int64_t nTimeTotal = 0;
1761 
1762 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1763  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1764 {
1766 
1767  const Consensus::Params& consensus = Params().GetConsensus(pindex->nHeight);
1768  int64_t nTimeStart = GetTimeMicros();
1769 
1770  // Check it again in case a previous version let a bad block in
1771  if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1772  return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1773 
1774  // verify that the view's current state corresponds to the previous block
1775  uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1776  assert(hashPrevBlock == view.GetBestBlock());
1777 
1778  // Special case for the genesis block, skipping connection of its transactions
1779  // (its coinbase is unspendable)
1780  if (block.GetHash() == Params().GetConsensus(0).hashGenesisBlock) {
1781  if (!fJustCheck)
1782  view.SetBestBlock(pindex->GetBlockHash());
1783  return true;
1784  }
1785 
1786  bool fScriptChecks = true;
1787  if (!hashAssumeValid.IsNull()) {
1788  // We've been configured with the hash of a block which has been externally verified to have a valid history.
1789  // A suitable default value is included with the software and updated from time to time. Because validity
1790  // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1791  // This setting doesn't force the selection of any particular chain but makes validating some faster by
1792  // effectively caching the result of part of the verification.
1793  BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1794  if (it != mapBlockIndex.end()) {
1795  if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1796  pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1798  // This block is a member of the assumed verified chain and an ancestor of the best header.
1799  // The equivalent time check discourages hashpower from extorting the network via DOS attack
1800  // into accepting an invalid block through telling users they must manually set assumevalid.
1801  // Requiring a software change or burying the invalid block, regardless of the setting, makes
1802  // it hard to hide the implication of the demand. This also avoids having release candidates
1803  // that are hardly doing any signature verification at all in testing without having to
1804  // artificially set the default assumed verified block further back.
1805  // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1806  // least as good as the expected chain.
1807  fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensus) <= 60 * 60 * 24 * 7 * 2);
1808  }
1809  }
1810  }
1811 
1812  int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1813  LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1814 
1815  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1816  // unless those are already completely spent.
1817  // If such overwrites are allowed, coinbases and transactions depending upon those
1818  // can be duplicated to remove the ability to spend the first instance -- even after
1819  // being sent to another address.
1820  // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1821  // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1822  // already refuses previously-known transaction ids entirely.
1823  // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1824  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1825  // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1826  // initial block download.
1827  // Dogecoin: BIP30 has been active since inception
1828  bool fEnforceBIP30 = true;
1829 
1830  // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1831  // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1832  // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1833  // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1834  // duplicate transactions descending from the known pairs either.
1835  // 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.
1836  CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus(0).BIP34Height);
1837  //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1838  fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus(0).BIP34Hash));
1839 
1840  if (fEnforceBIP30) {
1841  for (const auto& tx : block.vtx) {
1842  const CCoins* coins = view.AccessCoins(tx->GetHash());
1843  if (coins && !coins->IsPruned())
1844  return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1845  REJECT_INVALID, "bad-txns-BIP30");
1846  }
1847  }
1848 
1849  // BIP16 didn't become active until Apr 1 2012
1850  // Dogecoin: BIP16 has been enabled since inception
1851  bool fStrictPayToScriptHash = true;
1852 
1853  unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1854 
1855  // Start enforcing the DERSIG (BIP66) rule
1856  if (pindex->nHeight >= chainparams.GetConsensus(0).BIP66Height) {
1858  }
1859 
1860  // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4 blocks
1861  if (pindex->nHeight >= chainparams.GetConsensus(0).BIP65Height) {
1863  }
1864 
1865  // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1866  int nLockTimeFlags = 0;
1869  nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
1870  }
1871 
1872  // Start enforcing WITNESS rules using versionbits logic.
1873  if (IsWitnessEnabled(pindex->pprev, consensus)) {
1876  }
1877 
1878  int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1879  LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1880 
1881  CBlockUndo blockundo;
1882 
1883  CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1884 
1885  std::vector<int> prevheights;
1886  CAmount nFees = 0;
1887  int nInputs = 0;
1888  int64_t nSigOpsCost = 0;
1889  CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1890  std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1891  vPos.reserve(block.vtx.size());
1892  blockundo.vtxundo.reserve(block.vtx.size() - 1);
1893  std::vector<PrecomputedTransactionData> txdata;
1894  txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
1895  for (unsigned int i = 0; i < block.vtx.size(); i++)
1896  {
1897  const CTransaction &tx = *(block.vtx[i]);
1898 
1899  nInputs += tx.vin.size();
1900 
1901  if (!tx.IsCoinBase())
1902  {
1903  if (!view.HaveInputs(tx))
1904  return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1905  REJECT_INVALID, "bad-txns-inputs-missingorspent");
1906 
1907  // Check that transaction is BIP68 final
1908  // BIP68 lock checks (as opposed to nLockTime checks) must
1909  // be in ConnectBlock because they require the UTXO set
1910  prevheights.resize(tx.vin.size());
1911  for (size_t j = 0; j < tx.vin.size(); j++) {
1912  prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
1913  }
1914 
1915  if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
1916  return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
1917  REJECT_INVALID, "bad-txns-nonfinal");
1918  }
1919  }
1920 
1921  // GetTransactionSigOpCost counts 3 types of sigops:
1922  // * legacy (always)
1923  // * p2sh (when P2SH enabled in flags and excludes coinbase)
1924  // * witness (when witness enabled in flags and excludes coinbase)
1925  nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
1926  if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
1927  return state.DoS(100, error("ConnectBlock(): too many sigops"),
1928  REJECT_INVALID, "bad-blk-sigops");
1929 
1930  txdata.emplace_back(tx);
1931  if (!tx.IsCoinBase())
1932  {
1933  nFees += view.GetValueIn(tx)-tx.GetValueOut();
1934 
1935  std::vector<CScriptCheck> vChecks;
1936  bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1937  if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : NULL))
1938  return error("ConnectBlock(): CheckInputs on %s failed with %s",
1939  tx.GetHash().ToString(), FormatStateMessage(state));
1940  control.Add(vChecks);
1941  }
1942 
1943  CTxUndo undoDummy;
1944  if (i > 0) {
1945  blockundo.vtxundo.push_back(CTxUndo());
1946  }
1947  UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1948 
1949  vPos.push_back(std::make_pair(tx.GetHash(), pos));
1950  pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1951  }
1952  int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1953  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);
1954 
1955  CAmount blockReward = nFees + GetDogecoinBlockSubsidy(pindex->nHeight, chainparams.GetConsensus(pindex->nHeight), hashPrevBlock);
1956  if (block.vtx[0]->GetValueOut() > blockReward)
1957  return state.DoS(100,
1958  error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1959  block.vtx[0]->GetValueOut(), blockReward),
1960  REJECT_INVALID, "bad-cb-amount");
1961 
1962  if (!control.Wait())
1963  return state.DoS(100, false);
1964  int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1965  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);
1966 
1967  if (fJustCheck)
1968  return true;
1969 
1970  // Write undo information to disk
1971  if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1972  {
1973  if (pindex->GetUndoPos().IsNull()) {
1974  CDiskBlockPos _pos;
1975  if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1976  return error("ConnectBlock(): FindUndoPos failed");
1977  if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1978  return AbortNode(state, "Failed to write undo data");
1979 
1980  // update nUndoPos in block index
1981  pindex->nUndoPos = _pos.nPos;
1982  pindex->nStatus |= BLOCK_HAVE_UNDO;
1983  }
1984 
1986  setDirtyBlockIndex.insert(pindex);
1987  }
1988 
1989  if (fTxIndex)
1990  if (!pblocktree->WriteTxIndex(vPos))
1991  return AbortNode(state, "Failed to write transaction index");
1992 
1993  // add this block to the view's block chain
1994  view.SetBestBlock(pindex->GetBlockHash());
1995 
1996  int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1997  LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1998 
1999  // Watch for changes to the previous coinbase transaction.
2000  static uint256 hashPrevBestCoinBase;
2001  GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2002  hashPrevBestCoinBase = block.vtx[0]->GetHash();
2003 
2004 
2005  int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
2006  LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
2007 
2008  return true;
2009 }
2010 
2017 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
2018  int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
2019  const CChainParams& chainparams = Params();
2020  LOCK2(cs_main, cs_LastBlockFile);
2021  static int64_t nLastWrite = 0;
2022  static int64_t nLastFlush = 0;
2023  static int64_t nLastSetChain = 0;
2024  std::set<int> setFilesToPrune;
2025  bool fFlushForPrune = false;
2026  try {
2027  if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2028  if (nManualPruneHeight > 0) {
2029  FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
2030  } else {
2031  FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
2032  fCheckForPruning = false;
2033  }
2034  if (!setFilesToPrune.empty()) {
2035  fFlushForPrune = true;
2036  if (!fHavePruned) {
2037  pblocktree->WriteFlag("prunedblockfiles", true);
2038  fHavePruned = true;
2039  }
2040  }
2041  }
2042  int64_t nNow = GetTimeMicros();
2043  // Avoid writing/flushing immediately after startup.
2044  if (nLastWrite == 0) {
2045  nLastWrite = nNow;
2046  }
2047  if (nLastFlush == 0) {
2048  nLastFlush = nNow;
2049  }
2050  if (nLastSetChain == 0) {
2051  nLastSetChain = nNow;
2052  }
2053  int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2054  int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
2055  int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2056  // The cache is large and we're within 10% and 200 MiB or 50% and 50MiB of the limit, but we have time now (not in the middle of a block processing).
2057  bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::min(std::max(nTotalSpace / 2, nTotalSpace - MIN_BLOCK_COINSDB_USAGE * 1024 * 1024),
2058  std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024));
2059  // The cache is over the limit, we have to write now.
2060  bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
2061  // 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.
2062  bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2063  // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2064  bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2065  // Combine all conditions that result in a full cache flush.
2066  bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2067  // Write blocks and block index to disk.
2068  if (fDoFullFlush || fPeriodicWrite) {
2069  // Depend on nMinDiskSpace to ensure we can write block index
2070  if (!CheckDiskSpace(0))
2071  return state.Error("out of disk space");
2072  // First make sure all block and undo data is flushed to disk.
2073  FlushBlockFile();
2074  // Then update all block file information (which may refer to block and undo files).
2075  {
2076  std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2077  vFiles.reserve(setDirtyFileInfo.size());
2078  for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2079  vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2080  setDirtyFileInfo.erase(it++);
2081  }
2082  std::vector<const CBlockIndex*> vBlocks;
2083  vBlocks.reserve(setDirtyBlockIndex.size());
2084  for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2085  vBlocks.push_back(*it);
2086  setDirtyBlockIndex.erase(it++);
2087  }
2088  if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2089  return AbortNode(state, "Failed to write to block index database");
2090  }
2091  }
2092  // Finally remove any pruned files
2093  if (fFlushForPrune)
2094  UnlinkPrunedFiles(setFilesToPrune);
2095  nLastWrite = nNow;
2096  }
2097  // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2098  if (fDoFullFlush) {
2099  // Typical CCoins structures on disk are around 128 bytes in size.
2100  // Pushing a new one to the database can cause it to be written
2101  // twice (once in the log, and once in the tables). This is already
2102  // an overestimation, as most will delete an existing entry or
2103  // overwrite one. Still, use a conservative safety factor of 2.
2104  if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2105  return state.Error("out of disk space");
2106  // Flush the chainstate (which may refer to block index entries).
2107  if (!pcoinsTip->Flush())
2108  return AbortNode(state, "Failed to write to coin database");
2109  nLastFlush = nNow;
2110  }
2111  if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2112  // Update best block in wallet (so we can detect restored wallets).
2114  nLastSetChain = nNow;
2115  }
2116  } catch (const std::runtime_error& e) {
2117  return AbortNode(state, std::string("System error while flushing: ") + e.what());
2118  }
2119  return true;
2120 }
2121 
2123  CValidationState state;
2125 }
2126 
2128  CValidationState state;
2129  fCheckForPruning = true;
2131 }
2132 
2134 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2135  chainActive.SetTip(pindexNew);
2136 
2137  // New best block
2139 
2140  cvBlockChange.notify_all();
2141 
2142  static bool fWarned = false;
2143  std::vector<std::string> warningMessages;
2144  if (!IsInitialBlockDownload())
2145  {
2146  int nUpgraded = 0;
2147  const CBlockIndex* pindex = chainActive.Tip();
2148  for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2149  WarningBitsConditionChecker checker(bit);
2150  ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(pindex->nHeight), warningcache[bit]);
2151  if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2152  if (state == THRESHOLD_ACTIVE) {
2153  std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2154  SetMiscWarning(strWarning);
2155  if (!fWarned) {
2156  AlertNotify(strWarning);
2157  fWarned = true;
2158  }
2159  } else {
2160  warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
2161  }
2162  }
2163  }
2164  // Check the version of the last 100 blocks to see if we need to upgrade:
2165  for (int i = 0; i < 100 && pindex != NULL; i++)
2166  {
2167  int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus(pindex->nHeight));
2168  if (pindex->GetBaseVersion() > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->GetBaseVersion() & ~nExpectedVersion) != 0)
2169  ++nUpgraded;
2170  pindex = pindex->pprev;
2171  }
2172  if (nUpgraded > 0)
2173  warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
2174  if (nUpgraded > 100/2)
2175  {
2176  std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2177  // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2178  SetMiscWarning(strWarning);
2179  if (!fWarned) {
2180  AlertNotify(strWarning);
2181  fWarned = true;
2182  }
2183  }
2184  }
2185  LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
2187  log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2188  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2190  if (!warningMessages.empty())
2191  LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2192  LogPrintf("\n");
2193 
2194 }
2195 
2197 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, bool fBare = false)
2198 {
2199  CBlockIndex *pindexDelete = chainActive.Tip();
2200  assert(pindexDelete);
2201  // Read block from disk.
2202  CBlock block;
2203  if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus(chainActive.Height())))
2204  return AbortNode(state, "Failed to read block");
2205  // Apply the block atomically to the chain state.
2206  int64_t nStart = GetTimeMicros();
2207  {
2208  CCoinsViewCache view(pcoinsTip);
2209  if (!DisconnectBlock(block, state, pindexDelete, view))
2210  return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2211  bool flushed = view.Flush();
2212  assert(flushed);
2213  }
2214  LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2215  // Write the chain state to disk, if necessary.
2217  return false;
2218 
2219  if (!fBare) {
2220  // Resurrect mempool transactions from the disconnected block.
2221  std::vector<uint256> vHashUpdate;
2222  for (const auto& it : block.vtx) {
2223  const CTransaction& tx = *it;
2224  // ignore validation errors in resurrected transactions
2225  CValidationState stateDummy;
2226  if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, it, false, NULL, NULL, true)) {
2228  } else if (mempool.exists(tx.GetHash())) {
2229  vHashUpdate.push_back(tx.GetHash());
2230  }
2231  }
2232  // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2233  // no in-mempool children, which is generally not true when adding
2234  // previously-confirmed transactions back to the mempool.
2235  // UpdateTransactionsFromBlock finds descendants of any transactions in this
2236  // block that were added back and cleans up the mempool state.
2237  mempool.UpdateTransactionsFromBlock(vHashUpdate);
2238  }
2239 
2240  // Update chainActive and related variables.
2241  UpdateTip(pindexDelete->pprev, chainparams);
2242  // Let wallets know transactions went from 1-confirmed to
2243  // 0-confirmed or conflicted:
2244  for (const auto& tx : block.vtx) {
2246  }
2247  return true;
2248 }
2249 
2250 static int64_t nTimeReadFromDisk = 0;
2251 static int64_t nTimeConnectTotal = 0;
2252 static int64_t nTimeFlush = 0;
2253 static int64_t nTimeChainState = 0;
2254 static int64_t nTimePostConnect = 0;
2255 
2261  std::vector<std::pair<CBlockIndex*, std::shared_ptr<const CBlock> > > blocksConnected;
2262 };
2263 
2272 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace)
2273 {
2274  assert(pindexNew->pprev == chainActive.Tip());
2275  // Read block from disk.
2276  int64_t nTime1 = GetTimeMicros();
2277  if (!pblock) {
2278  std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2279  connectTrace.blocksConnected.emplace_back(pindexNew, pblockNew);
2280  if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus(pindexNew->nHeight)))
2281  return AbortNode(state, "Failed to read block");
2282  } else {
2283  connectTrace.blocksConnected.emplace_back(pindexNew, pblock);
2284  }
2285  const CBlock& blockConnecting = *connectTrace.blocksConnected.back().second;
2286  // Apply the block atomically to the chain state.
2287  int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2288  int64_t nTime3;
2289  LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2290  {
2291  CCoinsViewCache view(pcoinsTip);
2292  bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2293  GetMainSignals().BlockChecked(blockConnecting, state);
2294  if (!rv) {
2295  if (state.IsInvalid())
2296  InvalidBlockFound(pindexNew, state);
2297  return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2298  }
2299  nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2300  LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2301  bool flushed = view.Flush();
2302  assert(flushed);
2303  }
2304  int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2305  LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2306  // Write the chain state to disk, if necessary.
2308  return false;
2309  int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2310  LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2311  // Remove conflicting transactions from the mempool.;
2312  mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2313  // Update chainActive & related variables.
2314  UpdateTip(pindexNew, chainparams);
2315 
2316  int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2317  LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2318  LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2319  return true;
2320 }
2321 
2326 static CBlockIndex* FindMostWorkChain() {
2327  do {
2328  CBlockIndex *pindexNew = NULL;
2329 
2330  // Find the best candidate header.
2331  {
2332  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2333  if (it == setBlockIndexCandidates.rend())
2334  return NULL;
2335  pindexNew = *it;
2336  }
2337 
2338  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2339  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2340  CBlockIndex *pindexTest = pindexNew;
2341  bool fInvalidAncestor = false;
2342  while (pindexTest && !chainActive.Contains(pindexTest)) {
2343  assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2344 
2345  // Pruned nodes may have entries in setBlockIndexCandidates for
2346  // which block files have been deleted. Remove those as candidates
2347  // for the most work chain if we come across them; we can't switch
2348  // to a chain unless we have all the non-active-chain parent blocks.
2349  bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2350  bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2351  if (fFailedChain || fMissingData) {
2352  // Candidate chain is not usable (either invalid or missing data)
2353  if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2354  pindexBestInvalid = pindexNew;
2355  CBlockIndex *pindexFailed = pindexNew;
2356  // Remove the entire chain from the set.
2357  while (pindexTest != pindexFailed) {
2358  if (fFailedChain) {
2359  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2360  } else if (fMissingData) {
2361  // If we're missing data, then add back to mapBlocksUnlinked,
2362  // so that if the block arrives in the future we can try adding
2363  // to setBlockIndexCandidates again.
2364  mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2365  }
2366  setBlockIndexCandidates.erase(pindexFailed);
2367  pindexFailed = pindexFailed->pprev;
2368  }
2369  setBlockIndexCandidates.erase(pindexTest);
2370  fInvalidAncestor = true;
2371  break;
2372  }
2373  pindexTest = pindexTest->pprev;
2374  }
2375  if (!fInvalidAncestor)
2376  return pindexNew;
2377  } while(true);
2378 }
2379 
2381 static void PruneBlockIndexCandidates() {
2382  // Note that we can't delete the current block itself, as we may need to return to it later in case a
2383  // reorganization to a better block fails.
2384  std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2385  while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2386  setBlockIndexCandidates.erase(it++);
2387  }
2388  // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2389  assert(!setBlockIndexCandidates.empty());
2390 }
2391 
2396 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2397 {
2399  const CBlockIndex *pindexOldTip = chainActive.Tip();
2400  const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2401 
2402  // Disconnect active blocks which are no longer in the best chain.
2403  bool fBlocksDisconnected = false;
2404  while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2405  if (!DisconnectTip(state, chainparams))
2406  return false;
2407  fBlocksDisconnected = true;
2408  }
2409 
2410  // Build list of new blocks to connect.
2411  std::vector<CBlockIndex*> vpindexToConnect;
2412  bool fContinue = true;
2413  int nHeight = pindexFork ? pindexFork->nHeight : -1;
2414  while (fContinue && nHeight != pindexMostWork->nHeight) {
2415  // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2416  // a few blocks along the way.
2417  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2418  vpindexToConnect.clear();
2419  vpindexToConnect.reserve(nTargetHeight - nHeight);
2420  CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2421  while (pindexIter && pindexIter->nHeight != nHeight) {
2422  vpindexToConnect.push_back(pindexIter);
2423  pindexIter = pindexIter->pprev;
2424  }
2425  nHeight = nTargetHeight;
2426 
2427  // Connect new blocks.
2428  BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2429  if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace)) {
2430  if (state.IsInvalid()) {
2431  // The block violates a consensus rule.
2432  if (!state.CorruptionPossible())
2433  InvalidChainFound(vpindexToConnect.back());
2434  state = CValidationState();
2435  fInvalidFound = true;
2436  fContinue = false;
2437  // If we didn't actually connect the block, don't notify listeners about it
2438  connectTrace.blocksConnected.pop_back();
2439  break;
2440  } else {
2441  // A system error occurred (disk space, database error, ...).
2442  return false;
2443  }
2444  } else {
2445  PruneBlockIndexCandidates();
2446  if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2447  // We're in a better position than we were. Return temporarily to release the lock.
2448  fContinue = false;
2449  break;
2450  }
2451  }
2452  }
2453  }
2454 
2455  if (fBlocksDisconnected) {
2456  mempool.removeForReorg(pcoinsTip, chainActive.Height() + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2457  LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2458  }
2460 
2461  // Callbacks/notifications for a new best chain.
2462  if (fInvalidFound)
2463  CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2464  else
2466 
2467  return true;
2468 }
2469 
2470 static void NotifyHeaderTip() {
2471  bool fNotify = false;
2472  bool fInitialBlockDownload = false;
2473  static CBlockIndex* pindexHeaderOld = NULL;
2474  CBlockIndex* pindexHeader = NULL;
2475  {
2476  LOCK(cs_main);
2477  pindexHeader = pindexBestHeader;
2478 
2479  if (pindexHeader != pindexHeaderOld) {
2480  fNotify = true;
2481  fInitialBlockDownload = IsInitialBlockDownload();
2482  pindexHeaderOld = pindexHeader;
2483  }
2484  }
2485  // Send block tip changed notifications without cs_main
2486  if (fNotify) {
2487  uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2488  }
2489 }
2490 
2496 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2497  // Note that while we're often called here from ProcessNewBlock, this is
2498  // far from a guarantee. Things in the P2P/RPC will often end up calling
2499  // us in the middle of ProcessNewBlock - do not assume pblock is set
2500  // sanely for performance or correctness!
2501 
2502  CBlockIndex *pindexMostWork = NULL;
2503  CBlockIndex *pindexNewTip = NULL;
2504  do {
2505  boost::this_thread::interruption_point();
2506  if (ShutdownRequested())
2507  break;
2508 
2509  const CBlockIndex *pindexFork;
2510  ConnectTrace connectTrace;
2511  bool fInitialDownload;
2512  {
2513  LOCK(cs_main);
2514  { // TODO: Tempoarily ensure that mempool removals are notified before
2515  // connected transactions. This shouldn't matter, but the abandoned
2516  // state of transactions in our wallet is currently cleared when we
2517  // receive another notification and there is a race condition where
2518  // notification of a connected conflict might cause an outside process
2519  // to abandon a transaction and then have it inadvertantly cleared by
2520  // the notification that the conflicted transaction was evicted.
2522  CBlockIndex *pindexOldTip = chainActive.Tip();
2523  if (pindexMostWork == NULL) {
2524  pindexMostWork = FindMostWorkChain();
2525  }
2526 
2527  // Whether we have anything to do at all.
2528  if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2529  return true;
2530 
2531  bool fInvalidFound = false;
2532  std::shared_ptr<const CBlock> nullBlockPtr;
2533  if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
2534  return false;
2535 
2536  if (fInvalidFound) {
2537  // Wipe cache, we may need another branch now.
2538  pindexMostWork = NULL;
2539  }
2540  pindexNewTip = chainActive.Tip();
2541  pindexFork = chainActive.FindFork(pindexOldTip);
2542  fInitialDownload = IsInitialBlockDownload();
2543 
2544  // throw all transactions though the signal-interface
2545 
2546  } // MemPoolConflictRemovalTracker destroyed and conflict evictions are notified
2547 
2548  // Transactions in the connnected block are notified
2549  for (const auto& pair : connectTrace.blocksConnected) {
2550  assert(pair.second);
2551  const CBlock& block = *(pair.second);
2552  for (unsigned int i = 0; i < block.vtx.size(); i++)
2553  GetMainSignals().SyncTransaction(*block.vtx[i], pair.first, i);
2554  }
2555  }
2556  // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2557 
2558  // Notifications/callbacks that can run without cs_main
2559 
2560  // Notify external listeners about the new tip.
2561  GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
2562 
2563  // Always notify the UI if a new block tip was connected
2564  if (pindexFork != pindexNewTip) {
2565  uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2566  }
2567  } while (pindexNewTip != pindexMostWork);
2568  CheckBlockIndex(chainparams.GetConsensus(pindexNewTip->nHeight));
2569 
2570  // Write changes periodically to disk, after relay.
2571  if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2572  return false;
2573  }
2574 
2575  return true;
2576 }
2577 
2578 
2579 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
2580 {
2581  {
2582  LOCK(cs_main);
2583  if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
2584  // Nothing to do, this block is not at the tip.
2585  return true;
2586  }
2587  if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
2588  // The chain has been extended since the last call, reset the counter.
2589  nBlockReverseSequenceId = -1;
2590  }
2591  nLastPreciousChainwork = chainActive.Tip()->nChainWork;
2592  setBlockIndexCandidates.erase(pindex);
2593  pindex->nSequenceId = nBlockReverseSequenceId;
2594  if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
2595  // We can't keep reducing the counter if somebody really wants to
2596  // call preciousblock 2**31-1 times on the same set of tips...
2597  nBlockReverseSequenceId--;
2598  }
2599  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
2600  setBlockIndexCandidates.insert(pindex);
2601  PruneBlockIndexCandidates();
2602  }
2603  }
2604 
2605  return ActivateBestChain(state, params);
2606 }
2607 
2608 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
2609 {
2611 
2612  // Mark the block itself as invalid.
2613  pindex->nStatus |= BLOCK_FAILED_VALID;
2614  setDirtyBlockIndex.insert(pindex);
2615  setBlockIndexCandidates.erase(pindex);
2616 
2617  while (chainActive.Contains(pindex)) {
2618  CBlockIndex *pindexWalk = chainActive.Tip();
2619  pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2620  setDirtyBlockIndex.insert(pindexWalk);
2621  setBlockIndexCandidates.erase(pindexWalk);
2622  // ActivateBestChain considers blocks already in chainActive
2623  // unconditionally valid already, so force disconnect away from it.
2624  if (!DisconnectTip(state, chainparams)) {
2625  mempool.removeForReorg(pcoinsTip, chainActive.Height() + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2626  return false;
2627  }
2628  }
2629 
2630  LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2631 
2632  // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2633  // add it again.
2634  BlockMap::iterator it = mapBlockIndex.begin();
2635  while (it != mapBlockIndex.end()) {
2636  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2637  setBlockIndexCandidates.insert(it->second);
2638  }
2639  it++;
2640  }
2641 
2642  InvalidChainFound(pindex);
2643  mempool.removeForReorg(pcoinsTip, chainActive.Height() + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2645  return true;
2646 }
2647 
2650 
2651  int nHeight = pindex->nHeight;
2652 
2653  // Remove the invalidity flag from this block and all its descendants.
2654  BlockMap::iterator it = mapBlockIndex.begin();
2655  while (it != mapBlockIndex.end()) {
2656  if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2657  it->second->nStatus &= ~BLOCK_FAILED_MASK;
2658  setDirtyBlockIndex.insert(it->second);
2659  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2660  setBlockIndexCandidates.insert(it->second);
2661  }
2662  if (it->second == pindexBestInvalid) {
2663  // Reset invalid block marker if it was pointing to one of those.
2664  pindexBestInvalid = NULL;
2665  }
2666  }
2667  it++;
2668  }
2669 
2670  // Remove the invalidity flag from all ancestors too.
2671  while (pindex != NULL) {
2672  if (pindex->nStatus & BLOCK_FAILED_MASK) {
2673  pindex->nStatus &= ~BLOCK_FAILED_MASK;
2674  setDirtyBlockIndex.insert(pindex);
2675  }
2676  pindex = pindex->pprev;
2677  }
2678  return true;
2679 }
2680 
2682 {
2683  // Check for duplicate
2684  uint256 hash = block.GetHash();
2685  BlockMap::iterator it = mapBlockIndex.find(hash);
2686  if (it != mapBlockIndex.end())
2687  return it->second;
2688 
2689  // Construct new block index object
2690  CBlockIndex* pindexNew = new CBlockIndex(block);
2691  assert(pindexNew);
2692  // We assign the sequence id to blocks only when the full data is available,
2693  // to avoid miners withholding blocks but broadcasting headers, to get a
2694  // competitive advantage.
2695  pindexNew->nSequenceId = 0;
2696  BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
2697  pindexNew->phashBlock = &((*mi).first);
2698  BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2699  if (miPrev != mapBlockIndex.end())
2700  {
2701  pindexNew->pprev = (*miPrev).second;
2702  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2703  pindexNew->BuildSkip();
2704  }
2705  pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
2706  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2707  pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2708  if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2709  pindexBestHeader = pindexNew;
2710 
2711  setDirtyBlockIndex.insert(pindexNew);
2712 
2713  return pindexNew;
2714 }
2715 
2717 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2718 {
2719  pindexNew->nTx = block.vtx.size();
2720  pindexNew->nChainTx = 0;
2721  pindexNew->nFile = pos.nFile;
2722  pindexNew->nDataPos = pos.nPos;
2723  pindexNew->nUndoPos = 0;
2724  pindexNew->nStatus |= BLOCK_HAVE_DATA;
2725  if (IsWitnessEnabled(pindexNew->pprev, Params().GetConsensus(pindexNew->nHeight))) {
2726  pindexNew->nStatus |= BLOCK_OPT_WITNESS;
2727  }
2729  setDirtyBlockIndex.insert(pindexNew);
2730 
2731  if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2732  // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2733  std::deque<CBlockIndex*> queue;
2734  queue.push_back(pindexNew);
2735 
2736  // Recursively process any descendant blocks that now may be eligible to be connected.
2737  while (!queue.empty()) {
2738  CBlockIndex *pindex = queue.front();
2739  queue.pop_front();
2740  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2741  {
2742  LOCK(cs_nBlockSequenceId);
2743  pindex->nSequenceId = nBlockSequenceId++;
2744  }
2745  if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2746  setBlockIndexCandidates.insert(pindex);
2747  }
2748  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2749  while (range.first != range.second) {
2750  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2751  queue.push_back(it->second);
2752  range.first++;
2753  mapBlocksUnlinked.erase(it);
2754  }
2755  }
2756  } else {
2757  if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2758  mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2759  }
2760  }
2761 
2762  return true;
2763 }
2764 
2765 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2766 {
2767  LOCK(cs_LastBlockFile);
2768 
2769  unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2770  if (vinfoBlockFile.size() <= nFile) {
2771  vinfoBlockFile.resize(nFile + 1);
2772  }
2773 
2774  if (!fKnown) {
2775  while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2776  nFile++;
2777  if (vinfoBlockFile.size() <= nFile) {
2778  vinfoBlockFile.resize(nFile + 1);
2779  }
2780  }
2781  pos.nFile = nFile;
2782  pos.nPos = vinfoBlockFile[nFile].nSize;
2783  }
2784 
2785  if ((int)nFile != nLastBlockFile) {
2786  if (!fKnown) {
2787  LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2788  }
2789  FlushBlockFile(!fKnown);
2790  nLastBlockFile = nFile;
2791  }
2792 
2793  vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2794  if (fKnown)
2795  vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2796  else
2797  vinfoBlockFile[nFile].nSize += nAddSize;
2798 
2799  if (!fKnown) {
2800  unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2801  unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2802  if (nNewChunks > nOldChunks) {
2803  if (fPruneMode)
2804  fCheckForPruning = true;
2805  if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2806  FILE *file = OpenBlockFile(pos);
2807  if (file) {
2808  LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2809  AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2810  fclose(file);
2811  }
2812  }
2813  else
2814  return state.Error("out of disk space");
2815  }
2816  }
2817 
2818  setDirtyFileInfo.insert(nFile);
2819  return true;
2820 }
2821 
2822 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2823 {
2824  pos.nFile = nFile;
2825 
2826  LOCK(cs_LastBlockFile);
2827 
2828  unsigned int nNewSize;
2829  pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2830  nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2831  setDirtyFileInfo.insert(nFile);
2832 
2833  unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2834  unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2835  if (nNewChunks > nOldChunks) {
2836  if (fPruneMode)
2837  fCheckForPruning = true;
2838  if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2839  FILE *file = OpenUndoFile(pos);
2840  if (file) {
2841  LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2842  AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2843  fclose(file);
2844  }
2845  }
2846  else
2847  return state.Error("out of disk space");
2848  }
2849 
2850  return true;
2851 }
2852 
2853 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2854 {
2855  // Check proof of work matches claimed amount
2856  // We don't have block height as this is called without context (i.e. without
2857  // knowing the previous block), but that's okay, as the checks done are permissive
2858  // (i.e. doesn't check work limit or whether AuxPoW is enabled)
2859  if (fCheckPOW && !CheckAuxPowProofOfWork(block, Params().GetConsensus(0)))
2860  return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
2861 
2862  return true;
2863 }
2864 
2865 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2866 {
2867  // These are checks that are independent of context.
2868 
2869  if (block.fChecked)
2870  return true;
2871 
2872  // Check that the header is valid (particularly PoW). This is mostly
2873  // redundant with the call in AcceptBlockHeader.
2874  if (!CheckBlockHeader(block, state, fCheckPOW))
2875  return false;
2876 
2877  // Check the merkle root.
2878  if (fCheckMerkleRoot) {
2879  bool mutated;
2880  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
2881  if (block.hashMerkleRoot != hashMerkleRoot2)
2882  return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
2883 
2884  // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2885  // of transactions in a block without affecting the merkle root of a block,
2886  // while still invalidating it.
2887  if (mutated)
2888  return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
2889  }
2890 
2891  // All potential-corruption validation must be done before we do any
2892  // transaction validation, as otherwise we may mark the header as invalid
2893  // because we receive the wrong transactions for it.
2894  // Note that witness malleability is checked in ContextualCheckBlock, so no
2895  // checks that use witness data may be performed here.
2896 
2897  // Size limits
2898  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)
2899  return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
2900 
2901  // First transaction must be coinbase, the rest must not be
2902  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
2903  return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
2904  for (unsigned int i = 1; i < block.vtx.size(); i++)
2905  if (block.vtx[i]->IsCoinBase())
2906  return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
2907 
2908  // Check transactions
2909  for (const auto& tx : block.vtx)
2910  if (!CheckTransaction(*tx, state, true))
2911  return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
2912  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
2913 
2914  unsigned int nSigOps = 0;
2915  for (const auto& tx : block.vtx)
2916  {
2917  nSigOps += GetLegacySigOpCount(*tx);
2918  }
2919  if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
2920  return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
2921 
2922  if (fCheckPOW && fCheckMerkleRoot)
2923  block.fChecked = true;
2924 
2925  return true;
2926 }
2927 
2928 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2929 {
2930  if (*pindexPrev->phashBlock == chainparams.GetConsensus(0).hashGenesisBlock)
2931  return true;
2932 
2933  int nHeight = pindexPrev->nHeight+1;
2934  // Don't accept any forks from the main chain prior to last checkpoint
2935  CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2936  if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2937  return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2938 
2939  return true;
2940 }
2941 
2942 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2943 {
2944  // Dogecoin: Disable SegWit
2945  return false;
2946  // LOCK(cs_main);
2947  // return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
2948 }
2949 
2950 // Compute at which vout of the block's coinbase transaction the witness
2951 // commitment occurs, or -1 if not found.
2952 static int GetWitnessCommitmentIndex(const CBlock& block)
2953 {
2954  int commitpos = -1;
2955  if (!block.vtx.empty()) {
2956  for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
2957  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) {
2958  commitpos = o;
2959  }
2960  }
2961  }
2962  return commitpos;
2963 }
2964 
2965 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2966 {
2967  int commitpos = GetWitnessCommitmentIndex(block);
2968  static const std::vector<unsigned char> nonce(32, 0x00);
2969  if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
2970  CMutableTransaction tx(*block.vtx[0]);
2971  tx.vin[0].scriptWitness.stack.resize(1);
2972  tx.vin[0].scriptWitness.stack[0] = nonce;
2973  block.vtx[0] = MakeTransactionRef(std::move(tx));
2974  }
2975 }
2976 
2977 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
2978 {
2979  std::vector<unsigned char> commitment;
2980  int commitpos = GetWitnessCommitmentIndex(block);
2981  std::vector<unsigned char> ret(32, 0x00);
2982  if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
2983  if (commitpos == -1) {
2984  uint256 witnessroot = BlockWitnessMerkleRoot(block, NULL);
2985  CHash256().Write(witnessroot.begin(), 32).Write(&ret[0], 32).Finalize(witnessroot.begin());
2986  CTxOut out;
2987  out.nValue = 0;
2988  out.scriptPubKey.resize(38);
2989  out.scriptPubKey[0] = OP_RETURN;
2990  out.scriptPubKey[1] = 0x24;
2991  out.scriptPubKey[2] = 0xaa;
2992  out.scriptPubKey[3] = 0x21;
2993  out.scriptPubKey[4] = 0xa9;
2994  out.scriptPubKey[5] = 0xed;
2995  memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
2996  commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
2997  CMutableTransaction tx(*block.vtx[0]);
2998  tx.vout.push_back(out);
2999  block.vtx[0] = MakeTransactionRef(std::move(tx));
3000  }
3001  }
3002  UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3003  return commitment;
3004 }
3005 
3006 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
3007 {
3008  const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3009  const Consensus::Params& consensusParams = Params().GetConsensus(nHeight);
3010 
3011  // Disallow legacy blocks after merge-mining start.
3012  if (!consensusParams.fAllowLegacyBlocks
3013  && block.IsLegacy())
3014  return state.DoS(100, error("%s : legacy block after auxpow start",
3015  __func__),
3016  REJECT_INVALID, "late-legacy-block");
3017 
3018  // Dogecoin: Disallow AuxPow blocks before it is activated.
3019  // TODO: Remove this test, as checkpoints will enforce this for us now
3020  // NOTE: Previously this had its own fAllowAuxPoW flag, but that's always the opposite of fAllowLegacyBlocks
3021  if (consensusParams.fAllowLegacyBlocks
3022  && block.IsAuxpow())
3023  return state.DoS(100, error("%s : auxpow blocks are not allowed at height %d, parameters effective from %d",
3024  __func__, pindexPrev->nHeight + 1, consensusParams.nHeightEffective),
3025  REJECT_INVALID, "early-auxpow-block");
3026 
3027  // Check proof of work
3028  if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3029  return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
3030 
3031  // Check timestamp against prev
3032  if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3033  return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
3034 
3035  // Check timestamp
3036  if (block.GetBlockTime() > nAdjustedTime + 2 * 60 * 60)
3037  return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
3038 
3039  // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3040  // check for version 2, 3 and 4 upgrades
3041  // Dogecoin: Version 2 enforcement was never used
3042  if((block.GetBaseVersion() < 3 && nHeight >= consensusParams.BIP66Height) ||
3043  (block.GetBaseVersion() < 4 && nHeight >= consensusParams.BIP65Height))
3044  return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.GetBaseVersion()),
3045  strprintf("rejected nVersion=0x%08x block", block.GetBaseVersion()));
3046 
3047  return true;
3048 }
3049 
3050 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindexPrev)
3051 {
3052  const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3053  const CChainParams& chainParams = Params();
3054  const Consensus::Params& consensusParams = chainParams.GetConsensus(nHeight);
3055 
3056  // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3057  // Dogecoin: We probably want to disable this
3058  int nLockTimeFlags = 0;
3059  if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3060  nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3061  }
3062 
3063  int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3064  ? pindexPrev->GetMedianTimePast()
3065  : block.GetBlockTime();
3066 
3067  // Check that all transactions are finalized
3068  for (const auto& tx : block.vtx) {
3069  if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3070  return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3071  }
3072  }
3073 
3074  // Enforce rule that the coinbase starts with serialized block height
3075  if (nHeight >= consensusParams.BIP34Height)
3076  {
3077  CScript expect = CScript() << nHeight;
3078  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3079  !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3080  return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3081  }
3082  }
3083 
3084  // Validation for witness commitments.
3085  // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3086  // coinbase (where 0x0000....0000 is used instead).
3087  // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3088  // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3089  // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3090  // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3091  // multiple, the last one is used.
3092  bool fHaveWitness = false;
3093  if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
3094  int commitpos = GetWitnessCommitmentIndex(block);
3095  if (commitpos != -1) {
3096  bool malleated = false;
3097  uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
3098  // The malleation check is ignored; as the transaction tree itself
3099  // already does not permit it, it is impossible to trigger in the
3100  // witness tree.
3101  if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
3102  return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
3103  }
3104  CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
3105  if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
3106  return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
3107  }
3108  fHaveWitness = true;
3109  }
3110  }
3111 
3112  // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
3113  if (!fHaveWitness) {
3114  for (size_t i = 0; i < block.vtx.size(); i++) {
3115  if (block.vtx[i]->HasWitness()) {
3116  return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
3117  }
3118  }
3119  }
3120 
3121  // After the coinbase witness nonce and commitment are verified,
3122  // we can check if the block weight passes (before we've checked the
3123  // coinbase witness, it would be possible for the weight to be too
3124  // large by filling up the coinbase witness, which doesn't change
3125  // the block hash, so we couldn't mark the block as permanently
3126  // failed).
3127  if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
3128  return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
3129  }
3130 
3131  return true;
3132 }
3133 
3134 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3135 {
3137  // Check for duplicate
3138  uint256 hash = block.GetHash();
3139  BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3140  CBlockIndex *pindex = NULL;
3141  if (hash != chainparams.GetConsensus(0).hashGenesisBlock) {
3142 
3143  if (miSelf != mapBlockIndex.end()) {
3144  // Block header is already known.
3145  pindex = miSelf->second;
3146  if (ppindex)
3147  *ppindex = pindex;
3148  if (pindex->nStatus & BLOCK_FAILED_MASK)
3149  return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3150  return true;
3151  }
3152 
3153  if (!CheckBlockHeader(block, state))
3154  return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3155 
3156  // Get prev block index
3157  CBlockIndex* pindexPrev = NULL;
3158  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3159  if (mi == mapBlockIndex.end())
3160  return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3161  pindexPrev = (*mi).second;
3162  if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3163  return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3164 
3165  assert(pindexPrev);
3166  if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3167  return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3168 
3169  if (!ContextualCheckBlockHeader(block, state, pindexPrev, GetAdjustedTime()))
3170  return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3171  }
3172  if (pindex == NULL)
3173  pindex = AddToBlockIndex(block);
3174 
3175  if (ppindex)
3176  *ppindex = pindex;
3177 
3178  CheckBlockIndex(chainparams.GetConsensus(pindex->nHeight));
3179 
3180  return true;
3181 }
3182 
3183 // Exposed wrapper for AcceptBlockHeader
3184 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex)
3185 {
3186  {
3187  LOCK(cs_main);
3188  for (const CBlockHeader& header : headers) {
3189  CBlockIndex *pindex = NULL; // Use a temp pindex instead of ppindex to avoid a const_cast
3190  if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
3191  return false;
3192  }
3193  if (ppindex) {
3194  *ppindex = pindex;
3195  }
3196  }
3197  }
3198  NotifyHeaderTip();
3199  return true;
3200 }
3201 
3203 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3204 {
3205  const CBlock& block = *pblock;
3206 
3207  if (fNewBlock) *fNewBlock = false;
3209 
3210  CBlockIndex *pindexDummy = NULL;
3211  CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3212 
3213  if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3214  return false;
3215 
3216  // Try to process all requested blocks that we don't have, but only
3217  // process an unrequested block if it's new and has enough work to
3218  // advance our tip, and isn't too many blocks ahead.
3219  bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3220  bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3221  // Blocks that are too out-of-order needlessly limit the effectiveness of
3222  // pruning, because pruning will not delete block files that contain any
3223  // blocks which are too close in height to the tip. Apply this test
3224  // regardless of whether pruning is enabled; it should generally be safe to
3225  // not process unrequested blocks.
3226  bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3227 
3228  // TODO: Decouple this function from the block download logic by removing fRequested
3229  // This requires some new chain datastructure to efficiently look up if a
3230  // block is in a chain leading to a candidate for best tip, despite not
3231  // being such a candidate itself.
3232 
3233  // TODO: deal better with return value and error conditions for duplicate
3234  // and unrequested blocks.
3235  if (fAlreadyHave) return true;
3236  if (!fRequested) { // If we didn't ask for it:
3237  if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3238  if (!fHasMoreWork) return true; // Don't process less-work chains
3239  if (fTooFarAhead) return true; // Block height is too high
3240  }
3241  if (fNewBlock) *fNewBlock = true;
3242 
3243  if (!CheckBlock(block, state) ||
3244  !ContextualCheckBlock(block, state, pindex->pprev)) {
3245  if (state.IsInvalid() && !state.CorruptionPossible()) {
3246  pindex->nStatus |= BLOCK_FAILED_VALID;
3247  setDirtyBlockIndex.insert(pindex);
3248  }
3249  return error("%s: %s", __func__, FormatStateMessage(state));
3250  }
3251 
3252  // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
3253  // (but if it does not build on our best tip, let the SendMessages loop relay it)
3254  if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3255  GetMainSignals().NewPoWValidBlock(pindex, pblock);
3256 
3257  int nHeight = pindex->nHeight;
3258 
3259  // Write block to history file
3260  try {
3261  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3262  CDiskBlockPos blockPos;
3263  if (dbp != NULL)
3264  blockPos = *dbp;
3265  if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3266  return error("AcceptBlock(): FindBlockPos failed");
3267  if (dbp == NULL)
3268  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3269  AbortNode(state, "Failed to write block");
3270  if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3271  return error("AcceptBlock(): ReceivedBlockTransactions failed");
3272  } catch (const std::runtime_error& e) {
3273  return AbortNode(state, std::string("System error: ") + e.what());
3274  }
3275 
3276  if (fCheckForPruning)
3277  FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3278 
3279  return true;
3280 }
3281 
3282 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3283 {
3284  unsigned int nFound = 0;
3285  for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3286  {
3287  if (pstart->GetBaseVersion() >= minVersion)
3288  ++nFound;
3289  pstart = pstart->pprev;
3290  }
3291  return (nFound >= nRequired);
3292 }
3293 
3294 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3295 {
3296  {
3297  CBlockIndex *pindex = NULL;
3298  if (fNewBlock) *fNewBlock = false;
3299  CValidationState state;
3300  // Ensure that CheckBlock() passes before calling AcceptBlock, as
3301  // belt-and-suspenders.
3302  bool ret = CheckBlock(*pblock, state);
3303 
3304  LOCK(cs_main);
3305 
3306  if (ret) {
3307  // Store to disk
3308  ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, NULL, fNewBlock);
3309  }
3310  CheckBlockIndex(chainparams.GetConsensus(chainActive.Height()));
3311  if (!ret) {
3312  GetMainSignals().BlockChecked(*pblock, state);
3313  return error("%s: AcceptBlock FAILED", __func__);
3314  }
3315  }
3316 
3317  NotifyHeaderTip();
3318 
3319  CValidationState state; // Only used to report errors, not invalidity - ignore it
3320  if (!ActivateBestChain(state, chainparams, pblock))
3321  return error("%s: ActivateBestChain failed", __func__);
3322 
3323  return true;
3324 }
3325 
3326 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3327 {
3329  assert(pindexPrev && pindexPrev == chainActive.Tip());
3330  if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3331  return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3332 
3333  CCoinsViewCache viewNew(pcoinsTip);
3334  CBlockIndex indexDummy(block);
3335  indexDummy.pprev = pindexPrev;
3336  indexDummy.nHeight = pindexPrev->nHeight + 1;
3337 
3338  // NOTE: CheckBlockHeader is called by CheckBlock
3339  if (!ContextualCheckBlockHeader(block, state, pindexPrev, GetAdjustedTime()))
3340  return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3341  if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
3342  return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3343  if (!ContextualCheckBlock(block, state, pindexPrev))
3344  return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3345  if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3346  return false;
3347  assert(state.IsValid());
3348 
3349  return true;
3350 }
3351 
3356 /* Calculate the amount of disk space the block & undo files currently use */
3358 {
3359  LOCK(cs_LastBlockFile);
3360 
3361  uint64_t retval = 0;
3362  BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3363  retval += file.nSize + file.nUndoSize;
3364  }
3365  return retval;
3366 }
3367 
3368 /* Prune a block file (modify associated database entries)*/
3369 void PruneOneBlockFile(const int fileNumber)
3370 {
3371  LOCK(cs_LastBlockFile);
3372 
3373  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3374  CBlockIndex* pindex = it->second;
3375  if (pindex->nFile == fileNumber) {
3376  pindex->nStatus &= ~BLOCK_HAVE_DATA;
3377  pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3378  pindex->nFile = 0;
3379  pindex->nDataPos = 0;
3380  pindex->nUndoPos = 0;
3381  setDirtyBlockIndex.insert(pindex);
3382 
3383  // Prune from mapBlocksUnlinked -- any block we prune would have
3384  // to be downloaded again in order to consider its chain, at which
3385  // point it would be considered as a candidate for
3386  // mapBlocksUnlinked or setBlockIndexCandidates.
3387  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3388  while (range.first != range.second) {
3389  std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3390  range.first++;
3391  if (_it->second == pindex) {
3392  mapBlocksUnlinked.erase(_it);
3393  }
3394  }
3395  }
3396  }
3397 
3398  vinfoBlockFile[fileNumber].SetNull();
3399  setDirtyFileInfo.insert(fileNumber);
3400 }
3401 
3402 
3403 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3404 {
3405  for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3406  CDiskBlockPos pos(*it, 0);
3407  boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3408  boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3409  LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3410  }
3411 }
3412 
3413 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3414 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3415 {
3416  assert(fPruneMode && nManualPruneHeight > 0);
3417 
3418  LOCK2(cs_main, cs_LastBlockFile);
3419  if (chainActive.Tip() == NULL)
3420  return;
3421 
3422  // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3423  unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Height() - MIN_BLOCKS_TO_KEEP);
3424  int count=0;
3425  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3426  if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3427  continue;
3428  PruneOneBlockFile(fileNumber);
3429  setFilesToPrune.insert(fileNumber);
3430  count++;
3431  }
3432  LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3433 }
3434 
3435 /* This function is called from the RPC code for pruneblockchain */
3436 void PruneBlockFilesManual(int nManualPruneHeight)
3437 {
3438  CValidationState state;
3439  FlushStateToDisk(state, FLUSH_STATE_NONE, nManualPruneHeight);
3440 }
3441 
3442 /* Calculate the block/rev files that should be deleted to remain under target*/
3443 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3444 {
3445  LOCK2(cs_main, cs_LastBlockFile);
3446  if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3447  return;
3448  }
3449  if ((uint64_t)chainActive.Height() <= nPruneAfterHeight) {
3450  return;
3451  }
3452 
3453  unsigned int nLastBlockWeCanPrune = chainActive.Height() - MIN_BLOCKS_TO_KEEP;
3454  uint64_t nCurrentUsage = CalculateCurrentUsage();
3455  // We don't check to prune until after we've allocated new space for files
3456  // So we should leave a buffer under our target to account for another allocation
3457  // before the next pruning.
3458  uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3459  uint64_t nBytesToPrune;
3460  int count=0;
3461 
3462  if (nCurrentUsage + nBuffer >= nPruneTarget) {
3463  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3464  nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3465 
3466  if (vinfoBlockFile[fileNumber].nSize == 0)
3467  continue;
3468 
3469  if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3470  break;
3471 
3472  // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3473  if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3474  continue;
3475 
3476  PruneOneBlockFile(fileNumber);
3477  // Queue up the files for removal
3478  setFilesToPrune.insert(fileNumber);
3479  nCurrentUsage -= nBytesToPrune;
3480  count++;
3481  }
3482  }
3483 
3484  LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3485  nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3486  ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3487  nLastBlockWeCanPrune, count);
3488 }
3489 
3490 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3491 {
3492  uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3493 
3494  // Check for nMinDiskSpace bytes (currently 50MB)
3495  if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3496  return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3497 
3498  return true;
3499 }
3500 
3501 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3502 {
3503  if (pos.IsNull())
3504  return NULL;
3505  boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3506  boost::filesystem::create_directories(path.parent_path());
3507  FILE* file = fopen(path.string().c_str(), "rb+");
3508  if (!file && !fReadOnly)
3509  file = fopen(path.string().c_str(), "wb+");
3510  if (!file) {
3511  LogPrintf("Unable to open file %s\n", path.string());
3512  return NULL;
3513  }
3514  if (pos.nPos) {
3515  if (fseek(file, pos.nPos, SEEK_SET)) {
3516  LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3517  fclose(file);
3518  return NULL;
3519  }
3520  }
3521  return file;
3522 }
3523 
3524 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3525  return OpenDiskFile(pos, "blk", fReadOnly);
3526 }
3527 
3528 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3529  return OpenDiskFile(pos, "rev", fReadOnly);
3530 }
3531 
3532 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3533 {
3534  return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3535 }
3536 
3538 {
3539  if (hash.IsNull())
3540  return NULL;
3541 
3542  // Return existing
3543  BlockMap::iterator mi = mapBlockIndex.find(hash);
3544  if (mi != mapBlockIndex.end())
3545  return (*mi).second;
3546 
3547  // Create new
3548  CBlockIndex* pindexNew = new CBlockIndex();
3549  if (!pindexNew)
3550  throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
3551  mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3552  pindexNew->phashBlock = &((*mi).first);
3553 
3554  return pindexNew;
3555 }
3556 
3557 bool static LoadBlockIndexDB(const CChainParams& chainparams)
3558 {
3560  return false;
3561 
3562  boost::this_thread::interruption_point();
3563 
3564  // Calculate nChainWork
3565  std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
3566  vSortedByHeight.reserve(mapBlockIndex.size());
3567  BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3568  {
3569  CBlockIndex* pindex = item.second;
3570  vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
3571  }
3572  sort(vSortedByHeight.begin(), vSortedByHeight.end());
3573  BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3574  {
3575  CBlockIndex* pindex = item.second;
3576  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3577  pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
3578  // We can link the chain of blocks for which we've received transactions at some point.
3579  // Pruned nodes may have deleted the block.
3580  if (pindex->nTx > 0) {
3581  if (pindex->pprev) {
3582  if (pindex->pprev->nChainTx) {
3583  pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3584  } else {
3585  pindex->nChainTx = 0;
3586  mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3587  }
3588  } else {
3589  pindex->nChainTx = pindex->nTx;
3590  }
3591  }
3592  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3593  setBlockIndexCandidates.insert(pindex);
3594  if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3595  pindexBestInvalid = pindex;
3596  if (pindex->pprev)
3597  pindex->BuildSkip();
3598  if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3599  pindexBestHeader = pindex;
3600  }
3601 
3602  // Load block file info
3603  pblocktree->ReadLastBlockFile(nLastBlockFile);
3604  vinfoBlockFile.resize(nLastBlockFile + 1);
3605  LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3606  for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3607  pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3608  }
3609  LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3610  for (int nFile = nLastBlockFile + 1; true; nFile++) {
3611  CBlockFileInfo info;
3612  if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3613  vinfoBlockFile.push_back(info);
3614  } else {
3615  break;
3616  }
3617  }
3618 
3619  // Check presence of blk files
3620  LogPrintf("Checking all blk files are present...\n");
3621  std::set<int> setBlkDataFiles;
3622  BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3623  {
3624  CBlockIndex* pindex = item.second;
3625  if (pindex->nStatus & BLOCK_HAVE_DATA) {
3626  setBlkDataFiles.insert(pindex->nFile);
3627  }
3628  }
3629  for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3630  {
3631  CDiskBlockPos pos(*it, 0);
3632  if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3633  return false;
3634  }
3635  }
3636 
3637  // Check whether we have ever pruned block & undo files
3638  pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3639  if (fHavePruned)
3640  LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3641 
3642  // Check whether we need to continue reindexing
3643  bool fReindexing = false;
3644  pblocktree->ReadReindexing(fReindexing);
3645  fReindex |= fReindexing;
3646 
3647  // Check whether we have a transaction index
3648  pblocktree->ReadFlag("txindex", fTxIndex);
3649  LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3650 
3651  // Load pointer to end of best chain
3652  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3653  if (it == mapBlockIndex.end())
3654  return true;
3655  chainActive.SetTip(it->second);
3656 
3657  PruneBlockIndexCandidates();
3658 
3659  LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3661  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3662  GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
3663 
3664  return true;
3665 }
3666 
3668 {
3669  uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3670 }
3671 
3673 {
3674  uiInterface.ShowProgress("", 100);
3675 }
3676 
3677 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3678 {
3679  LOCK(cs_main);
3680  if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3681  return true;
3682 
3683  // Verify blocks in the best chain
3684  if (nCheckDepth <= 0)
3685  nCheckDepth = 1000000000; // suffices until the year 19000
3686  if (nCheckDepth > chainActive.Height())
3687  nCheckDepth = chainActive.Height();
3688  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3689  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3690  CCoinsViewCache coins(coinsview);
3691  CBlockIndex* pindexState = chainActive.Tip();
3692  CBlockIndex* pindexFailure = NULL;
3693  int nGoodTransactions = 0;
3694  CValidationState state;
3695  int reportDone = 0;
3696  LogPrintf("[0%%]...");
3697  for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3698  {
3699  boost::this_thread::interruption_point();
3700  int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
3701  if (reportDone < percentageDone/10) {
3702  // report every 10% step
3703  LogPrintf("[%d%%]...", percentageDone);
3704  reportDone = percentageDone/10;
3705  }
3706  uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
3707  if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3708  break;
3709  if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3710  // If pruning, only go back as far as we have data.
3711  LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3712  break;
3713  }
3714  CBlock block;
3715  // check level 0: read from disk
3716  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus(pindex->nHeight)))
3717  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3718  // check level 1: verify block validity
3719  if (nCheckLevel >= 1 && !CheckBlock(block, state))
3720  return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3721  pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3722  // check level 2: verify undo validity
3723  if (nCheckLevel >= 2 && pindex) {
3724  CBlockUndo undo;
3725  CDiskBlockPos pos = pindex->GetUndoPos();
3726  if (!pos.IsNull()) {
3727  if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3728  return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3729  }
3730  }
3731  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3732  if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3733  bool fClean = true;
3734  if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3735  return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3736  pindexState = pindex->pprev;
3737  if (!fClean) {
3738  nGoodTransactions = 0;
3739  pindexFailure = pindex;
3740  } else
3741  nGoodTransactions += block.vtx.size();
3742  }
3743  if (ShutdownRequested())
3744  return true;
3745  }
3746  if (pindexFailure)
3747  return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3748 
3749  // check level 4: try reconnecting blocks
3750  if (nCheckLevel >= 4) {
3751  CBlockIndex *pindex = pindexState;
3752  while (pindex != chainActive.Tip()) {
3753  boost::this_thread::interruption_point();
3754  uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3755  pindex = chainActive.Next(pindex);
3756  CBlock block;
3757  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus(pindex->nHeight)))
3758  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3759  if (!ConnectBlock(block, state, pindex, coins, chainparams))
3760  return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3761  }
3762  }
3763 
3764  LogPrintf("[DONE].\n");
3765  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3766 
3767  return true;
3768 }
3769 
3770 bool RewindBlockIndex(const CChainParams& params)
3771 {
3772  LOCK(cs_main);
3773 
3774  int nHeight = 1;
3775  while (nHeight <= chainActive.Height()) {
3776  if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus(nHeight - 1)) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
3777  break;
3778  }
3779  nHeight++;
3780  }
3781 
3782  // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3783  CValidationState state;
3784  CBlockIndex* pindex = chainActive.Tip();
3785  while (chainActive.Height() >= nHeight) {
3787  // If pruning, don't try rewinding past the HAVE_DATA point;
3788  // since older blocks can't be served anyway, there's
3789  // no need to walk further, and trying to DisconnectTip()
3790  // will fail (and require a needless reindex/redownload
3791  // of the blockchain).
3792  break;
3793  }
3794  if (!DisconnectTip(state, params, true)) {
3795  return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3796  }
3797  // Occasionally flush state to disk.
3799  return false;
3800  }
3801 
3802  // Reduce validity flag and have-data flags.
3803  // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3804  // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3805  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3806  CBlockIndex* pindexIter = it->second;
3807 
3808  // Note: If we encounter an insufficiently validated block that
3809  // is on chainActive, it must be because we are a pruning node, and
3810  // this block or some successor doesn't HAVE_DATA, so we were unable to
3811  // rewind all the way. Blocks remaining on chainActive at this point
3812  // must not have their validity reduced.
3813  if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus(pindexIter->nHeight)) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
3814  // Reduce validity
3815  pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3816  // Remove have-data flags.
3817  pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3818  // Remove storage location.
3819  pindexIter->nFile = 0;
3820  pindexIter->nDataPos = 0;
3821  pindexIter->nUndoPos = 0;
3822  // Remove various other things
3823  pindexIter->nTx = 0;
3824  pindexIter->nChainTx = 0;
3825  pindexIter->nSequenceId = 0;
3826  // Make sure it gets written.
3827  setDirtyBlockIndex.insert(pindexIter);
3828  // Update indexes
3829  setBlockIndexCandidates.erase(pindexIter);
3830  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3831  while (ret.first != ret.second) {
3832  if (ret.first->second == pindexIter) {
3833  mapBlocksUnlinked.erase(ret.first++);
3834  } else {
3835  ++ret.first;
3836  }
3837  }
3838  } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
3839  setBlockIndexCandidates.insert(pindexIter);
3840  }
3841  }
3842 
3843  PruneBlockIndexCandidates();
3844 
3845  CheckBlockIndex(params.GetConsensus(chainActive.Height()));
3846 
3847  if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
3848  return false;
3849  }
3850 
3851  return true;
3852 }
3853 
3854 // May NOT be used after any connections are up as much
3855 // of the peer-processing logic assumes a consistent
3856 // block index state
3858 {
3859  LOCK(cs_main);
3860  setBlockIndexCandidates.clear();
3861  chainActive.SetTip(NULL);
3862  pindexBestInvalid = NULL;
3863  pindexBestHeader = NULL;
3864  mempool.clear();
3865  mapBlocksUnlinked.clear();
3866  vinfoBlockFile.clear();
3867  nLastBlockFile = 0;
3868  nBlockSequenceId = 1;
3869  setDirtyBlockIndex.clear();
3870  setDirtyFileInfo.clear();
3872  for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3873  warningcache[b].clear();
3874  }
3875 
3876  BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3877  delete entry.second;
3878  }
3879  mapBlockIndex.clear();
3880  fHavePruned = false;
3881 }
3882 
3883 bool LoadBlockIndex(const CChainParams& chainparams)
3884 {
3885  // Load block index from databases
3886  if (!fReindex && !LoadBlockIndexDB(chainparams))
3887  return false;
3888  return true;
3889 }
3890 
3891 bool InitBlockIndex(const CChainParams& chainparams)
3892 {
3893  LOCK(cs_main);
3894 
3895  // Check whether we're already initialized
3896  if (chainActive.Genesis() != NULL)
3897  return true;
3898 
3899  // Use the provided setting for -txindex in the new database
3900  fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3901  pblocktree->WriteFlag("txindex", fTxIndex);
3902  LogPrintf("Initializing databases...\n");
3903 
3904  // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3905  if (!fReindex) {
3906  try {
3907  CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
3908  // Start new block file
3909  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3910  CDiskBlockPos blockPos;
3911  CValidationState state;
3912  if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3913  return error("LoadBlockIndex(): FindBlockPos failed");
3914  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3915  return error("LoadBlockIndex(): writing genesis block to disk failed");
3916  CBlockIndex *pindex = AddToBlockIndex(block);
3917  if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3918  return error("LoadBlockIndex(): genesis block not accepted");
3919  // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3920  return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3921  } catch (const std::runtime_error& e) {
3922  return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3923  }
3924  }
3925 
3926  return true;
3927 }
3928 
3929 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
3930 {
3931  // Map of disk positions for blocks with unknown parent (only used for reindex)
3932  static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3933  int64_t nStart = GetTimeMillis();
3934 
3935  int nLoaded = 0;
3936  try {
3937  // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3938  CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
3939  uint64_t nRewind = blkdat.GetPos();
3940  while (!blkdat.eof()) {
3941  boost::this_thread::interruption_point();
3942 
3943  blkdat.SetPos(nRewind);
3944  nRewind++; // start one byte further next time, in case of failure
3945  blkdat.SetLimit(); // remove former limit
3946  unsigned int nSize = 0;
3947  try {
3948  // locate a header
3949  unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
3950  blkdat.FindByte(chainparams.MessageStart()[0]);
3951  nRewind = blkdat.GetPos()+1;
3952  blkdat >> FLATDATA(buf);
3953  if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
3954  continue;
3955  // read size
3956  blkdat >> nSize;
3957  if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
3958  continue;
3959  } catch (const std::exception&) {
3960  // no valid block header found; don't complain
3961  break;
3962  }
3963  try {
3964  // read block
3965  uint64_t nBlockPos = blkdat.GetPos();
3966  if (dbp)
3967  dbp->nPos = nBlockPos;
3968  blkdat.SetLimit(nBlockPos + nSize);
3969  blkdat.SetPos(nBlockPos);
3970  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
3971  CBlock& block = *pblock;
3972  blkdat >> block;
3973  nRewind = blkdat.GetPos();
3974 
3975  // detect out of order blocks, and store them for later
3976  uint256 hash = block.GetHash();
3977  if (hash != chainparams.GetConsensus(0).hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3978  LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3979  block.hashPrevBlock.ToString());
3980  if (dbp)
3981  mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3982  continue;
3983  }
3984 
3985  // process in case the block isn't known yet
3986  if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3987  LOCK(cs_main);
3988  CValidationState state;
3989  if (AcceptBlock(pblock, state, chainparams, NULL, true, dbp, NULL))
3990  nLoaded++;
3991  if (state.IsError())
3992  break;
3993  } else if (hash != chainparams.GetConsensus(0).hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3994  LogPrint("reindex", "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3995  }
3996 
3997  // Activate the genesis block so normal node progress can continue
3998  if (hash == chainparams.GetConsensus(0).hashGenesisBlock) {
3999  CValidationState state;
4000  if (!ActivateBestChain(state, chainparams)) {
4001  break;
4002  }
4003  }
4004 
4005  NotifyHeaderTip();
4006 
4007  // Recursively process earlier encountered successors of this block
4008  std::deque<uint256> queue;
4009  queue.push_back(hash);
4010  while (!queue.empty()) {
4011  uint256 head = queue.front();
4012  queue.pop_front();
4013  std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4014  while (range.first != range.second) {
4015  std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4016  std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4017  // TODO: Need a valid consensus height
4018  if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus(0)))
4019  {
4020  LogPrint("reindex", "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4021  head.ToString());
4022  LOCK(cs_main);
4023  CValidationState dummy;
4024  if (AcceptBlock(pblockrecursive, dummy, chainparams, NULL, true, &it->second, NULL))
4025  {
4026  nLoaded++;
4027  queue.push_back(pblockrecursive->GetHash());
4028  }
4029  }
4030  range.first++;
4031  mapBlocksUnknownParent.erase(it);
4032  NotifyHeaderTip();
4033  }
4034  }
4035  } catch (const std::exception& e) {
4036  LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4037  }
4038  }
4039  } catch (const std::runtime_error& e) {
4040  AbortNode(std::string("System error: ") + e.what());
4041  }
4042  if (nLoaded > 0)
4043  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4044  return nLoaded > 0;
4045 }
4046 
4047 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4048 {
4049  if (!fCheckBlockIndex) {
4050  return;
4051  }
4052 
4053  LOCK(cs_main);
4054 
4055  // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4056  // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4057  // iterating the block tree require that chainActive has been initialized.)
4058  if (chainActive.Height() < 0) {
4059  assert(mapBlockIndex.size() <= 1);
4060  return;
4061  }
4062 
4063  // Build forward-pointing map of the entire block tree.
4064  std::multimap<CBlockIndex*,CBlockIndex*> forward;
4065  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4066  forward.insert(std::make_pair(it->second->pprev, it->second));
4067  }
4068 
4069  assert(forward.size() == mapBlockIndex.size());
4070 
4071  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4072  CBlockIndex *pindex = rangeGenesis.first->second;
4073  rangeGenesis.first++;
4074  assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4075 
4076  // Iterate over the entire block tree, using depth-first search.
4077  // Along the way, remember whether there are blocks on the path from genesis
4078  // block being explored which are the first to have certain properties.
4079  size_t nNodes = 0;
4080  int nHeight = 0;
4081  CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4082  CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4083  CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4084  CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4085  CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4086  CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4087  CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4088  while (pindex != NULL) {
4089  nNodes++;
4090  if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4091  if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4092  if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4093  if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4094  if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4095  if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4096  if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4097 
4098  // Begin: actual consistency checks.
4099  if (pindex->pprev == NULL) {
4100  // Genesis block checks.
4101  assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4102  assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4103  }
4104  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)
4105  // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4106  // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4107  if (!fHavePruned) {
4108  // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4109  assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4110  assert(pindexFirstMissing == pindexFirstNeverProcessed);
4111  } else {
4112  // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4113  if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4114  }
4115  if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4116  assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4117  // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4118  assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4119  assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4120  assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4121  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.
4122  assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4123  assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4124  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4125  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4126  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4127  if (pindexFirstInvalid == NULL) {
4128  // Checks for not-invalid blocks.
4129  assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4130  }
4131  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4132  if (pindexFirstInvalid == NULL) {
4133  // If this block sorts at least as good as the current tip and
4134  // is valid and we have all data for its parents, it must be in
4135  // setBlockIndexCandidates. chainActive.Tip() must also be there
4136  // even if some data has been pruned.
4137  if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4138  assert(setBlockIndexCandidates.count(pindex));
4139  }
4140  // If some parent is missing, then it could be that this block was in
4141  // setBlockIndexCandidates but had to be removed because of the missing data.
4142  // In this case it must be in mapBlocksUnlinked -- see test below.
4143  }
4144  } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4145  assert(setBlockIndexCandidates.count(pindex) == 0);
4146  }
4147  // Check whether this block is in mapBlocksUnlinked.
4148  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4149  bool foundInUnlinked = false;
4150  while (rangeUnlinked.first != rangeUnlinked.second) {
4151  assert(rangeUnlinked.first->first == pindex->pprev);
4152  if (rangeUnlinked.first->second == pindex) {
4153  foundInUnlinked = true;
4154  break;
4155  }
4156  rangeUnlinked.first++;
4157  }
4158  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4159  // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4160  assert(foundInUnlinked);
4161  }
4162  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4163  if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4164  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4165  // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4166  assert(fHavePruned); // We must have pruned.
4167  // This block may have entered mapBlocksUnlinked if:
4168  // - it has a descendant that at some point had more work than the
4169  // tip, and
4170  // - we tried switching to that descendant but were missing
4171  // data for some intermediate block between chainActive and the
4172  // tip.
4173  // So if this block is itself better than chainActive.Tip() and it wasn't in
4174  // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4175  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4176  if (pindexFirstInvalid == NULL) {
4177  assert(foundInUnlinked);
4178  }
4179  }
4180  }
4181  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4182  // End: actual consistency checks.
4183 
4184  // Try descending into the first subnode.
4185  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4186  if (range.first != range.second) {
4187  // A subnode was found.
4188  pindex = range.first->second;
4189  nHeight++;
4190  continue;
4191  }
4192  // This is a leaf node.
4193  // Move upwards until we reach a node of which we have not yet visited the last child.
4194  while (pindex) {
4195  // We are going to either move to a parent or a sibling of pindex.
4196  // If pindex was the first with a certain property, unset the corresponding variable.
4197  if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4198  if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4199  if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4200  if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4201  if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4202  if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4203  if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4204  // Find our parent.
4205  CBlockIndex* pindexPar = pindex->pprev;
4206  // Find which child we just visited.
4207  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4208  while (rangePar.first->second != pindex) {
4209  assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4210  rangePar.first++;
4211  }
4212  // Proceed to the next one.
4213  rangePar.first++;
4214  if (rangePar.first != rangePar.second) {
4215  // Move to the sibling.
4216  pindex = rangePar.first->second;
4217  break;
4218  } else {
4219  // Move up further.
4220  pindex = pindexPar;
4221  nHeight--;
4222  continue;
4223  }
4224  }
4225  }
4226 
4227  // Check that we actually traversed the entire map.
4228  assert(nNodes == forward.size());
4229 }
4230 
4231 std::string CBlockFileInfo::ToString() const
4232 {
4233  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));
4234 }
4235 
4237 {
4238  LOCK(cs_LastBlockFile);
4239 
4240  return &vinfoBlockFile.at(n);
4241 }
4242 
4244 {
4245  LOCK(cs_main);
4246  return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4247 }
4248 
4250 {
4251  LOCK(cs_main);
4253 }
4254 
4255 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4256 
4257 bool LoadMempool(void)
4258 {
4259  int64_t nExpiryTimeout = GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4260  FILE* filestr = fopen((GetDataDir() / "mempool.dat").string().c_str(), "rb");
4261  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4262  if (file.IsNull()) {
4263  LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4264  return false;
4265  }
4266 
4267  int64_t count = 0;
4268  int64_t skipped = 0;
4269  int64_t failed = 0;
4270  int64_t nNow = GetTime();
4271 
4272  try {
4273  uint64_t version;
4274  file >> version;
4275  if (version != MEMPOOL_DUMP_VERSION) {
4276  return false;
4277  }
4278  uint64_t num;
4279  file >> num;
4280  double prioritydummy = 0;
4281  while (num--) {
4282  CTransactionRef tx;
4283  int64_t nTime;
4284  int64_t nFeeDelta;
4285  file >> tx;
4286  file >> nTime;
4287  file >> nFeeDelta;
4288 
4289  CAmount amountdelta = nFeeDelta;
4290  if (amountdelta) {
4291  mempool.PrioritiseTransaction(tx->GetHash(), tx->GetHash().ToString(), prioritydummy, amountdelta);
4292  }
4293  CValidationState state;
4294  if (nTime + nExpiryTimeout > nNow) {
4295  LOCK(cs_main);
4296  AcceptToMemoryPoolWithTime(mempool, state, tx, true, NULL, nTime);
4297  if (state.IsValid()) {
4298  ++count;
4299  } else {
4300  ++failed;
4301  }
4302  } else {
4303  ++skipped;
4304  }
4305  if (ShutdownRequested())
4306  return false;
4307  }
4308  std::map<uint256, CAmount> mapDeltas;
4309  file >> mapDeltas;
4310 
4311  for (const auto& i : mapDeltas) {
4312  mempool.PrioritiseTransaction(i.first, i.first.ToString(), prioritydummy, i.second);
4313  }
4314  } catch (const std::exception& e) {
4315  LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4316  return false;
4317  }
4318 
4319  LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
4320  return true;
4321 }
4322 
4323 void DumpMempool(void)
4324 {
4325  int64_t start = GetTimeMicros();
4326 
4327  std::map<uint256, CAmount> mapDeltas;
4328  std::vector<TxMempoolInfo> vinfo;
4329 
4330  {
4331  LOCK(mempool.cs);
4332  for (const auto &i : mempool.mapDeltas) {
4333  mapDeltas[i.first] = i.second.second;
4334  }
4335  vinfo = mempool.infoAll();
4336  }
4337 
4338  int64_t mid = GetTimeMicros();
4339 
4340  try {
4341  FILE* filestr = fopen((GetDataDir() / "mempool.dat.new").string().c_str(), "wb");
4342  if (!filestr) {
4343  return;
4344  }
4345 
4346  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4347 
4348  uint64_t version = MEMPOOL_DUMP_VERSION;
4349  file << version;
4350 
4351  file << (uint64_t)vinfo.size();
4352  for (const auto& i : vinfo) {
4353  file << *(i.tx);
4354  file << (int64_t)i.nTime;
4355  file << (int64_t)i.nFeeDelta;
4356  mapDeltas.erase(i.tx->GetHash());
4357  }
4358 
4359  file << mapDeltas;
4360  FileCommit(file.Get());
4361  file.fclose();
4362  RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
4363  int64_t last = GetTimeMicros();
4364  LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
4365  } catch (const std::exception& e) {
4366  LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
4367  }
4368 }
4369 
4371 double GuessVerificationProgress(const ChainTxData& data, CBlockIndex *pindex) {
4372  if (pindex == NULL)
4373  return 0.0;
4374 
4375  int64_t nNow = time(NULL);
4376 
4377  double fTxTotal;
4378 
4379  if (pindex->nChainTx <= data.nTxCount) {
4380  fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
4381  } else {
4382  fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
4383  }
4384 
4385  return pindex->nChainTx / fTxTotal;
4386 }
4387 
4389 {
4390 public:
4393  // block headers
4394  BlockMap::iterator it1 = mapBlockIndex.begin();
4395  for (; it1 != mapBlockIndex.end(); it1++)
4396  delete (*it1).second;
4397  mapBlockIndex.clear();
4398  }
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:32
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:15
arith_uint256 UintToArith256(const uint256 &a)
int flags
Definition: bitcoin-tx.cpp:468
int64_t GetBlockWeight(const CBlock &block)
Compute the consensus-critical block weight (see BIP 141).
Definition: block.cpp:43
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:149
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:164
@ BLOCK_VALID_CHAIN
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends,...
Definition: chain.h:132
@ BLOCK_VALID_MASK
All validity bits.
Definition: chain.h:138
@ BLOCK_VALID_TRANSACTIONS
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid,...
Definition: chain.h:128
@ BLOCK_VALID_SCRIPTS
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:135
@ BLOCK_VALID_TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:121
@ BLOCK_HAVE_UNDO
undo data available in rev*.dat
Definition: chain.h:142
@ BLOCK_HAVE_DATA
full block available in blk*.dat
Definition: chain.h:141
@ BLOCK_FAILED_CHILD
descends from failed block
Definition: chain.h:146
@ BLOCK_FAILED_MASK
Definition: chain.h:147
@ BLOCK_FAILED_VALID
stage after last reached validness failed
Definition: chain.h:145
@ BLOCK_OPT_WITNESS
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:149
const CChainParams & Params()
Return the currently selected parameters.
Abstract class that implements BIP9-style threshold logic, and caches results.
Definition: versionbits.h:45
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API.
Definition: sync.h:56
static void Notify(const std::string &strMessage, bool fThread=true)
Definition: alert.cpp:229
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:456
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:496
bool IsNull() const
Return true if the wrapped FILE* is NULL, false otherwise.
Definition: streams.h:500
void fclose()
Definition: streams.h:478
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:26
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:27
std::string ToString() const
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:24
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:25
unsigned int nUndoSize
number of used bytes in the undo file
Definition: chain.h:23
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:21
unsigned int nSize
number of used bytes of block file
Definition: chain.h:22
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:25
Definition: block.h:67
std::vector< CTransactionRef > vtx
Definition: block.h:70
bool fChecked
Definition: block.h:73
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:158
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:318
std::string ToString() const
Definition: chain.h:299
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:164
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:143
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:182
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:173
int nVersion
block header
Definition: chain.h:197
unsigned int nTime
Definition: chain.h:199
int GetBaseVersion() const
Definition: chain.h:356
unsigned int nTimeMax
(memory only) Maximum nTime in the chain upto and including this block.
Definition: chain.h:207
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:204
unsigned int nUndoPos
Byte offset within rev?????.dat where this block's undo data is stored.
Definition: chain.h:179
uint256 GetBlockHash() const
Definition: chain.h:268
int64_t GetBlockTime() const
Definition: chain.h:273
CDiskBlockPos GetUndoPos() const
Definition: chain.h:257
int64_t GetMedianTimePast() const
Definition: chain.h:285
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:167
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:194
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:186
CDiskBlockPos GetBlockPos() const
Definition: chain.h:248
bool IsValid(enum BlockStatus nUpTo=BLOCK_VALID_TRANSACTIONS) const
Check whether this block index entry is valid up to the passed validity level.
Definition: chain.h:308
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:112
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:170
unsigned int nDataPos
Byte offset within blk?????.dat where this block's data is stored.
Definition: chain.h:176
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block.
Definition: chain.h:191
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:161
Access to the block database (blocks/index/)
Definition: txdb.h:109
bool ReadReindexing(bool &fReindex)
Definition: txdb.cpp:84
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
Definition: txdb.cpp:157
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
Definition: txdb.cpp:73
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Definition: txdb.cpp:153
bool LoadBlockIndexGuts(boost::function< CBlockIndex *(const uint256 &)> insertBlockIndex)
Definition: txdb.cpp:176
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo * > > &fileInfo, int nLastFile, const std::vector< const CBlockIndex * > &blockinfo)
Definition: txdb.cpp:141
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:168
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:89
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:164
Undo information for a CBlock.
Definition: undo.h:67
std::vector< CTxUndo > vtxundo
Definition: undo.h:69
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from.
Definition: streams.h:565
void FindByte(char ch)
Definition: streams.h:698
bool SetPos(uint64_t nPos)
Definition: streams.h:656
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
Definition: streams.h:683
bool eof() const
Definition: streams.h:624
uint64_t GetPos()
Definition: streams.h:651
An in-memory indexed chain of blocks.
Definition: chain.h:432
CBlockLocator GetLocator(const CBlockIndex *pindex=NULL) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
Definition: chain.cpp:52
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or NULL if none.
Definition: chain.h:438
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or NULL if the given index is not found or is the tip.
Definition: chain.h:466
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or NULL if none.
Definition: chain.h:443
int Height() const
Return the maximal height in the chain.
Definition: chain.h:474
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:80
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:40
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:461
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:47
const ChainTxData & TxData() const
Definition: chainparams.h:83
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:63
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:82
const Consensus::Params & GetConsensus(uint32_t nTargetHeight) const
Definition: chainparams.h:59
uint64_t PruneAfterHeight() const
Definition: chainparams.h:74
const CBlock & GenesisBlock() const
Definition: chainparams.h:67
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:175
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:201
Queue for verifications that have to be performed.
Definition: checkqueue.h:31
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
Definition: ui_interface.h:104
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: ui_interface.h:101
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyHeaderTip
Best header has changed.
Definition: ui_interface.h:107
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:77
Pruned version of CTransaction: only retains metadata and unspent transaction outputs.
Definition: coins.h:75
bool Spend(uint32_t nPos)
mark a vout spent
Definition: coins.cpp:35
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
Definition: coins.h:81
void Clear()
Definition: coins.h:103
bool IsPruned() const
check whether the entire CCoins is spent note that only !IsPruned() CCoins can be serialized
Definition: coins.h:229
int nVersion
version of the CTransaction; accesses to this value should probably check for nHeight as well,...
Definition: coins.h:88
bool IsCoinBase() const
Definition: coins.h:152
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
Definition: coins.h:223
void FromTx(const CTransaction &tx, int nHeightIn)
Definition: coins.h:90
void ClearUnspendable()
Definition: coins.h:121
bool fCoinBase
whether transaction is a coinbase
Definition: coins.h:78
int nHeight
at which height this transaction was included in the active block chain
Definition: coins.h:84
A reference to a mutable cache entry.
Definition: coins.h:356
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:55
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:372
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:178
CAmount GetValueIn(const CTransaction &tx) const
Amount of bitcoins coming in to a transaction Note that lightweight clients may not know anything bes...
Definition: coins.cpp:272
const CTxOut & GetOutputFor(const CTxIn &input) const
Definition: coins.cpp:265
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view.
Definition: coins.cpp:284
bool HaveCoinsInCache(const uint256 &txid) const
Check if we have the given tx already loaded in this cache.
Definition: coins.cpp:173
const CCoins * AccessCoins(const uint256 &txid) const
Return a pointer to CCoins in the cache, or NULL if not found.
Definition: coins.cpp:155
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transactions)
Definition: coins.cpp:261
double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
Return priority of tx at height nHeight.
Definition: coins.cpp:298
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:184
bool HaveCoins(const uint256 &txid) const
Just check whether we have data for a given txid.
Definition: coins.cpp:164
void Uncache(const uint256 &txid)
Removes the transaction with the given hash from the cache, if it is not modified.
Definition: coins.cpp:252
CCoinsModifier ModifyCoins(const uint256 &txid)
Return a modifiable reference to a CCoins.
Definition: coins.cpp:99
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:245
CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase)
Return a modifiable reference to a CCoins.
Definition: coins.cpp:134
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:68
Abstract view on the open txout dataset.
Definition: coins.h:307
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:713
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: txmempool.cpp:984
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:93
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: amount.h:38
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: amount.cpp:23
std::string ToString() const
Definition: amount.cpp:45
A hasher class for Bitcoin's 256-bit hash (double SHA-256).
Definition: hash.h:21
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:33
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hash.h:27
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:131
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:40
@ MESSAGE_START_SIZE
Definition: protocol.h:31
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
uint32_t n
Definition: transaction.h:23
bool IsNull() const
Definition: transaction.h:37
uint256 hash
Definition: transaction.h:22
bool IsAuxpow() const
Check if the auxpow flag is set in the version.
Definition: pureheader.h:129
int32_t GetBaseVersion() const
Extract the base version (without modifiers and chain ID).
Definition: pureheader.h:88
uint256 hashPrevBlock
Definition: pureheader.h:30
int64_t GetBlockTime() const
Definition: pureheader.h:73
uint256 GetHash() const
Definition: pureheader.cpp:20
uint256 hashMerkleRoot
Definition: pureheader.h:31
bool IsLegacy() const
Check whether this is a "legacy" block without chain ID.
Definition: pureheader.h:150
uint32_t nBits
Definition: pureheader.h:33
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:443
CScript scriptPubKey
Definition: validation.h:445
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:473
PrecomputedTransactionData * txdata
Definition: validation.h:452
void swap(CScriptCheck &check)
Definition: validation.h:462
bool cacheStore
Definition: validation.h:450
ScriptError error
Definition: validation.h:451
unsigned int nFlags
Definition: validation.h:449
const CTransaction * ptxTo
Definition: validation.h:447
unsigned int nIn
Definition: validation.h:448
CAmount amount
Definition: validation.h:446
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:377
bool IsPayToScriptHash() const
Definition: script.cpp:204
unsigned int GetSigOpCount(bool fAccurate) const
Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs as 20 sigops.
Definition: script.cpp:156
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:308
bool HasWitness() const
Definition: transaction.h:400
const uint32_t nLockTime
Definition: transaction.h:328
const std::vector< CTxOut > vout
Definition: transaction.h:327
const uint256 & GetHash() const
Definition: transaction.h:358
bool IsCoinBase() const
Definition: transaction.h:383
CAmount GetValueOut() const
Definition: transaction.cpp:83
const int32_t nVersion
Definition: transaction.h:325
const std::vector< CTxIn > vin
Definition: transaction.h:326
An input of a transaction.
Definition: transaction.h:63
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG
Definition: transaction.h:77
uint32_t nSequence
Definition: transaction.h:67
static const uint32_t SEQUENCE_LOCKTIME_MASK
Definition: transaction.h:86
static const uint32_t SEQUENCE_FINAL
Only serialized through CTransaction.
Definition: transaction.h:72
CScript scriptSig
Definition: transaction.h:66
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG
Definition: transaction.h:82
COutPoint prevout
Definition: transaction.h:65
static const int SEQUENCE_LOCKTIME_GRANULARITY
Definition: transaction.h:95
Undo information for a CTxIn.
Definition: undo.h:20
CTxOut txout
Definition: undo.h:22
int nVersion
Definition: undo.h:25
bool fCoinBase
Definition: undo.h:23
unsigned int nHeight
Definition: undo.h:24
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:83
double GetPriority(unsigned int currentHeight) const
Fast calculation of lower bound of current priority as update from entry priority.
Definition: txmempool.cpp:54
size_t GetTxSize() const
Definition: txmempool.cpp:75
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:432
void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:926
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Definition: txmempool.cpp:508
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1076
int Expire(int64_t time)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:1014
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:389
std::map< uint256, std::pair< double, CAmount > > mapDeltas
Definition: txmempool.h:516
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:853
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool validFeeEstimate=true)
Definition: txmempool.cpp:1030
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1000
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:839
indirectmap< COutPoint, const CTransaction * > mapNextTx
Definition: txmempool.h:515
void clear()
Definition: txmempool.cpp:640
void TrimToSize(size_t sizelimit, std::vector< uint256 > *pvNoSpendsRemaining=NULL)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:1108
bool HasNoInputsOf(const CTransaction &tx) const
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
Definition: txmempool.cpp:974
void UpdateTransactionsFromBlock(const std::vector< uint256 > &hashesToUpdate)
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:130
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:173
bool exists(uint256 hash) const
Definition: txmempool.h:632
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const
Definition: txmempool.cpp:957
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:494
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:486
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.cpp:646
CCriticalSection cs
Definition: txmempool.h:483
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:1006
indexed_transaction_set mapTx
Definition: txmempool.h:484
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
Definition: txmempool.cpp:540
boost::signals2::signal< void(CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved
Definition: txmempool.h:667
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:485
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight)
Called when a block is connected.
Definition: txmempool.cpp:598
An output of a transaction.
Definition: transaction.h:133
CScript scriptPubKey
Definition: transaction.h:136
CAmount nValue
Definition: transaction.h:135
Undo information for a CTransaction.
Definition: undo.h:52
std::vector< CTxInUndo > vprevout
Definition: undo.h:55
Capture information about block/transaction validation.
Definition: validation.h:22
unsigned int GetRejectCode() const
Definition: validation.h:83
bool DoS(int level, bool ret=false, unsigned int chRejectCodeIn=0, const std::string &strRejectReasonIn="", bool corruptionIn=false, const std::string &strDebugMessageIn="")
Definition: validation.h:36
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
Definition: validation.h:50
bool Error(const std::string &strRejectReasonIn)
Definition: validation.h:55
void SetCorruptionPossible()
Definition: validation.h:80
bool IsValid() const
Definition: validation.h:61
std::string GetRejectReason() const
Definition: validation.h:84
bool IsInvalid() const
Definition: validation.h:64
bool CorruptionPossible() const
Definition: validation.h:77
bool IsError() const
Definition: validation.h:67
std::string GetDebugMessage() const
Definition: validation.h:85
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
std::vector< CTransactionRef > conflictedTxs
Definition: validation.cpp:178
MemPoolConflictRemovalTracker(CTxMemPool &_pool)
Definition: validation.cpp:182
void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason)
Definition: validation.cpp:188
Threshold condition checker that triggers when unknown versionbits are seen on the network.
WarningBitsConditionChecker(int bitIn)
bool Condition(const CBlockIndex *pindex, const Consensus::Params &params) const
int64_t BeginTime(const Consensus::Params &params) const
int64_t EndTime(const Consensus::Params &params) const
int Threshold(const Consensus::Params &params) const
int Period(const Consensus::Params &params) const
256-bit unsigned big integer.
std::string ToString() const
Definition: uint256.cpp:65
bool IsNull() const
Definition: uint256.h:32
unsigned char * begin()
Definition: uint256.h:56
double getdouble() const
iterator find(const K &key)
Definition: indirectmap.h:36
iterator end()
Definition: indirectmap.h:49
iterator begin()
Definition: prevector.h:289
iterator end()
Definition: prevector.h:291
void resize(size_type new_size)
Definition: prevector.h:315
256-bit opaque blob.
Definition: uint256.h:123
@ LOCKTIME_MEDIAN_TIME_PAST
Definition: consensus.h:26
@ LOCKTIME_VERIFY_SEQUENCE
Definition: consensus.h:23
CAmount GetDogecoinMinRelayFee(const CTransaction &tx, unsigned int nBytes, bool fAllowFree)
Definition: dogecoin.cpp:149
bool CheckAuxPowProofOfWork(const CBlockHeader &block, const Consensus::Params &params)
Check proof-of-work of a block header, taking auxpow into account.
Definition: dogecoin.cpp:88
CAmount GetDogecoinBlockSubsidy(int nHeight, const Consensus::Params &consensusParams, uint256 prevHash)
Definition: dogecoin.cpp:125
void * memcpy(void *a, const void *b, size_t c)
bool ShutdownRequested()
Definition: init.cpp:138
void StartShutdown()
Definition: init.cpp:134
size_t CountWitnessSigOps(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
@ SCRIPT_VERIFY_NULLDUMMY
Definition: interpreter.h:51
@ SCRIPT_VERIFY_P2SH
Definition: interpreter.h:36
@ SCRIPT_VERIFY_WITNESS
Definition: interpreter.h:92
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
Definition: interpreter.h:83
@ SCRIPT_VERIFY_DERSIG
Definition: interpreter.h:44
@ SCRIPT_VERIFY_CLEANSTACK
Definition: interpreter.h:78
@ SCRIPT_VERIFY_NONE
Definition: interpreter.h:33
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
Definition: interpreter.h:88
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:158
uint256 BlockWitnessMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:168
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data)
Returns last CBlockIndex* in mapBlockIndex that is a checkpoint.
Definition: checkpoints.cpp:18
bool CheckTxInputs(const CChainParams &params, const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
DeploymentPos
Definition: params.h:16
@ DEPLOYMENT_CSV
Definition: params.h:18
@ DEPLOYMENT_SEGWIT
Definition: params.h:19
@ MAX_VERSION_BITS_DEPLOYMENTS
Definition: params.h:21
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check for standard transaction types.
Definition: policy.cpp:123
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:157
CFeeRate incrementalRelayFee
Definition: policy.cpp:209
bool IsStandardTx(const CTransaction &tx, std::string &reason, const bool witnessEnabled)
Check for standard transaction types.
Definition: policy.cpp:59
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:32
const char * prefix
Definition: rest.cpp:605
@ OP_RETURN
Definition: script.h:82
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:209
@ SER_DISK
Definition: serialize.h:147
@ SER_NETWORK
Definition: serialize.h:146
@ SER_GETHASH
Definition: serialize.h:148
#define FLATDATA(obj)
Definition: serialize.h:347
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:948
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:130
std::vector< uint256 > vHave
Definition: block.h:131
int nFile
Definition: chain.h:74
bool IsNull() const
Definition: chain.h:103
unsigned int nPos
Definition: chain.h:75
std::string ToString() const
Definition: chain.h:105
unsigned int nTxOffset
Definition: txdb.h:47
boost::signals2::signal< void(const CBlockLocator &)> SetBestChain
Notifies listeners of a new active block chain.
boost::signals2::signal< void(const uint256 &)> UpdatedTransaction
Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becomi...
static const int SYNC_TRANSACTION_NOT_IN_BLOCK
A posInBlock value for SyncTransaction calls for tranactions not included in connected blocks such as...
boost::signals2::signal< void(const CBlock &, const CValidationState &)> BlockChecked
Notifies listeners of a block validation result.
boost::signals2::signal< void(const CBlockIndex *, const std::shared_ptr< const CBlock > &)> NewPoWValidBlock
Notifies listeners that a block which builds directly on our current tip has been received and connec...
boost::signals2::signal< void(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip
Notifies listeners of updated block chain tip.
boost::signals2::signal< void(const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction
Notifies listeners of updated transaction data (transaction, and optionally the block it is found in)...
A mutable version of CTransaction.
Definition: transaction.h:413
std::vector< CTxOut > vout
Definition: transaction.h:416
std::vector< CTxIn > vin
Definition: transaction.h:415
double dTxRate
Definition: chainparams.h:36
int64_t nTime
Definition: chainparams.h:34
int64_t nTxCount
Definition: chainparams.h:35
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
std::vector< std::pair< CBlockIndex *, std::shared_ptr< const CBlock > > > blocksConnected
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Definition: params.h:33
Parameters that influence chain consensus.
Definition: params.h:39
int nMajorityWindow
Definition: params.h:45
int BIP65Height
Block height at which BIP65 becomes active.
Definition: params.h:50
uint256 BIP34Hash
Definition: params.h:48
uint32_t nMinerConfirmationWindow
Definition: params.h:59
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:47
int nSubsidyHalvingInterval
Definition: params.h:41
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:60
uint256 hashGenesisBlock
Definition: params.h:40
uint256 nMinimumChainWork
Definition: params.h:75
uint32_t nRuleChangeActivationThreshold
Minimum blocks including miner confirmation of the total of 2016 blocks in a retargeting period,...
Definition: params.h:58
uint32_t nCoinbaseMaturity
Definition: params.h:61
int BIP66Height
Block height at which BIP66 becomes active.
Definition: params.h:52
uint32_t nHeightEffective
Height-aware consensus parameters.
Definition: params.h:84
bool fAllowLegacyBlocks
Definition: params.h:81
CBlockIndex * maxInputBlock
Definition: txmempool.h:58
int height
Definition: txmempool.h:53
int64_t time
Definition: txmempool.h:54
#define LOCK2(cs1, cs2)
Definition: sync.h:178
#define LOCK(cs)
Definition: sync.h:177
#define AssertLockHeld(cs)
Definition: sync.h:86
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
Definition: sync.h:105
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
#define strprintf
Definition: tinyformat.h:1047
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:459
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:341
@ REPLACED
Removed for conflict with in-block transaction.
@ CONFLICT
Removed for block.
@ REORG
Removed in size limiting.
bool AllowFree(double dPriority)
Definition: txmempool.h:38
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
#define expect(bit)
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:395
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:411
void RenameThread(const char *name)
Definition: util.cpp:781
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: util.cpp:687
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:513
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:652
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
Definition: util.cpp:605
void FileCommit(FILE *file)
Definition: util.cpp:635
#define LogPrint(category,...)
Definition: util.h:76
bool error(const char *fmt, const Args &... args)
Definition: util.h:87
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
Definition: util.h:62
#define LogPrintf(...)
Definition: util.h:82
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
#define PAIRTYPE(t1, t2)
This is needed because the foreach macro can't get over the comma in pair<t1, t2>
int64_t GetTimeMicros()
Definition: utiltime.cpp:41
int64_t GetTimeMillis()
Definition: utiltime.cpp:33
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units.
Definition: utiltime.cpp:19
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:80
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:224
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:84
void FlushStateToDisk()
Flush all state, indexes and buffers to disk.
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
uint64_t nPruneTarget
Number of MiB of block files that we're trying to stay below.
Definition: validation.cpp:79
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:223
CCriticalSection cs_main
Global state.
Definition: validation.cpp:61
bool fCheckBlockIndex
Definition: validation.cpp:76
bool WriteBlockToDisk(const CBlock &block, CDiskBlockPos &pos, const CMessageHeader::MessageStartChars &messageStart)
Functions for disk access for blocks.
int nScriptCheckThreads
Definition: validation.cpp:68
const std::string strMessageMagic
Definition: validation.cpp:101
bool fEnableReplacement
Definition: validation.cpp:82
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain.
Definition: validation.cpp:365
bool fAlerts
Definition: validation.cpp:80
bool RewindBlockIndex(const CChainParams &params)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
std::atomic_bool fImporting(false)
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &headers, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex)
Process incoming block headers.
VersionBitsCache versionbitscache
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, const CBlockIndex *pindexPrev, int64_t nAdjustedTime)
Context-dependent validity checks.
bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state, bool fCheckPOW)
Functions for validating blocks and updating the block tree.
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:72
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
CBlockIndex * AddToBlockIndex(const CBlockHeader &block)
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
bool CheckBlock(const CBlock &block, CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot)
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
bool ConnectBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, const CChainParams &chainparams, bool fJustCheck)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:86
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.
void DumpMempool(void)
Dump the mempool to disk.
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight)
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:99
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network)
bool fTxIndex
Definition: validation.cpp:71
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block,...
void LimitMempoolSize(CTxMemPool &pool, size_t limit, unsigned long age)
Definition: validation.cpp:555
class CMainCleanup instance_of_cmaincleanup
void CheckForkWarningConditions()
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
CAmount maxTxFee
Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendra...
Definition: validation.cpp:87
bool ReceivedBlockTransactions(const CBlock &block, CValidationState &state, CBlockIndex *pindexNew, const CDiskBlockPos &pos)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
bool AcceptToMemoryPoolWorker(CTxMemPool &pool, CValidationState &state, const CTransactionRef &ptx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount &nAbsurdFee, std::vector< uint256 > &vHashTxnToUncache)
Definition: validation.cpp:587
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
bool CheckFinalTx(const CTransaction &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: validation.cpp:250
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
bool AcceptToMemoryPoolWithTime(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
(try to) add transaction to memory pool with a specified acceptance time
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:567
BlockMap mapBlockIndex
Definition: validation.cpp:63
void ThreadScriptCheck()
Run an instance of the script checking thread.
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
bool fReindex
Definition: validation.cpp:70
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
Definition: validation.cpp:483
CBlockIndex * pindexBestForkBase
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
bool InitBlockIndex(const CChainParams &chainparams)
Initialize a new block tree database + block data on disk.
FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
bool ContextualCheckBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindexPrev)
bool fPruneMode
True if we're running in -prune mode.
Definition: validation.cpp:73
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks)
Check whether all inputs of this transaction are valid (no double spends, scripts & sigs,...
CBlockIndex * pindexBestForkTip
size_t nCoinCacheUsage
Definition: validation.cpp:78
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams, bool fCheckPOW)
bool DisconnectBlock(const CBlock &block, CValidationState &state, const CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk.
bool fIsBareMultisigStd
Definition: validation.cpp:74
CWaitableCriticalSection csBestBlock
Definition: validation.cpp:66
int VersionBitsTipStateSinceHeight(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
void UnloadBlockIndex()
Unload database information.
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
bool ApplyTxInUndo(const CTxInUndo &undo, CCoinsViewCache &view, const COutPoint &out)
Apply the undo operation of a CTxInUndo to the given chain state.
bool fCheckpointsEnabled
Definition: validation.cpp:77
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:65
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs)
Transaction validation functions.
Definition: validation.cpp:506
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: validation.cpp:454
bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.cpp:383
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: validation.cpp:468
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:64
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: validation.cpp:237
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
FlushStateMode
Definition: validation.cpp:226
@ FLUSH_STATE_ALWAYS
Definition: validation.cpp:230
@ FLUSH_STATE_NONE
Definition: validation.cpp:227
@ FLUSH_STATE_PERIODIC
Definition: validation.cpp:229
@ FLUSH_STATE_IF_NEEDED
Definition: validation.cpp:228
CConditionVariable cvBlockChange
Definition: validation.cpp:67
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
bool LoadMempool(void)
Load the mempool from disk.
bool fRequireStandard
Definition: validation.cpp:75
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly)
Open an undo file (rev?????.dat)
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block.
Definition: validation.cpp:360
bool ReadBlockHeaderFromDisk(CBlockHeader &block, const CBlockIndex *pindex, const Consensus::Params &consensusParams, bool fCheckPOW)
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:205
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:81
void PruneAndFlush()
Prune block files and flush state to disk.
boost::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:160
CMainSignals & GetMainSignals()
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
int VersionBitsStateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
Definition: versionbits.h:31
ThresholdState
Definition: versionbits.h:20
@ THRESHOLD_LOCKED_IN
Definition: versionbits.h:23
@ THRESHOLD_ACTIVE
Definition: versionbits.h:24
@ THRESHOLD_STARTED
Definition: versionbits.h:22
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:39
void SetfLargeWorkForkFound(bool flag)
Definition: warnings.cpp:27
bool GetfLargeWorkForkFound()
Definition: warnings.cpp:33
void SetMiscWarning(const std::string &strWarning)
Definition: warnings.cpp:21