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