Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

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-2020 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 <arith_uint256.h>
10 #include <blockencodings.h>
11 #include <chain.h>
12 #include <chainparams.h>
13 #include <checkpoints.h>
14 #include <checkqueue.h>
15 #include <consensus/consensus.h>
16 #include <consensus/merkle.h>
17 #include <consensus/tx_verify.h>
18 #include <consensus/validation.h>
19 #include <cuckoocache.h>
20 #include <hash.h>
21 #include <init.h>
22 #include <policy/fees.h>
23 #include <policy/policy.h>
24 #include <pow.h>
25 #include <primitives/block.h>
26 #include <primitives/transaction.h>
27 #include <reverse_iterator.h>
28 #include <script/script.h>
29 #include <script/sigcache.h>
30 #include <script/standard.h>
31 #include <timedata.h>
32 #include <tinyformat.h>
33 #include <txdb.h>
34 #include <txmempool.h>
35 #include <ui_interface.h>
36 #include <undo.h>
37 #include <util.h>
38 #include <spork.h>
39 #include <utilmoneystr.h>
40 #include <utilstrencodings.h>
41 #include <validationinterface.h>
42 #include <warnings.h>
43 
45 
46 #include <evo/specialtx.h>
47 #include <evo/providertx.h>
48 #include <evo/deterministicmns.h>
49 #include <evo/cbtx.h>
50 
53 
54 #include <future>
55 #include <sstream>
56 
57 #include <boost/algorithm/string/replace.hpp>
58 #include <boost/algorithm/string/join.hpp>
59 #include <boost/thread.hpp>
60 
61 #if defined(NDEBUG)
62 # error "Dash Core cannot be compiled without assertions."
63 #endif
64 
65 #define MICRO 0.000001
66 #define MILLI 0.001
67 
71 namespace {
72  struct CBlockIndexWorkComparator
73  {
74  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
75  // First sort by most total work, ...
76  if (pa->nChainWork > pb->nChainWork) return false;
77  if (pa->nChainWork < pb->nChainWork) return true;
78 
79  // ... then by earliest time received, ...
80  if (pa->nSequenceId < pb->nSequenceId) return false;
81  if (pa->nSequenceId > pb->nSequenceId) return true;
82 
83  // Use pointer address as tie breaker (should only happen with blocks
84  // loaded from disk, as those all have id 0).
85  if (pa < pb) return false;
86  if (pa > pb) return true;
87 
88  // Identical blocks.
89  return false;
90  }
91  };
92 } // anon namespace
93 
95 {
96  DISCONNECT_OK, // All good.
97  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
98  DISCONNECT_FAILED // Something else went wrong.
99 };
100 
101 class ConnectTrace;
102 
117 class CChainState {
118 private:
124  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
125 
132  int32_t nBlockSequenceId = 1;
137 
156  std::set<CBlockIndex*> g_failed_blocks;
157 
158 public:
162  std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
164 
165  bool LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree);
166 
167  bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock);
168 
169  bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex);
170  bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock);
171 
172  // Block (dis)connection on a given view:
173  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
174  bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
175  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false);
176 
177  // Block disconnection on our pcoinsTip:
178  bool DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool);
179 
180  // Manual block validity manipulation:
181  bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex);
182  bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex);
183  bool ResetBlockFailureFlags(CBlockIndex *pindex);
184 
185  bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
186  bool RewindBlockIndex(const CChainParams& params);
187  bool LoadGenesisBlock(const CChainParams& chainparams);
188  bool AddGenesisBlock(const CChainParams& chainparams, const CBlock& block, CValidationState& state);
189 
191 
192  void UnloadBlockIndex();
193 
194 private:
195  bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace);
196  bool ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool);
197 
200  CBlockIndex * InsertBlockIndex(const uint256& hash);
201  void CheckBlockIndex(const Consensus::Params& consensusParams);
202 
203  void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state);
205  bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos);
206 
207 
208  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params);
209 } g_chainstate;
210 
211 
212 
214 
223 std::atomic_bool fImporting(false);
224 std::atomic_bool fReindex(false);
225 bool fTxIndex = true;
226 bool fAddressIndex = false;
227 bool fTimestampIndex = false;
228 bool fSpentIndex = false;
229 bool fHavePruned = false;
230 bool fPruneMode = false;
232 bool fRequireStandard = true;
234 bool fCheckBlockIndex = false;
236 size_t nCoinCacheUsage = 5000 * 300;
237 uint64_t nPruneTarget = 0;
239 
240 std::atomic<bool> fDIP0001ActiveAtTip{false};
241 std::atomic<bool> fDIP0003ActiveAtTip{false};
242 
245 
248 
251 
252 static void CheckBlockIndex(const Consensus::Params& consensusParams);
253 
256 
257 const std::string strMessageMagic = "DarkCoin Signed Message:\n";
258 
259 // Internal stuff
260 namespace {
261  CBlockIndex *&pindexBestInvalid = g_chainstate.pindexBestInvalid;
262 
266  std::multimap<CBlockIndex*, CBlockIndex*>& mapBlocksUnlinked = g_chainstate.mapBlocksUnlinked;
267 
268  CCriticalSection cs_LastBlockFile;
269  std::vector<CBlockFileInfo> vinfoBlockFile;
270  int nLastBlockFile = 0;
275  bool fCheckForPruning = false;
276 
278  std::set<CBlockIndex*> setDirtyBlockIndex;
279 
281  std::set<int> setDirtyFileInfo;
282 } // anon namespace
283 
285 {
286  // Find the first block the caller has in the main chain
287  for (const uint256& hash : locator.vHave) {
288  BlockMap::iterator mi = mapBlockIndex.find(hash);
289  if (mi != mapBlockIndex.end())
290  {
291  CBlockIndex* pindex = (*mi).second;
292  if (chain.Contains(pindex))
293  return pindex;
294  }
295  }
296  return chain.Genesis();
297 }
298 
299 std::unique_ptr<CCoinsViewDB> pcoinsdbview;
300 std::unique_ptr<CCoinsViewCache> pcoinsTip;
301 std::unique_ptr<CBlockTreeDB> pblocktree;
302 
308 };
309 
310 // See definition for documentation
311 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
312 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
313 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
314 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
315 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
316 
317 bool CheckFinalTx(const CTransaction &tx, int flags)
318 {
320 
321  // By convention a negative value for flags indicates that the
322  // current network-enforced consensus rules should be used. In
323  // a future soft-fork scenario that would mean checking which
324  // rules would be enforced for the next block and setting the
325  // appropriate flags. At the present time no soft-forks are
326  // scheduled, so no flags are set.
327  flags = std::max(flags, 0);
328 
329  // CheckFinalTx() uses chainActive.Height()+1 to evaluate
330  // nLockTime because when IsFinalTx() is called within
331  // CBlock::AcceptBlock(), the height of the block *being*
332  // evaluated is what is used. Thus if we want to know if a
333  // transaction can be part of the *next* block, we need to call
334  // IsFinalTx() with one more than chainActive.Height().
335  const int nBlockHeight = chainActive.Height() + 1;
336 
337  // BIP113 requires that time-locked transactions have nLockTime set to
338  // less than the median time of the previous block they're contained in.
339  // When the next block is created its previous block will be the current
340  // chain tip, so we use that to calculate the median time passed to
341  // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
342  const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
344  : GetAdjustedTime();
345 
346  return IsFinalTx(tx, nBlockHeight, nBlockTime);
347 }
348 
350 {
352  assert(lp);
353  // If there are relative lock times then the maxInputBlock will be set
354  // If there are no relative lock times, the LockPoints don't depend on the chain
355  if (lp->maxInputBlock) {
356  // Check whether chainActive is an extension of the block at which the LockPoints
357  // calculation was valid. If not LockPoints are no longer valid
358  if (!chainActive.Contains(lp->maxInputBlock)) {
359  return false;
360  }
361  }
362 
363  // LockPoints still valid
364  return true;
365 }
366 
367 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
368 {
371 
372  CBlockIndex* tip = chainActive.Tip();
373  assert(tip != nullptr);
374 
375  CBlockIndex index;
376  index.pprev = tip;
377  // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
378  // height based locks because when SequenceLocks() is called within
379  // ConnectBlock(), the height of the block *being*
380  // evaluated is what is used.
381  // Thus if we want to know if a transaction can be part of the
382  // *next* block, we need to use one more than chainActive.Height()
383  index.nHeight = tip->nHeight + 1;
384 
385  std::pair<int, int64_t> lockPair;
386  if (useExistingLockPoints) {
387  assert(lp);
388  lockPair.first = lp->height;
389  lockPair.second = lp->time;
390  }
391  else {
392  // pcoinsTip contains the UTXO set for chainActive.Tip()
393  CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool);
394  std::vector<int> prevheights;
395  prevheights.resize(tx.vin.size());
396  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
397  const CTxIn& txin = tx.vin[txinIndex];
398  Coin coin;
399  if (!viewMemPool.GetCoin(txin.prevout, coin)) {
400  return error("%s: Missing input", __func__);
401  }
402  if (coin.nHeight == MEMPOOL_HEIGHT) {
403  // Assume all mempool transaction confirm in the next block
404  prevheights[txinIndex] = tip->nHeight + 1;
405  } else {
406  prevheights[txinIndex] = coin.nHeight;
407  }
408  }
409  lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
410  if (lp) {
411  lp->height = lockPair.first;
412  lp->time = lockPair.second;
413  // Also store the hash of the block with the highest height of
414  // all the blocks which have sequence locked prevouts.
415  // This hash needs to still be on the chain
416  // for these LockPoint calculations to be valid
417  // Note: It is impossible to correctly calculate a maxInputBlock
418  // if any of the sequence locked inputs depend on unconfirmed txs,
419  // except in the special case where the relative lock time/height
420  // is 0, which is equivalent to no sequence lock. Since we assume
421  // input height of tip+1 for mempool txs and test the resulting
422  // lockPair from CalculateSequenceLocks against tip+1. We know
423  // EvaluateSequenceLocks will fail if there was a non-zero sequence
424  // lock on a mempool input, so we can use the return value of
425  // CheckSequenceLocks to indicate the LockPoints validity
426  int maxInputHeight = 0;
427  for (int height : prevheights) {
428  // Can ignore mempool inputs since we'll fail if they had non-zero locks
429  if (height != tip->nHeight+1) {
430  maxInputHeight = std::max(maxInputHeight, height);
431  }
432  }
433  lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
434  }
435  }
436  return EvaluateSequenceLocks(index, lockPair);
437 }
438 
439 bool GetUTXOCoin(const COutPoint& outpoint, Coin& coin)
440 {
441  LOCK(cs_main);
442  if (!pcoinsTip->GetCoin(outpoint, coin))
443  return false;
444  if (coin.IsSpent())
445  return false;
446  return true;
447 }
448 
449 int GetUTXOHeight(const COutPoint& outpoint)
450 {
451  // -1 means UTXO is yet unknown or already spent
452  Coin coin;
453  return GetUTXOCoin(outpoint, coin) ? coin.nHeight : -1;
454 }
455 
456 int GetUTXOConfirmations(const COutPoint& outpoint)
457 {
458  // -1 means UTXO is yet unknown or already spent
459  LOCK(cs_main);
460  int nPrevoutHeight = GetUTXOHeight(outpoint);
461  return (nPrevoutHeight > -1 && chainActive.Tip()) ? chainActive.Height() - nPrevoutHeight + 1 : -1;
462 }
463 
464 
465 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
466 {
467  int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
468  bool fDIP0001Active_context = nHeight >= consensusParams.DIP0001Height;
469  bool fDIP0003Active_context = nHeight >= consensusParams.DIP0003Height;
470 
471  if (fDIP0003Active_context) {
472  // check version 3 transaction types
473  if (tx.nVersion >= 3) {
474  if (tx.nType != TRANSACTION_NORMAL &&
479  tx.nType != TRANSACTION_COINBASE &&
481  return state.DoS(100, false, REJECT_INVALID, "bad-txns-type");
482  }
483  if (tx.IsCoinBase() && tx.nType != TRANSACTION_COINBASE)
484  return state.DoS(100, false, REJECT_INVALID, "bad-txns-cb-type");
485  } else if (tx.nType != TRANSACTION_NORMAL) {
486  return state.DoS(100, false, REJECT_INVALID, "bad-txns-type");
487  }
488  }
489 
490  // Size limits
491  if (fDIP0001Active_context && ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_STANDARD_TX_SIZE)
492  return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
493 
494  return true;
495 }
496 
497 // Returns the script flags which should be checked for a given block
498 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
499 
500 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
501  int expired = pool.Expire(GetTime() - age);
502  if (expired != 0) {
503  LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
504  }
505 
506  std::vector<COutPoint> vNoSpendsRemaining;
507  pool.TrimToSize(limit, &vNoSpendsRemaining);
508  for (const COutPoint& removed : vNoSpendsRemaining)
509  pcoinsTip->Uncache(removed);
510 }
511 
513 std::string FormatStateMessage(const CValidationState &state)
514 {
515  return strprintf("%s%s (code %i)",
516  state.GetRejectReason(),
517  state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
518  state.GetRejectCode());
519 }
520 
522 {
525  return false;
527  return false;
529  return false;
530  return true;
531 }
532 
533 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
534  * disconnected block transactions from the mempool, and also removing any
535  * other transactions from the mempool that are no longer valid given the new
536  * tip/height.
537  *
538  * Note: we assume that disconnectpool only contains transactions that are NOT
539  * confirmed in the current chain nor already in the mempool (otherwise,
540  * in-mempool descendants of such transactions would be removed).
541  *
542  * Passing fAddToMempool=false will skip trying to add the transactions back,
543  * and instead just erase from the mempool as needed.
544  */
545 
546 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
547 {
549  std::vector<uint256> vHashUpdate;
550  // disconnectpool's insertion_order index sorts the entries from
551  // oldest to newest, but the oldest entry will be the last tx from the
552  // latest mined block that was disconnected.
553  // Iterate disconnectpool in reverse, so that we add transactions
554  // back to the mempool starting with the earliest transaction that had
555  // been previously seen in a block.
556  auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
557  while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
558  // ignore validation errors in resurrected transactions
559  CValidationState stateDummy;
560  if (!fAddToMempool || (*it)->IsCoinBase() ||
561  !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
562  true /* bypass_limits */, 0 /* nAbsurdFee */)) {
563  // If the transaction doesn't make it in to the mempool, remove any
564  // transactions that depend on it (which would now be orphans).
566  } else if (mempool.exists((*it)->GetHash())) {
567  vHashUpdate.push_back((*it)->GetHash());
568  }
569  ++it;
570  }
571  disconnectpool.queuedTx.clear();
572  // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
573  // no in-mempool children, which is generally not true when adding
574  // previously-confirmed transactions back to the mempool.
575  // UpdateTransactionsFromBlock finds descendants of any transactions in
576  // the disconnectpool that were added back and cleans up the mempool state.
578 
579  // We also need to remove any now-immature transactions
581  // Re-limit mempool size, in case we added any transactions
582  LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
583 }
584 
585 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
586 // were somehow broken and returning the wrong scriptPubKeys
588  unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
590 
591  // pool.cs should be locked already, but go ahead and re-take the lock here
592  // to enforce that mempool doesn't change between when we check the view
593  // and when we actually call through to CheckInputs
594  LOCK(pool.cs);
595 
596  assert(!tx.IsCoinBase());
597  for (const CTxIn& txin : tx.vin) {
598  const Coin& coin = view.AccessCoin(txin.prevout);
599 
600  // At this point we haven't actually checked if the coins are all
601  // available (or shouldn't assume we have, since CheckInputs does).
602  // So we just return failure if the inputs are not available here,
603  // and then only have to check equivalence for available inputs.
604  if (coin.IsSpent()) return false;
605 
606  const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
607  if (txFrom) {
608  assert(txFrom->GetHash() == txin.prevout.hash);
609  assert(txFrom->vout.size() > txin.prevout.n);
610  assert(txFrom->vout[txin.prevout.n] == coin.out);
611  } else {
612  const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
613  assert(!coinFromDisk.IsSpent());
614  assert(coinFromDisk.out == coin.out);
615  }
616  }
617 
618  return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
619 }
620 
621 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
622  bool* pfMissingInputs, int64_t nAcceptTime, bool bypass_limits,
623  const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache, bool fDryRun)
624 {
625  const CTransaction& tx = *ptx;
626  const uint256 hash = tx.GetHash();
628  LOCK(pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
629  if (pfMissingInputs) {
630  *pfMissingInputs = false;
631  }
632 
633  if (!CheckTransaction(tx, state))
634  return false; // state filled in by CheckTransaction
635 
636  if (!ContextualCheckTransaction(tx, state, chainparams.GetConsensus(), chainActive.Tip()))
637  return error("%s: ContextualCheckTransaction: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
638 
639  if (tx.nVersion == 3 && tx.nType == TRANSACTION_QUORUM_COMMITMENT) {
640  // quorum commitment is not allowed outside of blocks
641  return state.DoS(100, false, REJECT_INVALID, "qc-not-allowed");
642  }
643 
644  // Coinbase is only valid in a block, not as a loose transaction
645  if (tx.IsCoinBase())
646  return state.DoS(100, false, REJECT_INVALID, "coinbase");
647 
648  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
649  std::string reason;
650  if (fRequireStandard && !IsStandardTx(tx, reason))
651  return state.DoS(0, false, REJECT_NONSTANDARD, reason);
652 
653  // Only accept nLockTime-using transactions that can be mined in the next
654  // block; we don't want our mempool filled up with transactions that can't
655  // be mined yet.
657  return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
658 
659  // is it already in the memory pool?
660  if (pool.exists(hash)) {
661  return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
662  }
663 
665  if (conflictLock) {
666  CTransactionRef txConflict;
667  uint256 hashBlock;
668  if (GetTransaction(conflictLock->txid, txConflict, chainparams.GetConsensus(), hashBlock)) {
670  }
671  return state.DoS(10, error("AcceptToMemoryPool : Transaction %s conflicts with locked TX %s",
672  hash.ToString(), conflictLock->txid.ToString()),
673  REJECT_INVALID, "tx-txlock-conflict");
674  }
675 
676  // Check for conflicts with in-memory transactions
677  for (const CTxIn &txin : tx.vin)
678  {
679  auto itConflicting = pool.mapNextTx.find(txin.prevout);
680  if (itConflicting != pool.mapNextTx.end())
681  {
682  const CTransaction *ptxConflicting = itConflicting->second;
683 
684  // Transaction conflicts with mempool and RBF doesn't exist in Dash
685  return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
686  }
687  }
688 
689  {
690  CCoinsView dummy;
691  CCoinsViewCache view(&dummy);
692 
693  LockPoints lp;
694  CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
695  view.SetBackend(viewMemPool);
696 
697  // do all inputs exist?
698  for (const CTxIn txin : tx.vin) {
699  if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
700  coins_to_uncache.push_back(txin.prevout);
701  }
702  if (!view.HaveCoin(txin.prevout)) {
703  // Are inputs missing because we already have the tx?
704  for (size_t out = 0; out < tx.vout.size(); out++) {
705  // Optimistically just do efficient check of cache for outputs
706  if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
707  return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
708  }
709  }
710  // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
711  if (pfMissingInputs) {
712  *pfMissingInputs = true;
713  }
714  return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
715  }
716  }
717 
718  // Bring the best block into scope
719  view.GetBestBlock();
720 
721  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
722  view.SetBackend(dummy);
723 
724  // Only accept BIP68 sequence locked transactions that can be mined in the next
725  // block; we don't want our mempool filled up with transactions that can't
726  // be mined yet.
727  // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
728  // CoinsViewCache instead of create its own
730  return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
731 
732  CAmount nFees = 0;
733  if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
734  return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
735  }
736 
737  // Check for non-standard pay-to-script-hash in inputs
738  if (fRequireStandard && !AreInputsStandard(tx, view))
739  return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
740 
741  unsigned int nSigOps = GetTransactionSigOpCount(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
742 
743  // nModifiedFees includes any fee deltas from PrioritiseTransaction
744  CAmount nModifiedFees = nFees;
745  pool.ApplyDelta(hash, nModifiedFees);
746 
747  // Keep track of transactions that spend a coinbase, which we re-scan
748  // during reorgs to ensure COINBASE_MATURITY is still met.
749  bool fSpendsCoinbase = false;
750  for (const CTxIn &txin : tx.vin) {
751  const Coin &coin = view.AccessCoin(txin.prevout);
752  if (coin.IsCoinBase()) {
753  fSpendsCoinbase = true;
754  break;
755  }
756  }
757 
758  CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
759  fSpendsCoinbase, nSigOps, lp);
760  unsigned int nSize = entry.GetTxSize();
761 
762  // Check that the transaction doesn't have an excessive number of
763  // sigops, making it impossible to mine. Since the coinbase transaction
764  // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
765  // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
766  // merely non-standard transaction.
767  if ((nSigOps > MAX_STANDARD_TX_SIGOPS) || (nBytesPerSigOp && nSigOps > nSize / nBytesPerSigOp))
768  return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
769  strprintf("%d", nSigOps));
770 
771  CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
772  if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
773  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
774  }
775 
776  // No transactions are allowed below minRelayTxFee except from disconnected blocks
777  if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
778  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
779  }
780 
781  if (nAbsurdFee && nFees > nAbsurdFee)
782  return state.Invalid(false,
783  REJECT_HIGHFEE, "absurdly-high-fee",
784  strprintf("%d > %d", nFees, nAbsurdFee));
785 
786  // Calculate in-mempool ancestors, up to a limit.
787  CTxMemPool::setEntries setAncestors;
788  size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
789  size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
790  size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
791  size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
792  std::string errString;
793  if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
794  return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
795  }
796 
797  // check special TXs after all the other checks. If we'd do this before the other checks, we might end up
798  // DoS scoring a node for non-critical errors, e.g. duplicate keys because a TX is received that was already
799  // mined
800  if (!CheckSpecialTx(tx, chainActive.Tip(), state))
801  return false;
802 
803  if (pool.existsProviderTxConflict(tx)) {
804  return state.DoS(0, false, REJECT_DUPLICATE, "protx-dup");
805  }
806 
807  // If we aren't going to actually accept it but just were verifying it, we are fine already
808  if(fDryRun) return true;
809 
810  constexpr unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
811 
812  // Check against previous transactions
813  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
814  PrecomputedTransactionData txdata(tx);
815  if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, false, txdata))
816  return false; // state filled in by CheckInputs
817 
818  // Check again against the current block tip's script verification
819  // flags to cache our script execution flags. This is, of course,
820  // useless if the next block has different script flags from the
821  // previous one, but because the cache tracks script flags for us it
822  // will auto-invalidate and we'll just have a few blocks of extra
823  // misses on soft-fork activation.
824  //
825  // This is also useful in case of bugs in the standard flags that cause
826  // transactions to pass as valid when they're actually invalid. For
827  // instance the STRICTENC flag was incorrectly allowing certain
828  // CHECKSIG NOT scripts to pass, even though they were invalid.
829  //
830  // There is a similar check in CreateNewBlock() to prevent creating
831  // invalid blocks (using TestBlockValidity), however allowing such
832  // transactions into the mempool can be exploited as a DoS attack.
833  unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), chainparams.GetConsensus());
834  if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) {
835  return error("%s: BUG! PLEASE REPORT THIS! CheckInputs failed against latest-block but not STANDARD flags %s, %s",
836  __func__, hash.ToString(), FormatStateMessage(state));
837  }
838 
839  // This transaction should only count for fee estimation if:
840  // - it's not being readded during a reorg which bypasses typical mempool fee limits
841  // - the node is not behind
842  // - the transaction is not dependent on any other transactions in the mempool
843  // - the transaction is not a zero fee transaction
844  bool validForFeeEstimation = (nFees !=0) && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
845 
846  // Store transaction in memory
847  pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
848 
849  // Add memory address index
850  if (fAddressIndex) {
851  pool.addAddressIndex(entry, view);
852  }
853 
854  // Add memory spent index
855  if (fSpentIndex) {
856  pool.addSpentIndex(entry, view);
857  }
858 
859  if (!bypass_limits) {
860  LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
861  if (!pool.exists(hash))
862  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
863  }
864  }
865 
866  if(!fDryRun)
867  GetMainSignals().TransactionAddedToMempool(ptx, nAcceptTime);
868 
869  return true;
870 }
871 
873 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
874  bool* pfMissingInputs, int64_t nAcceptTime, bool bypass_limits,
875  const CAmount nAbsurdFee, bool fDryRun)
876 {
877  std::vector<COutPoint> coins_to_uncache;
878  bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, bypass_limits, nAbsurdFee, coins_to_uncache, fDryRun);
879  if (!res || fDryRun) {
880  if(!res) LogPrint(BCLog::MEMPOOL, "%s: %s %s (%s)\n", __func__, tx->GetHash().ToString(), state.GetRejectReason(), state.GetDebugMessage());
881  for (const COutPoint& hashTx : coins_to_uncache)
882  pcoinsTip->Uncache(hashTx);
883  }
884  // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
885  CValidationState stateDummy;
886  FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
887  return res;
888 }
889 
891  bool* pfMissingInputs, bool bypass_limits, const CAmount nAbsurdFee, bool fDryRun)
892 {
893  const CChainParams& chainparams = Params();
894  return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), bypass_limits, nAbsurdFee, fDryRun);
895 }
896 
897 bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector<uint256> &hashes)
898 {
899  if (!fTimestampIndex)
900  return error("Timestamp index not enabled");
901 
902  if (!pblocktree->ReadTimestampIndex(high, low, hashes))
903  return error("Unable to get hashes for timestamps");
904 
905  return true;
906 }
907 
909 {
910  if (!fSpentIndex)
911  return false;
912 
913  if (mempool.getSpentIndex(key, value))
914  return true;
915 
916  if (!pblocktree->ReadSpentIndex(key, value))
917  return false;
918 
919  return true;
920 }
921 
922 bool GetAddressIndex(uint160 addressHash, int type,
923  std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex, int start, int end)
924 {
925  if (!fAddressIndex)
926  return error("address index not enabled");
927 
928  if (!pblocktree->ReadAddressIndex(addressHash, type, addressIndex, start, end))
929  return error("unable to get txids for address");
930 
931  return true;
932 }
933 
934 bool GetAddressUnspent(uint160 addressHash, int type,
935  std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs)
936 {
937  if (!fAddressIndex)
938  return error("address index not enabled");
939 
940  if (!pblocktree->ReadAddressUnspentIndex(addressHash, type, unspentOutputs))
941  return error("unable to get txids for address");
942 
943  return true;
944 }
945 
950 bool GetTransaction(const uint256& hash, CTransactionRef& txOut, const Consensus::Params& consensusParams, uint256& hashBlock, bool fAllowSlow, CBlockIndex* blockIndex)
951 {
952  CBlockIndex* pindexSlow = blockIndex;
953 
954  LOCK(cs_main);
955 
956  if (!blockIndex) {
957  CTransactionRef ptx = mempool.get(hash);
958  if (ptx) {
959  txOut = ptx;
960  return true;
961  }
962 
963  if (fTxIndex) {
964  CDiskTxPos postx;
965  if (pblocktree->ReadTxIndex(hash, postx)) {
966  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
967  if (file.IsNull())
968  return error("%s: OpenBlockFile failed", __func__);
969  CBlockHeader header;
970  try {
971  file >> header;
972  fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
973  file >> txOut;
974  } catch (const std::exception& e) {
975  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
976  }
977  hashBlock = header.GetHash();
978  if (txOut->GetHash() != hash)
979  return error("%s: txid mismatch", __func__);
980  if (!mapBlockIndex.count(hashBlock)) {
981  return error("%s: hashBlock %s not in mapBlockIndex", __func__, hashBlock.ToString());
982  }
983  return true;
984  }
985 
986  // transaction not found in index, nothing more can be done
987  return false;
988  }
989 
990  if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
991  const Coin& coin = AccessByTxid(*pcoinsTip, hash);
992  if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
993  }
994  }
995 
996  if (pindexSlow) {
997  CBlock block;
998  if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
999  for (const auto& tx : block.vtx) {
1000  if (tx->GetHash() == hash) {
1001  txOut = tx;
1002  hashBlock = pindexSlow->GetBlockHash();
1003  return true;
1004  }
1005  }
1006  }
1007  }
1008 
1009  return false;
1010 }
1011 
1012 
1013 
1014 
1015 
1016 
1018 //
1019 // CBlock and CBlockIndex
1020 //
1021 
1022 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1023 {
1024  // Open history file to append
1026  if (fileout.IsNull())
1027  return error("WriteBlockToDisk: OpenBlockFile failed");
1028 
1029  // Write index header
1030  unsigned int nSize = GetSerializeSize(fileout, block);
1031  fileout << FLATDATA(messageStart) << nSize;
1032 
1033  // Write block
1034  long fileOutPos = ftell(fileout.Get());
1035  if (fileOutPos < 0)
1036  return error("WriteBlockToDisk: ftell failed");
1037  pos.nPos = (unsigned int)fileOutPos;
1038  fileout << block;
1039 
1040  return true;
1041 }
1042 
1043 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1044 {
1045  block.SetNull();
1046 
1047  // Open history file to read
1048  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1049  if (filein.IsNull())
1050  return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1051 
1052  // Read block
1053  try {
1054  filein >> block;
1055  }
1056  catch (const std::exception& e) {
1057  return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1058  }
1059 
1060  // Check the header
1061  if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1062  return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1063 
1064  return true;
1065 }
1066 
1067 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1068 {
1069  CDiskBlockPos blockPos;
1070  {
1071  LOCK(cs_main);
1072  blockPos = pindex->GetBlockPos();
1073  }
1074 
1075  if (!ReadBlockFromDisk(block, blockPos, consensusParams))
1076  return false;
1077  if (block.GetHash() != pindex->GetBlockHash())
1078  return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1079  pindex->ToString(), pindex->GetBlockPos().ToString());
1080  return true;
1081 }
1082 
1083 double ConvertBitsToDouble(unsigned int nBits)
1084 {
1085  int nShift = (nBits >> 24) & 0xff;
1086 
1087  double dDiff = (double)0x0000ffff / (double)(nBits & 0x00ffffff);
1088 
1089  while (nShift < 29)
1090  {
1091  dDiff *= 256.0;
1092  nShift++;
1093  }
1094  while (nShift > 29)
1095  {
1096  dDiff /= 256.0;
1097  nShift--;
1098  }
1099 
1100  return dDiff;
1101 }
1102 
1103 /*
1104 NOTE: unlike bitcoin we are using PREVIOUS block height here,
1105  might be a good idea to change this to use prev bits
1106  but current height to avoid confusion.
1107 */
1108 CAmount GetBlockSubsidy(int nPrevBits, int nPrevHeight, const Consensus::Params& consensusParams, bool fSuperblockPartOnly)
1109 {
1110  double dDiff;
1111  CAmount nSubsidyBase;
1112 
1113  if (nPrevHeight <= 4500 && Params().NetworkIDString() == CBaseChainParams::MAIN) {
1114  /* a bug which caused diff to not be correctly calculated */
1115  dDiff = (double)0x0000ffff / (double)(nPrevBits & 0x00ffffff);
1116  } else {
1117  dDiff = ConvertBitsToDouble(nPrevBits);
1118  }
1119 
1120  if (nPrevHeight < 5465) {
1121  // Early ages...
1122  // 1111/((x+1)^2)
1123  nSubsidyBase = (1111.0 / (pow((dDiff+1.0),2.0)));
1124  if(nSubsidyBase > 500) nSubsidyBase = 500;
1125  else if(nSubsidyBase < 1) nSubsidyBase = 1;
1126  } else if (nPrevHeight < 17000 || (dDiff <= 75 && nPrevHeight < 24000)) {
1127  // CPU mining era
1128  // 11111/(((x+51)/6)^2)
1129  nSubsidyBase = (11111.0 / (pow((dDiff+51.0)/6.0,2.0)));
1130  if(nSubsidyBase > 500) nSubsidyBase = 500;
1131  else if(nSubsidyBase < 25) nSubsidyBase = 25;
1132  } else {
1133  // GPU/ASIC mining era
1134  // 2222222/(((x+2600)/9)^2)
1135  nSubsidyBase = (2222222.0 / (pow((dDiff+2600.0)/9.0,2.0)));
1136  if(nSubsidyBase > 25) nSubsidyBase = 25;
1137  else if(nSubsidyBase < 5) nSubsidyBase = 5;
1138  }
1139 
1140  CAmount nSubsidy = nSubsidyBase * COIN;
1141 
1142  // yearly decline of production by ~7.1% per year, projected ~18M coins max by year 2050+.
1143  for (int i = consensusParams.nSubsidyHalvingInterval; i <= nPrevHeight; i += consensusParams.nSubsidyHalvingInterval) {
1144  nSubsidy -= nSubsidy/14;
1145  }
1146 
1147  // this is only active on devnets
1148  if (nPrevHeight < consensusParams.nHighSubsidyBlocks) {
1149  nSubsidy *= consensusParams.nHighSubsidyFactor;
1150  }
1151 
1152  // Hard fork to reduce the block reward by 10 extra percent (allowing budget/superblocks)
1153  CAmount nSuperblockPart = (nPrevHeight > consensusParams.nBudgetPaymentsStartBlock) ? nSubsidy/10 : 0;
1154 
1155  return fSuperblockPartOnly ? nSuperblockPart : nSubsidy - nSuperblockPart;
1156 }
1157 
1158 CAmount GetMasternodePayment(int nHeight, CAmount blockValue, int nReallocActivationHeight)
1159 {
1160  CAmount ret = blockValue/5; // start at 20%
1161 
1164 
1165  // mainnet:
1166  if(nHeight > nMNPIBlock) ret += blockValue / 20; // 158000 - 25.0% - 2014-10-24
1167  if(nHeight > nMNPIBlock+(nMNPIPeriod* 1)) ret += blockValue / 20; // 175280 - 30.0% - 2014-11-25
1168  if(nHeight > nMNPIBlock+(nMNPIPeriod* 2)) ret += blockValue / 20; // 192560 - 35.0% - 2014-12-26
1169  if(nHeight > nMNPIBlock+(nMNPIPeriod* 3)) ret += blockValue / 40; // 209840 - 37.5% - 2015-01-26
1170  if(nHeight > nMNPIBlock+(nMNPIPeriod* 4)) ret += blockValue / 40; // 227120 - 40.0% - 2015-02-27
1171  if(nHeight > nMNPIBlock+(nMNPIPeriod* 5)) ret += blockValue / 40; // 244400 - 42.5% - 2015-03-30
1172  if(nHeight > nMNPIBlock+(nMNPIPeriod* 6)) ret += blockValue / 40; // 261680 - 45.0% - 2015-05-01
1173  if(nHeight > nMNPIBlock+(nMNPIPeriod* 7)) ret += blockValue / 40; // 278960 - 47.5% - 2015-06-01
1174  if(nHeight > nMNPIBlock+(nMNPIPeriod* 9)) ret += blockValue / 40; // 313520 - 50.0% - 2015-08-03
1175 
1176  if (nHeight < nReallocActivationHeight) {
1177  // Block Reward Realocation is not activated yet, nothing to do
1178  return ret;
1179  }
1180 
1181  int nSuperblockCycle = Params().GetConsensus().nSuperblockCycle;
1182  // Actual realocation starts in the cycle next to one activation happens in
1183  int nReallocStart = nReallocActivationHeight - nReallocActivationHeight % nSuperblockCycle + nSuperblockCycle;
1184 
1185  if (nHeight < nReallocStart) {
1186  // Activated but we have to wait for the next cycle to start realocation, nothing to do
1187  return ret;
1188  }
1189 
1190  // Periods used to reallocate the masternode reward from 50% to 60%
1191  static std::vector<int> vecPeriods{
1192  513, // Period 1: 51.3%
1193  526, // Period 2: 52.6%
1194  533, // Period 3: 53.3%
1195  540, // Period 4: 54%
1196  546, // Period 5: 54.6%
1197  552, // Period 6: 55.2%
1198  557, // Period 7: 55.7%
1199  562, // Period 8: 56.2%
1200  567, // Period 9: 56.7%
1201  572, // Period 10: 57.2%
1202  577, // Period 11: 57.7%
1203  582, // Period 12: 58.2%
1204  585, // Period 13: 58.5%
1205  588, // Period 14: 58.8%
1206  591, // Period 15: 59.1%
1207  594, // Period 16: 59.4%
1208  597, // Period 17: 59.7%
1209  599, // Period 18: 59.9%
1210  600 // Period 19: 60%
1211  };
1212 
1213  int nReallocCycle = nSuperblockCycle * 3;
1214  int nCurrentPeriod = std::min<int>((nHeight - nReallocStart) / nReallocCycle, vecPeriods.size() - 1);
1215 
1216  return static_cast<CAmount>(blockValue * vecPeriods[nCurrentPeriod] / 1000);
1217 }
1218 
1220 {
1221  // Once this function has returned false, it must remain false.
1222  static std::atomic<bool> latchToFalse{false};
1223  // Optimization: pre-test latch before taking the lock.
1224  if (latchToFalse.load(std::memory_order_relaxed))
1225  return false;
1226 
1227  LOCK(cs_main);
1228  if (latchToFalse.load(std::memory_order_relaxed))
1229  return false;
1230  if (fImporting || fReindex)
1231  return true;
1232  const CChainParams& chainParams = Params();
1233  if (chainActive.Tip() == nullptr)
1234  return true;
1236  return true;
1237  if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1238  return true;
1239  LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1240  latchToFalse.store(true, std::memory_order_relaxed);
1241  return false;
1242 }
1243 
1245 
1246 static void AlertNotify(const std::string& strMessage)
1247 {
1249  std::string strCmd = gArgs.GetArg("-alertnotify", "");
1250  if (strCmd.empty()) return;
1251 
1252  // Alert text should be plain ascii coming from a trusted source, but to
1253  // be safe we first strip anything not in safeChars, then add single quotes around
1254  // the whole string before passing it to the shell:
1255  std::string singleQuote("'");
1256  std::string safeStatus = SanitizeString(strMessage);
1257  safeStatus = singleQuote+safeStatus+singleQuote;
1258  boost::replace_all(strCmd, "%s", safeStatus);
1259 
1260  boost::thread t(runCommand, strCmd); // thread runs free
1261 }
1262 
1264 {
1266  // Before we get past initial download, we cannot reliably alert about forks
1267  // (we assume we don't get stuck on a fork before finishing our initial sync)
1268  if (IsInitialBlockDownload())
1269  return;
1270 
1271  // If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it)
1272  // of our head, drop it
1274  pindexBestForkTip = nullptr;
1275 
1276  if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1277  {
1279  {
1281  std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1282  pindexBestForkBase->phashBlock->ToString() + std::string("'");
1283  AlertNotify(warning);
1284  }
1285  }
1287  {
1289  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__,
1292  SetfLargeWorkForkFound(true);
1293  }
1294  }
1295  else
1296  {
1297  if(pindexBestInvalid->nHeight > chainActive.Height() + 6)
1298  LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1299  else
1300  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__);
1302  }
1303  }
1304  else
1305  {
1306  SetfLargeWorkForkFound(false);
1308  }
1309 }
1310 
1311 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1312 {
1314  // If we are on a fork that is sufficiently large, set a warning flag
1315  CBlockIndex* pfork = pindexNewForkTip;
1316  CBlockIndex* plonger = chainActive.Tip();
1317  while (pfork && pfork != plonger)
1318  {
1319  while (plonger && plonger->nHeight > pfork->nHeight)
1320  plonger = plonger->pprev;
1321  if (pfork == plonger)
1322  break;
1323  pfork = pfork->pprev;
1324  }
1325 
1326  // We define a condition where we should warn the user about as a fork of at least 7 blocks
1327  // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1328  // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1329  // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1330  // hash rate operating on the fork.
1331  // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1332  // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1333  if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1334  pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1335  chainActive.Height() - pindexNewForkTip->nHeight < 72)
1336  {
1337  pindexBestForkTip = pindexNewForkTip;
1338  pindexBestForkBase = pfork;
1339  }
1340 
1342 }
1343 
1344 void static InvalidChainFound(CBlockIndex* pindexNew)
1345 {
1346  if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1347  pindexBestInvalid = pindexNew;
1348 
1349  LogPrintf("%s: invalid block=%s height=%d log2_work=%.8f date=%s\n", __func__,
1350  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1351  log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1352  pindexNew->GetBlockTime()));
1353  CBlockIndex *tip = chainActive.Tip();
1354  assert (tip);
1355  LogPrintf("%s: current best=%s height=%d log2_work=%.8f date=%s\n", __func__,
1356  tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1357  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1359 }
1360 
1362  if (!state.CorruptionPossible()) {
1363  pindex->nStatus |= BLOCK_FAILED_VALID;
1364  g_failed_blocks.insert(pindex);
1365  setDirtyBlockIndex.insert(pindex);
1366  setBlockIndexCandidates.erase(pindex);
1367  InvalidChainFound(pindex);
1368  }
1369 }
1370 
1371 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1372 {
1373  // mark inputs spent
1374  if (!tx.IsCoinBase()) {
1375  txundo.vprevout.reserve(tx.vin.size());
1376  for (const CTxIn &txin : tx.vin) {
1377  txundo.vprevout.emplace_back();
1378  bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1379  assert(is_spent);
1380  }
1381  }
1382  // add outputs
1383  AddCoins(inputs, tx, nHeight);
1384 }
1385 
1386 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1387 {
1388  CTxUndo txundo;
1389  UpdateCoins(tx, inputs, txundo, nHeight);
1390 }
1391 
1393  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1396 }
1397 
1399 {
1400  LOCK(cs_main);
1401  CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1402  return pindexPrev->nHeight + 1;
1403 }
1404 
1405 
1408 
1410  // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1411  // setup_bytes creates the minimum possible cache (2 elements).
1412  size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
1413  size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1414  LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1415  (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1416 }
1417 
1432 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
1433 {
1434  if (!tx.IsCoinBase())
1435  {
1436  if (pvChecks)
1437  pvChecks->reserve(tx.vin.size());
1438 
1439  // The first loop above does all the inexpensive checks.
1440  // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1441  // Helps prevent CPU exhaustion attacks.
1442 
1443  // Skip script verification when connecting blocks under the
1444  // assumevalid block. Assuming the assumevalid block is valid this
1445  // is safe because block merkle hashes are still computed and checked,
1446  // Of course, if an assumed valid block is invalid due to false scriptSigs
1447  // this optimization would allow an invalid chain to be accepted.
1448  if (fScriptChecks) {
1449  // First check if script executions have been cached with the same
1450  // flags. Note that this assumes that the inputs provided are
1451  // correct (ie that the transaction hash which is in tx's prevouts
1452  // properly commits to the scriptPubKey in the inputs view of that
1453  // transaction).
1454  uint256 hashCacheEntry;
1455  // We only use the first 19 bytes of nonce to avoid a second SHA
1456  // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1457  static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1458  CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1459  AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1460  if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1461  return true;
1462  }
1463 
1464  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1465  const COutPoint &prevout = tx.vin[i].prevout;
1466  const Coin& coin = inputs.AccessCoin(prevout);
1467  assert(!coin.IsSpent());
1468 
1469  // We very carefully only pass in things to CScriptCheck which
1470  // are clearly committed to by tx' witness hash. This provides
1471  // a sanity check that our caching is not introducing consensus
1472  // failures through additional data in, eg, the coins being
1473  // spent being checked as a part of CScriptCheck.
1474 
1475  // Verify signature
1476  CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
1477  if (pvChecks) {
1478  pvChecks->push_back(CScriptCheck());
1479  check.swap(pvChecks->back());
1480  } else if (!check()) {
1482  // Check whether the failure was caused by a
1483  // non-mandatory script verification check, such as
1484  // non-standard DER encodings or non-null dummy
1485  // arguments; if so, don't trigger DoS protection to
1486  // avoid splitting the network between upgraded and
1487  // non-upgraded nodes.
1488  CScriptCheck check2(coin.out, tx, i,
1489  flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1490  if (check2())
1491  return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1492  }
1493  // Failures of other flags indicate a transaction that is
1494  // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1495  // such nodes as they are not following the protocol. That
1496  // said during an upgrade careful thought should be taken
1497  // as to the correct behavior - we may want to continue
1498  // peering with non-upgraded nodes even after soft-fork
1499  // super-majority signaling has occurred.
1500  return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1501  }
1502  }
1503 
1504  if (cacheFullScriptStore && !pvChecks) {
1505  // We executed all of the provided scripts, and were told to
1506  // cache the result. Do so now.
1507  scriptExecutionCache.insert(hashCacheEntry);
1508  }
1509  }
1510  }
1511 
1512  return true;
1513 }
1514 
1515 namespace {
1516 
1517 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1518 {
1519  // Open history file to append
1521  if (fileout.IsNull())
1522  return error("%s: OpenUndoFile failed", __func__);
1523 
1524  // Write index header
1525  unsigned int nSize = GetSerializeSize(fileout, blockundo);
1526  fileout << FLATDATA(messageStart) << nSize;
1527 
1528  // Write undo data
1529  long fileOutPos = ftell(fileout.Get());
1530  if (fileOutPos < 0)
1531  return error("%s: ftell failed", __func__);
1532  pos.nPos = (unsigned int)fileOutPos;
1533  fileout << blockundo;
1534 
1535  // calculate & write checksum
1537  hasher << hashBlock;
1538  hasher << blockundo;
1539  fileout << hasher.GetHash();
1540 
1541  return true;
1542 }
1543 
1544 static bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
1545 {
1546  CDiskBlockPos pos = pindex->GetUndoPos();
1547  if (pos.IsNull()) {
1548  return error("%s: no undo data available", __func__);
1549  }
1550 
1551  // Open history file to read
1552  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1553  if (filein.IsNull())
1554  return error("%s: OpenUndoFile failed", __func__);
1555 
1556  // Read block
1557  uint256 hashChecksum;
1558  CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1559  try {
1560  verifier << pindex->pprev->GetBlockHash();
1561  verifier >> blockundo;
1562  filein >> hashChecksum;
1563  }
1564  catch (const std::exception& e) {
1565  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1566  }
1567 
1568  // Verify checksum
1569  if (hashChecksum != verifier.GetHash())
1570  return error("%s: Checksum mismatch", __func__);
1571 
1572  return true;
1573 }
1574 
1576 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1577 {
1578  SetMiscWarning(strMessage);
1579  LogPrintf("*** %s\n", strMessage);
1581  userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1582  "", CClientUIInterface::MSG_ERROR);
1583  StartShutdown();
1584  return false;
1585 }
1586 
1587 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1588 {
1589  AbortNode(strMessage, userMessage);
1590  return state.Error(strMessage);
1591 }
1592 
1593 } // namespace
1594 
1602 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1603 {
1604  bool fClean = true;
1605 
1606  if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1607 
1608  if (undo.nHeight == 0) {
1609  // Missing undo metadata (height and coinbase). Older versions included this
1610  // information only in undo records for the last spend of a transactions'
1611  // outputs. This implies that it must be present for some other output of the same tx.
1612  const Coin& alternate = AccessByTxid(view, out.hash);
1613  if (!alternate.IsSpent()) {
1614  undo.nHeight = alternate.nHeight;
1615  undo.fCoinBase = alternate.fCoinBase;
1616  } else {
1617  return DISCONNECT_FAILED; // adding output for transaction without known metadata
1618  }
1619  }
1620  // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1621  // sure that the coin did not already exist in the cache. As we have queried for that above
1622  // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1623  // it is an overwrite.
1624  view.AddCoin(out, std::move(undo), !fClean);
1625 
1626  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1627 }
1628 
1632 {
1633  bool fDIP0003Active = pindex->nHeight >= Params().GetConsensus().DIP0003Height;
1634  bool fHasBestBlock = evoDb->VerifyBestBlock(pindex->GetBlockHash());
1635 
1636  if (fDIP0003Active && !fHasBestBlock) {
1637  // Nodes that upgraded after DIP3 activation will have to reindex to ensure evodb consistency
1638  AbortNode("Found EvoDB inconsistency, you must reindex to continue");
1639  return DISCONNECT_FAILED;
1640  }
1641 
1642  bool fClean = true;
1643 
1644  CBlockUndo blockUndo;
1645  if (!UndoReadFromDisk(blockUndo, pindex)) {
1646  error("DisconnectBlock(): failure reading undo data");
1647  return DISCONNECT_FAILED;
1648  }
1649 
1650  if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1651  error("DisconnectBlock(): block and undo data inconsistent");
1652  return DISCONNECT_FAILED;
1653  }
1654 
1655  std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
1656  std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > addressUnspentIndex;
1657  std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> > spentIndex;
1658 
1659  if (!UndoSpecialTxsInBlock(block, pindex)) {
1660  return DISCONNECT_FAILED;
1661  }
1662 
1663  // undo transactions in reverse order
1664  for (int i = block.vtx.size() - 1; i >= 0; i--) {
1665  const CTransaction &tx = *(block.vtx[i]);
1666  uint256 hash = tx.GetHash();
1667  bool is_coinbase = tx.IsCoinBase();
1668 
1669  if (fAddressIndex) {
1670 
1671  for (unsigned int k = tx.vout.size(); k-- > 0;) {
1672  const CTxOut &out = tx.vout[k];
1673 
1674  if (out.scriptPubKey.IsPayToScriptHash()) {
1675  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
1676 
1677  // undo receiving activity
1678  addressIndex.push_back(std::make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue));
1679 
1680  // undo unspent index
1681  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(2, uint160(hashBytes), hash, k), CAddressUnspentValue()));
1682 
1683  } else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
1684  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
1685 
1686  // undo receiving activity
1687  addressIndex.push_back(std::make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, hash, k, false), out.nValue));
1688 
1689  // undo unspent index
1690  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(1, uint160(hashBytes), hash, k), CAddressUnspentValue()));
1691 
1692  } else if (out.scriptPubKey.IsPayToPublicKey()) {
1693  uint160 hashBytes(Hash160(out.scriptPubKey.begin()+1, out.scriptPubKey.end()-1));
1694  addressIndex.push_back(std::make_pair(CAddressIndexKey(1, hashBytes, pindex->nHeight, i, hash, k, false), out.nValue));
1695  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(1, hashBytes, hash, k), CAddressUnspentValue()));
1696  } else {
1697  continue;
1698  }
1699 
1700  }
1701 
1702  }
1703 
1704  // Check that all outputs are available and match the outputs in the block itself
1705  // exactly.
1706  for (size_t o = 0; o < tx.vout.size(); o++) {
1707  if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1708  COutPoint out(hash, o);
1709  Coin coin;
1710  bool is_spent = view.SpendCoin(out, &coin);
1711  if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1712  fClean = false; // transaction output mismatch
1713  }
1714  }
1715  }
1716 
1717  // restore inputs
1718  if (i > 0) { // not coinbases
1719  CTxUndo &txundo = blockUndo.vtxundo[i-1];
1720  if (txundo.vprevout.size() != tx.vin.size()) {
1721  error("DisconnectBlock(): transaction and undo data inconsistent");
1722  return DISCONNECT_FAILED;
1723  }
1724  for (unsigned int j = tx.vin.size(); j-- > 0;) {
1725  const COutPoint &out = tx.vin[j].prevout;
1726  int undoHeight = txundo.vprevout[j].nHeight;
1727  int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1728  if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1729  fClean = fClean && res != DISCONNECT_UNCLEAN;
1730 
1731  const CTxIn input = tx.vin[j];
1732 
1733  if (fSpentIndex) {
1734  // undo and delete the spent index
1735  spentIndex.push_back(std::make_pair(CSpentIndexKey(input.prevout.hash, input.prevout.n), CSpentIndexValue()));
1736  }
1737 
1738  if (fAddressIndex) {
1739  const Coin &coin = view.AccessCoin(tx.vin[j].prevout);
1740  const CTxOut &prevout = coin.out;
1741  if (prevout.scriptPubKey.IsPayToScriptHash()) {
1742  std::vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22);
1743 
1744  // undo spending activity
1745  addressIndex.push_back(std::make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1));
1746 
1747  // restore unspent index
1748  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(2, uint160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undoHeight)));
1749 
1750 
1751  } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
1752  std::vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
1753 
1754  // undo spending activity
1755  addressIndex.push_back(std::make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, hash, j, true), prevout.nValue * -1));
1756 
1757  // restore unspent index
1758  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(1, uint160(hashBytes), input.prevout.hash, input.prevout.n), CAddressUnspentValue(prevout.nValue, prevout.scriptPubKey, undoHeight)));
1759 
1760  } else if (prevout.scriptPubKey.IsPayToPublicKey()) {
1761  uint160 hashBytes(Hash160(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.end()-1));
1762  addressIndex.push_back(std::make_pair(CAddressIndexKey(1, hashBytes, pindex->nHeight, i, hash, j, false), prevout.nValue));
1763  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(1, hashBytes, hash, j), CAddressUnspentValue()));
1764  } else {
1765  continue;
1766  }
1767  }
1768 
1769  }
1770  // At this point, all of txundo.vprevout should have been moved out.
1771  }
1772  }
1773 
1774 
1775  if (fSpentIndex) {
1776  if (!pblocktree->UpdateSpentIndex(spentIndex)) {
1777  AbortNode("Failed to delete spent index");
1778  return DISCONNECT_FAILED;
1779  }
1780  }
1781 
1782  if (fAddressIndex) {
1783  if (!pblocktree->EraseAddressIndex(addressIndex)) {
1784  AbortNode("Failed to delete address index");
1785  return DISCONNECT_FAILED;
1786  }
1787  if (!pblocktree->UpdateAddressUnspentIndex(addressUnspentIndex)) {
1788  AbortNode("Failed to write address unspent index");
1789  return DISCONNECT_FAILED;
1790  }
1791  }
1792 
1793  // move best block pointer to prevout block
1794  view.SetBestBlock(pindex->pprev->GetBlockHash());
1795  evoDb->WriteBestBlock(pindex->pprev->GetBlockHash());
1796 
1797  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1798 }
1799 
1800 void static FlushBlockFile(bool fFinalize = false)
1801 {
1802  LOCK(cs_LastBlockFile);
1803 
1804  CDiskBlockPos posOld(nLastBlockFile, 0);
1805 
1806  FILE *fileOld = OpenBlockFile(posOld);
1807  if (fileOld) {
1808  if (fFinalize)
1809  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1810  FileCommit(fileOld);
1811  fclose(fileOld);
1812  }
1813 
1814  fileOld = OpenUndoFile(posOld);
1815  if (fileOld) {
1816  if (fFinalize)
1817  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1818  FileCommit(fileOld);
1819  fclose(fileOld);
1820  }
1821 }
1822 
1823 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1824 
1825 static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, CValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
1826 {
1827  // Write undo information to disk
1828  if (pindex->GetUndoPos().IsNull()) {
1829  CDiskBlockPos _pos;
1830  if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1831  return error("ConnectBlock(): FindUndoPos failed");
1832  if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1833  return AbortNode(state, "Failed to write undo data");
1834 
1835  // update nUndoPos in block index
1836  pindex->nUndoPos = _pos.nPos;
1837  pindex->nStatus |= BLOCK_HAVE_UNDO;
1838  setDirtyBlockIndex.insert(pindex);
1839  }
1840 
1841  return true;
1842 }
1843 
1844 static bool WriteTxIndexDataForBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex)
1845 {
1846  if (!fTxIndex) return true;
1847 
1848  CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1849  std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1850  vPos.reserve(block.vtx.size());
1851  for (const CTransactionRef& tx : block.vtx)
1852  {
1853  vPos.push_back(std::make_pair(tx->GetHash(), pos));
1855  }
1856 
1857  if (!pblocktree->WriteTxIndex(vPos)) {
1858  return AbortNode(state, "Failed to write transaction index");
1859  }
1860 
1861  return true;
1862 }
1863 
1865 
1867  RenameThread("dash-scriptch");
1868  scriptcheckqueue.Thread();
1869 }
1870 
1871 // Protected by cs_main
1873 
1874 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params, bool fCheckMasternodesUpgraded)
1875 {
1876  LOCK(cs_main);
1877  int32_t nVersion = VERSIONBITS_TOP_BITS;
1878 
1879  for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1881  ThresholdState state = VersionBitsState(pindexPrev, params, pos, versionbitscache);
1882  const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
1883  if (vbinfo.check_mn_protocol && state == THRESHOLD_STARTED && fCheckMasternodesUpgraded) {
1884  // TODO implement new logic for MN upgrade checks (e.g. with LLMQ based feature/version voting)
1885  }
1886  if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1887  nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1888  }
1889  }
1890 
1891  return nVersion;
1892 }
1893 
1894 bool GetBlockHash(uint256& hashRet, int nBlockHeight)
1895 {
1896  LOCK(cs_main);
1897  if(chainActive.Tip() == nullptr) return false;
1898  if(nBlockHeight < -1 || nBlockHeight > chainActive.Height()) return false;
1899  if(nBlockHeight == -1) nBlockHeight = chainActive.Height();
1900  hashRet = chainActive[nBlockHeight]->GetBlockHash();
1901  return true;
1902 }
1903 
1908 {
1909 private:
1910  int bit;
1911 
1912 public:
1913  explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1914 
1915  int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1916  int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1917  int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1918  int Threshold(const Consensus::Params& params, int nAttempt) const override { return params.nRuleChangeActivationThreshold; }
1919 
1920  bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1921  {
1922  return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1923  ((pindex->nVersion >> bit) & 1) != 0 &&
1924  ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1925  }
1926 };
1927 
1928 // Protected by cs_main
1930 
1931 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1933 
1934  // BIP16 didn't become active until Apr 1 2012
1935  int64_t nBIP16SwitchTime = 1333238400;
1936  bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1937 
1938  unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1939 
1940  // Start enforcing the DERSIG (BIP66) rule
1941  if (pindex->nHeight >= consensusparams.BIP66Height) {
1943  }
1944 
1945  // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1946  if (pindex->nHeight >= consensusparams.BIP65Height) {
1948  }
1949 
1950  // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1953  }
1954 
1955  // Start enforcing BIP147 (NULLDUMMY) rule using versionbits logic.
1958  }
1959 
1960  return flags;
1961 }
1962 
1963 
1964 
1965 static int64_t nTimeCheck = 0;
1966 static int64_t nTimeForks = 0;
1967 static int64_t nTimeVerify = 0;
1968 static int64_t nTimeISFilter = 0;
1969 static int64_t nTimeSubsidy = 0;
1970 static int64_t nTimeValueValid = 0;
1971 static int64_t nTimePayeeValid = 0;
1972 static int64_t nTimeProcessSpecial = 0;
1973 static int64_t nTimeDashSpecific = 0;
1974 static int64_t nTimeConnect = 0;
1975 static int64_t nTimeIndex = 0;
1976 static int64_t nTimeCallbacks = 0;
1977 static int64_t nTimeTotal = 0;
1978 static int64_t nBlocksTotal = 0;
1979 
1984  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
1985 {
1987  assert(pindex);
1988  // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1989  assert((pindex->phashBlock == nullptr) ||
1990  (*pindex->phashBlock == block.GetHash()));
1991  int64_t nTimeStart = GetTimeMicros();
1992 
1993  // Check it again in case a previous version let a bad block in
1994  // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
1995  // ContextualCheckBlockHeader() here. This means that if we add a new
1996  // consensus rule that is enforced in one of those two functions, then we
1997  // may have let in a block that violates the rule prior to updating the
1998  // software, and we would NOT be enforcing the rule here. Fully solving
1999  // upgrade from one software version to the next after a consensus rule
2000  // change is potentially tricky and issue-specific (see RewindBlockIndex()
2001  // for one general approach that was used for BIP 141 deployment).
2002  // Also, currently the rule against blocks more than 2 hours in the future
2003  // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
2004  // re-enforce that rule here (at least until we make it impossible for
2005  // GetAdjustedTime() to go backward).
2006  if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
2007  return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
2008 
2009  if (pindex->pprev && pindex->phashBlock && llmq::chainLocksHandler->HasConflictingChainLock(pindex->nHeight, pindex->GetBlockHash())) {
2010  return state.DoS(10, error("%s: conflicting with chainlock", __func__), REJECT_INVALID, "bad-chainlock");
2011  }
2012 
2013  // verify that the view's current state corresponds to the previous block
2014  uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
2015  assert(hashPrevBlock == view.GetBestBlock());
2016 
2017  if (pindex->pprev) {
2018  bool fDIP0003Active = pindex->nHeight >= chainparams.GetConsensus().DIP0003Height;
2019  bool fHasBestBlock = evoDb->VerifyBestBlock(pindex->pprev->GetBlockHash());
2020 
2021  if (fDIP0003Active && !fHasBestBlock) {
2022  // Nodes that upgraded after DIP3 activation will have to reindex to ensure evodb consistency
2023  return AbortNode(state, "Found EvoDB inconsistency, you must reindex to continue");
2024  }
2025  }
2026 
2027  // Special case for the genesis block, skipping connection of its transactions
2028  // (its coinbase is unspendable)
2029  if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2030  if (!fJustCheck)
2031  view.SetBestBlock(pindex->GetBlockHash());
2032  return true;
2033  }
2034 
2035  nBlocksTotal++;
2036 
2037  bool fScriptChecks = true;
2038  if (!hashAssumeValid.IsNull()) {
2039  // We've been configured with the hash of a block which has been externally verified to have a valid history.
2040  // A suitable default value is included with the software and updated from time to time. Because validity
2041  // relative to a piece of software is an objective fact these defaults can be easily reviewed.
2042  // This setting doesn't force the selection of any particular chain but makes validating some faster by
2043  // effectively caching the result of part of the verification.
2044  BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
2045  if (it != mapBlockIndex.end()) {
2046  if (it->second->GetAncestor(pindex->nHeight) == pindex &&
2047  pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
2049  // This block is a member of the assumed verified chain and an ancestor of the best header.
2050  // The equivalent time check discourages hash power from extorting the network via DOS attack
2051  // into accepting an invalid block through telling users they must manually set assumevalid.
2052  // Requiring a software change or burying the invalid block, regardless of the setting, makes
2053  // it hard to hide the implication of the demand. This also avoids having release candidates
2054  // that are hardly doing any signature verification at all in testing without having to
2055  // artificially set the default assumed verified block further back.
2056  // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
2057  // least as good as the expected chain.
2058  fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
2059  }
2060  }
2061  }
2062 
2063  int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
2064  LogPrint(BCLog::BENCHMARK, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
2065 
2066  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2067  // unless those are already completely spent.
2068  // If such overwrites are allowed, coinbases and transactions depending upon those
2069  // can be duplicated to remove the ability to spend the first instance -- even after
2070  // being sent to another address.
2071  // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
2072  // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
2073  // already refuses previously-known transaction ids entirely.
2074  // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2075  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2076  // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2077  // initial block download.
2078  bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
2079  !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2080  (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2081 
2082  // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2083  // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2084  // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2085  // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
2086  // duplicate transactions descending from the known pairs either.
2087  // 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.
2088  assert(pindex->pprev);
2089  CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
2090  //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2091  fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
2092 
2093  if (fEnforceBIP30) {
2094  for (const auto& tx : block.vtx) {
2095  for (size_t o = 0; o < tx->vout.size(); o++) {
2096  if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2097  return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2098  REJECT_INVALID, "bad-txns-BIP30");
2099  }
2100  }
2101  }
2102  }
2103 
2105 
2106  // make sure old budget is the real one
2107  if (pindex->nHeight == chainparams.GetConsensus().nSuperblockStartBlock &&
2108  chainparams.GetConsensus().nSuperblockStartHash != uint256() &&
2109  block.GetHash() != chainparams.GetConsensus().nSuperblockStartHash)
2110  return state.DoS(100, error("ConnectBlock(): invalid superblock start"),
2111  REJECT_INVALID, "bad-sb-start");
2112 
2114 
2115  // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
2116  int nLockTimeFlags = 0;
2118  nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2119  }
2120 
2121  // Get the script flags for this block
2122  unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
2123 
2124  int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
2125  LogPrint(BCLog::BENCHMARK, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
2126 
2127  CBlockUndo blockundo;
2128 
2129  CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
2130 
2131  std::vector<int> prevheights;
2132  CAmount nFees = 0;
2133  int nInputs = 0;
2134  unsigned int nSigOps = 0;
2135  blockundo.vtxundo.reserve(block.vtx.size() - 1);
2136  std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex;
2137  std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > addressUnspentIndex;
2138  std::vector<std::pair<CSpentIndexKey, CSpentIndexValue> > spentIndex;
2139 
2140  std::vector<PrecomputedTransactionData> txdata;
2141  txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2142 
2143  bool fDIP0001Active_context = pindex->nHeight >= Params().GetConsensus().DIP0001Height;
2144 
2145  for (unsigned int i = 0; i < block.vtx.size(); i++)
2146  {
2147  const CTransaction &tx = *(block.vtx[i]);
2148  const uint256 txhash = tx.GetHash();
2149 
2150  nInputs += tx.vin.size();
2151 
2152  if (!tx.IsCoinBase())
2153  {
2154  CAmount txfee = 0;
2155  if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
2156  return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
2157  }
2158  nFees += txfee;
2159  if (!MoneyRange(nFees)) {
2160  return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
2161  REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
2162  }
2163 
2164  // Check that transaction is BIP68 final
2165  // BIP68 lock checks (as opposed to nLockTime checks) must
2166  // be in ConnectBlock because they require the UTXO set
2167  prevheights.resize(tx.vin.size());
2168  for (size_t j = 0; j < tx.vin.size(); j++) {
2169  prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2170  }
2171 
2172  if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
2173  return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
2174  REJECT_INVALID, "bad-txns-nonfinal");
2175  }
2176 
2177  if (fAddressIndex || fSpentIndex)
2178  {
2179  for (size_t j = 0; j < tx.vin.size(); j++) {
2180  const CTxIn input = tx.vin[j];
2181  const Coin& coin = view.AccessCoin(tx.vin[j].prevout);
2182  const CTxOut &prevout = coin.out;
2183  uint160 hashBytes;
2184  int addressType;
2185 
2186  if (prevout.scriptPubKey.IsPayToScriptHash()) {
2187  hashBytes = uint160(std::vector<unsigned char>(prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
2188  addressType = 2;
2189  } else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
2190  hashBytes = uint160(std::vector<unsigned char>(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
2191  addressType = 1;
2192  } else if (prevout.scriptPubKey.IsPayToPublicKey()) {
2193  hashBytes = Hash160(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.end()-1);
2194  addressType = 1;
2195  } else {
2196  hashBytes.SetNull();
2197  addressType = 0;
2198  }
2199 
2200  if (fAddressIndex && addressType > 0) {
2201  // record spending activity
2202  addressIndex.push_back(std::make_pair(CAddressIndexKey(addressType, hashBytes, pindex->nHeight, i, txhash, j, true), prevout.nValue * -1));
2203 
2204  // remove address from unspent index
2205  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(addressType, hashBytes, input.prevout.hash, input.prevout.n), CAddressUnspentValue()));
2206  }
2207 
2208  if (fSpentIndex) {
2209  // add the spent index to determine the txid and input that spent an output
2210  // and to find the amount and address from an input
2211  spentIndex.push_back(std::make_pair(CSpentIndexKey(input.prevout.hash, input.prevout.n), CSpentIndexValue(txhash, j, pindex->nHeight, prevout.nValue, addressType, hashBytes)));
2212  }
2213  }
2214 
2215  }
2216 
2217  }
2218 
2219  // GetTransactionSigOpCount counts 2 types of sigops:
2220  // * legacy (always)
2221  // * p2sh (when P2SH enabled in flags and excludes coinbase)
2222  nSigOps += GetTransactionSigOpCount(tx, view, flags);
2223  if (nSigOps > MaxBlockSigOps(fDIP0001Active_context))
2224  return state.DoS(100, error("ConnectBlock(): too many sigops"),
2225  REJECT_INVALID, "bad-blk-sigops");
2226 
2227  txdata.emplace_back(tx);
2228  if (!tx.IsCoinBase())
2229  {
2230 
2231  std::vector<CScriptCheck> vChecks;
2232  bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2233  if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
2234  return error("ConnectBlock(): CheckInputs on %s failed with %s",
2235  tx.GetHash().ToString(), FormatStateMessage(state));
2236  control.Add(vChecks);
2237  }
2238 
2239  if (fAddressIndex) {
2240  for (unsigned int k = 0; k < tx.vout.size(); k++) {
2241  const CTxOut &out = tx.vout[k];
2242 
2243  if (out.scriptPubKey.IsPayToScriptHash()) {
2244  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
2245 
2246  // record receiving activity
2247  addressIndex.push_back(std::make_pair(CAddressIndexKey(2, uint160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue));
2248 
2249  // record unspent output
2250  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(2, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight)));
2251 
2252  } else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
2253  std::vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
2254 
2255  // record receiving activity
2256  addressIndex.push_back(std::make_pair(CAddressIndexKey(1, uint160(hashBytes), pindex->nHeight, i, txhash, k, false), out.nValue));
2257 
2258  // record unspent output
2259  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(1, uint160(hashBytes), txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight)));
2260 
2261  } else if (out.scriptPubKey.IsPayToPublicKey()) {
2262  uint160 hashBytes(Hash160(out.scriptPubKey.begin()+1, out.scriptPubKey.end()-1));
2263  addressIndex.push_back(std::make_pair(CAddressIndexKey(1, hashBytes, pindex->nHeight, i, txhash, k, false), out.nValue));
2264  addressUnspentIndex.push_back(std::make_pair(CAddressUnspentKey(1, hashBytes, txhash, k), CAddressUnspentValue(out.nValue, out.scriptPubKey, pindex->nHeight)));
2265  } else {
2266  continue;
2267  }
2268 
2269  }
2270  }
2271 
2272  CTxUndo undoDummy;
2273  if (i > 0) {
2274  blockundo.vtxundo.push_back(CTxUndo());
2275  }
2276  UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2277  }
2278  int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
2279  LogPrint(BCLog::BENCHMARK, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
2280 
2281  if (!control.Wait())
2282  return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
2283  int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
2284  LogPrint(BCLog::BENCHMARK, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
2285 
2286 
2287  // DASH
2288 
2289  // It's possible that we simply don't have enough data and this could fail
2290  // (i.e. block itself could be a correct one and we need to store it),
2291  // that's why this is in ConnectBlock. Could be the other way around however -
2292  // the peer who sent us this block is missing some data and wasn't able
2293  // to recognize that block is actually invalid.
2294 
2295  // DASH : CHECK TRANSACTIONS FOR INSTANTSEND
2296 
2298  // Require other nodes to comply, send them some data in case they are missing it.
2299  for (const auto& tx : block.vtx) {
2300  // skip txes that have no inputs
2301  if (tx->vin.empty()) continue;
2303  if (!conflictLock) {
2304  continue;
2305  }
2306  if (llmq::chainLocksHandler->HasChainLock(pindex->nHeight, pindex->GetBlockHash())) {
2308  assert(llmq::quorumInstantSendManager->GetConflictingLock(*tx) == nullptr);
2309  } else {
2310  // The node which relayed this should switch to correct chain.
2311  // TODO: relay instantsend data/proof.
2312  LOCK(cs_main);
2313  return state.DoS(10, error("ConnectBlock(DASH): transaction %s conflicts with transaction lock %s", tx->GetHash().ToString(), conflictLock->txid.ToString()),
2314  REJECT_INVALID, "conflict-tx-lock");
2315  }
2316  }
2317  } else {
2318  LogPrintf("ConnectBlock(DASH): spork is off, skipping transaction locking checks\n");
2319  }
2320 
2321  int64_t nTime5_1 = GetTimeMicros(); nTimeISFilter += nTime5_1 - nTime4;
2322  LogPrint(BCLog::BENCHMARK, " - IS filter: %.2fms [%.2fs (%.2fms/blk)]\n", MICRO * (nTime5_1 - nTime4), nTimeISFilter * MICRO, nTimeISFilter * MILLI / nBlocksTotal);
2323 
2324  // DASH : MODIFIED TO CHECK MASTERNODE PAYMENTS AND SUPERBLOCKS
2325 
2326  // TODO: resync data (both ways?) and try to reprocess this block later.
2327  CAmount blockReward = nFees + GetBlockSubsidy(pindex->pprev->nBits, pindex->pprev->nHeight, chainparams.GetConsensus());
2328  std::string strError = "";
2329 
2330  int64_t nTime5_2 = GetTimeMicros(); nTimeSubsidy += nTime5_2 - nTime5_1;
2331  LogPrint(BCLog::BENCHMARK, " - GetBlockSubsidy: %.2fms [%.2fs (%.2fms/blk)]\n", MICRO * (nTime5_2 - nTime5_1), nTimeSubsidy * MICRO, nTimeSubsidy * MILLI / nBlocksTotal);
2332 
2333  if (!IsBlockValueValid(block, pindex->nHeight, blockReward, strError)) {
2334  return state.DoS(0, error("ConnectBlock(DASH): %s", strError), REJECT_INVALID, "bad-cb-amount");
2335  }
2336 
2337  int64_t nTime5_3 = GetTimeMicros(); nTimeValueValid += nTime5_3 - nTime5_2;
2338  LogPrint(BCLog::BENCHMARK, " - IsBlockValueValid: %.2fms [%.2fs (%.2fms/blk)]\n", MICRO * (nTime5_3 - nTime5_2), nTimeValueValid * MICRO, nTimeValueValid * MILLI / nBlocksTotal);
2339 
2340  if (!IsBlockPayeeValid(*block.vtx[0], pindex->nHeight, blockReward)) {
2341  return state.DoS(0, error("ConnectBlock(DASH): couldn't find masternode or superblock payments"),
2342  REJECT_INVALID, "bad-cb-payee");
2343  }
2344 
2345  int64_t nTime5_4 = GetTimeMicros(); nTimePayeeValid += nTime5_4 - nTime5_3;
2346  LogPrint(BCLog::BENCHMARK, " - IsBlockPayeeValid: %.2fms [%.2fs (%.2fms/blk)]\n", MICRO * (nTime5_4 - nTime5_3), nTimePayeeValid * MICRO, nTimePayeeValid * MILLI / nBlocksTotal);
2347 
2348  if (!ProcessSpecialTxsInBlock(block, pindex, state, fJustCheck, fScriptChecks)) {
2349  return error("ConnectBlock(DASH): ProcessSpecialTxsInBlock for block %s failed with %s",
2350  pindex->GetBlockHash().ToString(), FormatStateMessage(state));
2351  }
2352 
2353  int64_t nTime5_5 = GetTimeMicros(); nTimeProcessSpecial += nTime5_5 - nTime5_4;
2354  LogPrint(BCLog::BENCHMARK, " - ProcessSpecialTxsInBlock: %.2fms [%.2fs (%.2fms/blk)]\n", MICRO * (nTime5_5 - nTime5_4), nTimeProcessSpecial * MICRO, nTimeProcessSpecial * MILLI / nBlocksTotal);
2355 
2356  int64_t nTime5 = GetTimeMicros(); nTimeDashSpecific += nTime5 - nTime4;
2357  LogPrint(BCLog::BENCHMARK, " - Dash specific: %.2fms [%.2fs (%.2fms/blk)]\n", MICRO * (nTime5 - nTime4), nTimeDashSpecific * MICRO, nTimeDashSpecific * MILLI / nBlocksTotal);
2358 
2359  // END DASH
2360 
2361  if (fJustCheck)
2362  return true;
2363 
2364  if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
2365  return false;
2366 
2367  if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
2369  setDirtyBlockIndex.insert(pindex);
2370  }
2371 
2372  if (!WriteTxIndexDataForBlock(block, state, pindex))
2373  return false;
2374 
2375  if (fAddressIndex) {
2376  if (!pblocktree->WriteAddressIndex(addressIndex)) {
2377  return AbortNode(state, "Failed to write address index");
2378  }
2379 
2380  if (!pblocktree->UpdateAddressUnspentIndex(addressUnspentIndex)) {
2381  return AbortNode(state, "Failed to write address unspent index");
2382  }
2383  }
2384 
2385  if (fSpentIndex)
2386  if (!pblocktree->UpdateSpentIndex(spentIndex))
2387  return AbortNode(state, "Failed to write transaction index");
2388 
2389  if (fTimestampIndex)
2390  if (!pblocktree->WriteTimestampIndex(CTimestampIndexKey(pindex->nTime, pindex->GetBlockHash())))
2391  return AbortNode(state, "Failed to write timestamp index");
2392 
2393  assert(pindex->phashBlock);
2394  // add this block to the view's block chain
2395  view.SetBestBlock(pindex->GetBlockHash());
2396 
2397  int64_t nTime6 = GetTimeMicros(); nTimeIndex += nTime6 - nTime5;
2398  LogPrint(BCLog::BENCHMARK, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
2399 
2400  evoDb->WriteBestBlock(pindex->GetBlockHash());
2401 
2402  int64_t nTime7 = GetTimeMicros(); nTimeCallbacks += nTime7 - nTime6;
2403  LogPrint(BCLog::BENCHMARK, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime7 - nTime6), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
2404 
2405  return true;
2406 }
2407 
2414 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
2415  int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
2416  LOCK(cs_main);
2417  static int64_t nLastWrite = 0;
2418  static int64_t nLastFlush = 0;
2419  static int64_t nLastSetChain = 0;
2420  std::set<int> setFilesToPrune;
2421  bool fFlushForPrune = false;
2422  bool fDoFullFlush = false;
2423  int64_t nNow = 0;
2424  try {
2425  {
2426  LOCK(cs_LastBlockFile);
2427  if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2428  if (nManualPruneHeight > 0) {
2429  FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
2430  } else {
2431  FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
2432  fCheckForPruning = false;
2433  }
2434  if (!setFilesToPrune.empty()) {
2435  fFlushForPrune = true;
2436  if (!fHavePruned) {
2437  pblocktree->WriteFlag("prunedblockfiles", true);
2438  fHavePruned = true;
2439  }
2440  }
2441  }
2442  nNow = GetTimeMicros();
2443  // Avoid writing/flushing immediately after startup.
2444  if (nLastWrite == 0) {
2445  nLastWrite = nNow;
2446  }
2447  if (nLastFlush == 0) {
2448  nLastFlush = nNow;
2449  }
2450  if (nLastSetChain == 0) {
2451  nLastSetChain = nNow;
2452  }
2453  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2454  int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2455  cacheSize += evoDb->GetMemoryUsage();
2456  int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2457  // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
2458  bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
2459  // The cache is over the limit, we have to write now.
2460  bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2461  // 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.
2462  bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2463  // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2464  bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2465  // Combine all conditions that result in a full cache flush.
2466  fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2467  // Write blocks and block index to disk.
2468  if (fDoFullFlush || fPeriodicWrite) {
2469  // Depend on nMinDiskSpace to ensure we can write block index
2470  if (!CheckDiskSpace(0))
2471  return state.Error("out of disk space");
2472  // First make sure all block and undo data is flushed to disk.
2473  FlushBlockFile();
2474  // Then update all block file information (which may refer to block and undo files).
2475  {
2476  std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2477  vFiles.reserve(setDirtyFileInfo.size());
2478  for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2479  vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2480  setDirtyFileInfo.erase(it++);
2481  }
2482  std::vector<const CBlockIndex*> vBlocks;
2483  vBlocks.reserve(setDirtyBlockIndex.size());
2484  for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2485  vBlocks.push_back(*it);
2486  setDirtyBlockIndex.erase(it++);
2487  }
2488  if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2489  return AbortNode(state, "Failed to write to block index database");
2490  }
2491  }
2492  // Finally remove any pruned files
2493  if (fFlushForPrune)
2494  UnlinkPrunedFiles(setFilesToPrune);
2495  nLastWrite = nNow;
2496  }
2497  // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2498  if (fDoFullFlush && !pcoinsTip->GetBestBlock().IsNull()) {
2499  // Typical Coin structures on disk are around 48 bytes in size.
2500  // Pushing a new one to the database can cause it to be written
2501  // twice (once in the log, and once in the tables). This is already
2502  // an overestimation, as most will delete an existing entry or
2503  // overwrite one. Still, use a conservative safety factor of 2.
2504  if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
2505  return state.Error("out of disk space");
2506  // Flush the chainstate (which may refer to block index entries).
2507  if (!pcoinsTip->Flush())
2508  return AbortNode(state, "Failed to write to coin database");
2509  if (!evoDb->CommitRootTransaction()) {
2510  return AbortNode(state, "Failed to commit EvoDB");
2511  }
2512  nLastFlush = nNow;
2513  }
2514  }
2515  if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2516  // Update best block in wallet (so we can detect restored wallets).
2518  nLastSetChain = nNow;
2519  }
2520  } catch (const std::runtime_error& e) {
2521  return AbortNode(state, std::string("System error while flushing: ") + e.what());
2522  }
2523  return true;
2524 }
2525 
2527  CValidationState state;
2528  const CChainParams& chainparams = Params();
2529  FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
2530 }
2531 
2533  CValidationState state;
2534  fCheckForPruning = true;
2535  const CChainParams& chainparams = Params();
2536  FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2537 }
2538 
2539 static void DoWarning(const std::string& strWarning)
2540 {
2541  static bool fWarned = false;
2542  SetMiscWarning(strWarning);
2543  if (!fWarned) {
2544  AlertNotify(strWarning);
2545  fWarned = true;
2546  }
2547 }
2548 
2550 void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainParams) {
2551  // New best block
2553 
2554  {
2556  g_best_block = pindexNew->GetBlockHash();
2557  g_best_block_cv.notify_all();
2558  }
2559 
2560  std::vector<std::string> warningMessages;
2561  if (!IsInitialBlockDownload())
2562  {
2563  int nUpgraded = 0;
2564  const CBlockIndex* pindex = pindexNew;
2565  for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2566  WarningBitsConditionChecker checker(bit);
2567  ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2568  if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2569  const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2570  if (state == THRESHOLD_ACTIVE) {
2571  DoWarning(strWarning);
2572  } else {
2573  warningMessages.push_back(strWarning);
2574  }
2575  }
2576  }
2577  // Check the version of the last 100 blocks to see if we need to upgrade:
2578  for (int i = 0; i < 100 && pindex != nullptr; i++)
2579  {
2580  int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2581  if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2582  ++nUpgraded;
2583  pindex = pindex->pprev;
2584  }
2585  if (nUpgraded > 0)
2586  warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2587  if (nUpgraded > 100/2)
2588  {
2589  std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2590  // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2591  DoWarning(strWarning);
2592  }
2593  }
2594  std::string strMessage = strprintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8f tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2595  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
2596  log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2597  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()),
2598  GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2599  strMessage += strprintf(" evodb_cache=%.1fMiB", evoDb->GetMemoryUsage() * (1.0 / (1<<20)));
2600  if (!warningMessages.empty())
2601  strMessage += strprintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2602  LogPrintf("%s\n", strMessage);
2603 }
2604 
2616 {
2617  CBlockIndex *pindexDelete = chainActive.Tip();
2618  assert(pindexDelete);
2619  // Read block from disk.
2620  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2621  CBlock& block = *pblock;
2622  if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2623  return AbortNode(state, "Failed to read block");
2624  // Apply the block atomically to the chain state.
2625  int64_t nStart = GetTimeMicros();
2626  {
2627  auto dbTx = evoDb->BeginTransaction();
2628 
2629  CCoinsViewCache view(pcoinsTip.get());
2630  assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2631  if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
2632  return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2633  bool flushed = view.Flush();
2634  assert(flushed);
2635  dbTx->Commit();
2636  }
2637  LogPrint(BCLog::BENCHMARK, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
2638  // Write the chain state to disk, if necessary.
2639  if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2640  return false;
2641 
2642  if (disconnectpool) {
2643  // Save transactions to re-add to mempool at end of reorg
2644  for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2645  disconnectpool->addTransaction(*it);
2646  }
2647  while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2648  // Drop the earliest entry, and remove its children from the mempool.
2649  auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2651  disconnectpool->removeEntry(it);
2652  }
2653  }
2654 
2655  chainActive.SetTip(pindexDelete->pprev);
2656 
2657  UpdateTip(pindexDelete->pprev, chainparams);
2658  // Let wallets know transactions went from 1-confirmed to
2659  // 0-confirmed or conflicted:
2660  GetMainSignals().BlockDisconnected(pblock, pindexDelete);
2661  return true;
2662 }
2663 
2664 static int64_t nTimeReadFromDisk = 0;
2665 static int64_t nTimeConnectTotal = 0;
2666 static int64_t nTimeFlush = 0;
2667 static int64_t nTimeChainState = 0;
2668 static int64_t nTimePostConnect = 0;
2669 
2671  CBlockIndex* pindex = nullptr;
2672  std::shared_ptr<const CBlock> pblock;
2673  std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
2674  PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
2675 };
2693 private:
2694  std::vector<PerBlockConnectTrace> blocksConnected;
2696 
2697 public:
2698  explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
2699  pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2700  }
2701 
2703  pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
2704  }
2705 
2706  void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
2707  assert(!blocksConnected.back().pindex);
2708  assert(pindex);
2709  assert(pblock);
2710  blocksConnected.back().pindex = pindex;
2711  blocksConnected.back().pblock = std::move(pblock);
2712  blocksConnected.emplace_back();
2713  }
2714 
2715  std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
2716  // We always keep one extra block at the end of our list because
2717  // blocks are added after all the conflicted transactions have
2718  // been filled in. Thus, the last entry should always be an empty
2719  // one waiting for the transactions from the next block. We pop
2720  // the last entry here to make sure the list we return is sane.
2721  assert(!blocksConnected.back().pindex);
2722  assert(blocksConnected.back().conflictedTxs->empty());
2723  blocksConnected.pop_back();
2724  return blocksConnected;
2725  }
2726 
2728  assert(!blocksConnected.back().pindex);
2729  if (reason == MemPoolRemovalReason::CONFLICT) {
2730  blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
2731  }
2732  }
2733 };
2734 
2741 bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
2742 {
2743  assert(pindexNew->pprev == chainActive.Tip());
2744  // Read block from disk.
2745  int64_t nTime1 = GetTimeMicros();
2746  std::shared_ptr<const CBlock> pthisBlock;
2747  if (!pblock) {
2748  std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
2749  if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
2750  return AbortNode(state, "Failed to read block");
2751  pthisBlock = pblockNew;
2752  } else {
2753  pthisBlock = pblock;
2754  }
2755  const CBlock& blockConnecting = *pthisBlock;
2756  // Apply the block atomically to the chain state.
2757  int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2758  int64_t nTime3;
2759  LogPrint(BCLog::BENCHMARK, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
2760  {
2761  auto dbTx = evoDb->BeginTransaction();
2762 
2763  CCoinsViewCache view(pcoinsTip.get());
2764  bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
2765  GetMainSignals().BlockChecked(blockConnecting, state);
2766  if (!rv) {
2767  if (state.IsInvalid())
2768  InvalidBlockFound(pindexNew, state);
2769  return error("ConnectTip(): ConnectBlock %s failed with %s", pindexNew->GetBlockHash().ToString(), FormatStateMessage(state));
2770  }
2771  nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2772  LogPrint(BCLog::BENCHMARK, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
2773  bool flushed = view.Flush();
2774  assert(flushed);
2775  dbTx->Commit();
2776  }
2777  int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2778  LogPrint(BCLog::BENCHMARK, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
2779  // Write the chain state to disk, if necessary.
2780  if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2781  return false;
2782  int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2783  LogPrint(BCLog::BENCHMARK, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
2784  // Remove conflicting transactions from the mempool.;
2785  mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
2786  disconnectpool.removeForBlock(blockConnecting.vtx);
2787  // Update chainActive & related variables.
2788  chainActive.SetTip(pindexNew);
2789  UpdateTip(pindexNew, chainparams);
2790 
2791  int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2792  LogPrint(BCLog::BENCHMARK, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
2793  LogPrint(BCLog::BENCHMARK, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
2794 
2795  connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
2796  return true;
2797 }
2798 
2804  do {
2805  CBlockIndex *pindexNew = nullptr;
2806 
2807  // Find the best candidate header.
2808  {
2809  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2810  if (it == setBlockIndexCandidates.rend())
2811  return nullptr;
2812  pindexNew = *it;
2813  }
2814 
2815  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2816  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2817  CBlockIndex *pindexTest = pindexNew;
2818  bool fInvalidAncestor = false;
2819  while (pindexTest && !chainActive.Contains(pindexTest)) {
2820  assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2821 
2822  // Pruned nodes may have entries in setBlockIndexCandidates for
2823  // which block files have been deleted. Remove those as candidates
2824  // for the most work chain if we come across them; we can't switch
2825  // to a chain unless we have all the non-active-chain parent blocks.
2826  bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2827  bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2828  if (fFailedChain || fMissingData) {
2829  // Candidate chain is not usable (either invalid or missing data)
2830  if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2831  pindexBestInvalid = pindexNew;
2832  CBlockIndex *pindexFailed = pindexNew;
2833  // Remove the entire chain from the set.
2834  while (pindexTest != pindexFailed) {
2835  if (fFailedChain) {
2836  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2837  } else if (fMissingData) {
2838  // If we're missing data, then add back to mapBlocksUnlinked,
2839  // so that if the block arrives in the future we can try adding
2840  // to setBlockIndexCandidates again.
2841  mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2842  }
2843  setBlockIndexCandidates.erase(pindexFailed);
2844  pindexFailed = pindexFailed->pprev;
2845  }
2846  setBlockIndexCandidates.erase(pindexTest);
2847  fInvalidAncestor = true;
2848  break;
2849  }
2850  pindexTest = pindexTest->pprev;
2851  }
2852  if (!fInvalidAncestor)
2853  return pindexNew;
2854  } while(true);
2855 }
2856 
2859  // Note that we can't delete the current block itself, as we may need to return to it later in case a
2860  // reorganization to a better block fails.
2861  std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2862  while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2863  setBlockIndexCandidates.erase(it++);
2864  }
2865  // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2866  assert(!setBlockIndexCandidates.empty());
2867 }
2868 
2873 bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
2874 {
2876  const CBlockIndex *pindexOldTip = chainActive.Tip();
2877  const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2878 
2879  // Disconnect active blocks which are no longer in the best chain.
2880  bool fBlocksDisconnected = false;
2881  DisconnectedBlockTransactions disconnectpool;
2882  while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2883  if (!DisconnectTip(state, chainparams, &disconnectpool)) {
2884  // This is likely a fatal error, but keep the mempool consistent,
2885  // just in case. Only remove from the mempool in this case.
2886  UpdateMempoolForReorg(disconnectpool, false);
2887  return false;
2888  }
2889  fBlocksDisconnected = true;
2890  }
2891 
2892  // Build list of new blocks to connect.
2893  std::vector<CBlockIndex*> vpindexToConnect;
2894  bool fContinue = true;
2895  int nHeight = pindexFork ? pindexFork->nHeight : -1;
2896  while (fContinue && nHeight != pindexMostWork->nHeight) {
2897  // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2898  // a few blocks along the way.
2899  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2900  vpindexToConnect.clear();
2901  vpindexToConnect.reserve(nTargetHeight - nHeight);
2902  CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2903  while (pindexIter && pindexIter->nHeight != nHeight) {
2904  vpindexToConnect.push_back(pindexIter);
2905  pindexIter = pindexIter->pprev;
2906  }
2907  nHeight = nTargetHeight;
2908 
2909  // Connect new blocks.
2910  for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
2911  if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
2912  if (state.IsInvalid()) {
2913  // The block violates a consensus rule.
2914  if (!state.CorruptionPossible())
2915  InvalidChainFound(vpindexToConnect.back());
2916  state = CValidationState();
2917  fInvalidFound = true;
2918  fContinue = false;
2919  break;
2920  } else {
2921  // A system error occurred (disk space, database error, ...).
2922  // Make the mempool consistent with the current tip, just in case
2923  // any observers try to use it before shutdown.
2924  UpdateMempoolForReorg(disconnectpool, false);
2925  return false;
2926  }
2927  } else {
2929  if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2930  // We're in a better position than we were. Return temporarily to release the lock.
2931  fContinue = false;
2932  break;
2933  }
2934  }
2935  }
2936  }
2937 
2938  if (fBlocksDisconnected) {
2939  // If any blocks were disconnected, disconnectpool may be non empty. Add
2940  // any disconnected transactions back to the mempool.
2941  UpdateMempoolForReorg(disconnectpool, true);
2942  }
2943  mempool.check(pcoinsTip.get());
2944 
2945  // Callbacks/notifications for a new best chain.
2946  if (fInvalidFound)
2947  CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2948  else
2950 
2951  return true;
2952 }
2953 
2954 static void NotifyHeaderTip() {
2955  bool fNotify = false;
2956  bool fInitialBlockDownload = false;
2957  static CBlockIndex* pindexHeaderOld = nullptr;
2958  CBlockIndex* pindexHeader = nullptr;
2959  {
2960  LOCK(cs_main);
2961  pindexHeader = pindexBestHeader;
2962 
2963  if (pindexHeader != pindexHeaderOld) {
2964  fNotify = true;
2965  fInitialBlockDownload = IsInitialBlockDownload();
2966  pindexHeaderOld = pindexHeader;
2967  }
2968  }
2969  // Send block tip changed notifications without cs_main
2970  if (fNotify) {
2971  uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2972  GetMainSignals().NotifyHeaderTip(pindexHeader, fInitialBlockDownload);
2973  }
2974 }
2975 
2981 bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
2982  // Note that while we're often called here from ProcessNewBlock, this is
2983  // far from a guarantee. Things in the P2P/RPC will often end up calling
2984  // us in the middle of ProcessNewBlock - do not assume pblock is set
2985  // sanely for performance or correctness!
2987 
2988  // make sure that no matter what, only one thread is executing ActivateBestChain. This avoids a race condition when
2989  // validation signals are invoked, which might result in out-of-order execution.
2990  static CCriticalSection cs_activateBestChain;
2991  LOCK(cs_activateBestChain);
2992 
2993  CBlockIndex *pindexMostWork = nullptr;
2994  CBlockIndex *pindexNewTip = nullptr;
2995  int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
2996  do {
2997  boost::this_thread::interruption_point();
2998 
2999  if (GetMainSignals().CallbacksPending() > 10) {
3000  // Block until the validation queue drains. This should largely
3001  // never happen in normal operation, however may happen during
3002  // reindex, causing memory blowup if we run too far ahead.
3004  }
3005 
3006 
3007  const CBlockIndex *pindexFork;
3008  bool fInitialDownload;
3009  {
3010  LOCK(cs_main);
3011  ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
3012 
3013  CBlockIndex *pindexOldTip = chainActive.Tip();
3014  if (pindexMostWork == nullptr) {
3015  pindexMostWork = FindMostWorkChain();
3016  }
3017 
3018  // Whether we have anything to do at all.
3019  if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
3020  return true;
3021 
3022  bool fInvalidFound = false;
3023  std::shared_ptr<const CBlock> nullBlockPtr;
3024  if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
3025  return false;
3026 
3027  if (fInvalidFound) {
3028  // Wipe cache, we may need another branch now.
3029  pindexMostWork = nullptr;
3030  }
3031  pindexNewTip = chainActive.Tip();
3032  pindexFork = chainActive.FindFork(pindexOldTip);
3033  fInitialDownload = IsInitialBlockDownload();
3034 
3035  for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
3036  assert(trace.pblock && trace.pindex);
3037  GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
3038  }
3039  }
3040  // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3041 
3042  // Notifications/callbacks that can run without cs_main
3043 
3044  // Notify external listeners about the new tip.
3045  GetMainSignals().SynchronousUpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
3046  GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
3047 
3048  // Always notify the UI if a new block tip was connected
3049  if (pindexFork != pindexNewTip) {
3050  uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
3051  }
3052 
3053  if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
3054 
3055  // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
3056  // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
3057  // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
3058  // that the best block hash is non-null.
3059  if (ShutdownRequested())
3060  break;
3061  } while (pindexNewTip != pindexMostWork);
3062  CheckBlockIndex(chainparams.GetConsensus());
3063 
3064  // Write changes periodically to disk, after relay.
3065  if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
3066  return false;
3067  }
3068 
3069  return true;
3070 }
3071 
3072 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
3073  return g_chainstate.ActivateBestChain(state, chainparams, std::move(pblock));
3074 }
3075 
3077 {
3078  {
3079  LOCK(cs_main);
3080  if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
3081  // Nothing to do, this block is not at the tip.
3082  return true;
3083  }
3085  // The chain has been extended since the last call, reset the counter.
3087  }
3089  setBlockIndexCandidates.erase(pindex);
3091  if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3092  // We can't keep reducing the counter if somebody really wants to
3093  // call preciousblock 2**31-1 times on the same set of tips...
3095  }
3096  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
3097  setBlockIndexCandidates.insert(pindex);
3099  }
3100  }
3101 
3102  return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
3103 }
3104 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
3105  return g_chainstate.PreciousBlock(state, params, pindex);
3106 }
3107 
3109 {
3111 
3112  // We first disconnect backwards and then mark the blocks as invalid.
3113  // This prevents a case where pruned nodes may fail to invalidateblock
3114  // and be left unable to start as they have no tip candidates (as there
3115  // are no blocks that meet the "have data and are not invalid per
3116  // nStatus" criteria for inclusion in setBlockIndexCandidates).
3117 
3118  bool pindex_was_in_chain = false;
3119  CBlockIndex *invalid_walk_tip = chainActive.Tip();
3120 
3121  if (pindex == pindexBestHeader) {
3124  }
3125 
3126  DisconnectedBlockTransactions disconnectpool;
3127  while (chainActive.Contains(pindex)) {
3128  const CBlockIndex* pindexOldTip = chainActive.Tip();
3129  pindex_was_in_chain = true;
3130  // ActivateBestChain considers blocks already in chainActive
3131  // unconditionally valid already, so force disconnect away from it.
3132  if (!DisconnectTip(state, chainparams, &disconnectpool)) {
3133  // It's probably hopeless to try to make the mempool consistent
3134  // here if DisconnectTip failed, but we can try.
3135  UpdateMempoolForReorg(disconnectpool, false);
3136  return false;
3137  }
3138  if (pindexOldTip == pindexBestHeader) {
3141  }
3142  }
3143 
3144  // Now mark the blocks we just disconnected as descendants invalid
3145  // (note this may not be all descendants).
3146  while (pindex_was_in_chain && invalid_walk_tip != pindex) {
3147  invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
3148  setDirtyBlockIndex.insert(invalid_walk_tip);
3149  setBlockIndexCandidates.erase(invalid_walk_tip);
3150  invalid_walk_tip = invalid_walk_tip->pprev;
3151  }
3152 
3153  // Mark the block itself as invalid.
3154  pindex->nStatus |= BLOCK_FAILED_VALID;
3155  setDirtyBlockIndex.insert(pindex);
3156  setBlockIndexCandidates.erase(pindex);
3157  g_failed_blocks.insert(pindex);
3158 
3159  // DisconnectTip will add transactions to disconnectpool; try to add these
3160  // back to the mempool.
3161  UpdateMempoolForReorg(disconnectpool, true);
3162 
3163  // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3164  // add it again.
3165  BlockMap::iterator it = mapBlockIndex.begin();
3166  while (it != mapBlockIndex.end()) {
3167  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3168  setBlockIndexCandidates.insert(it->second);
3169  }
3170  it++;
3171  }
3172 
3173  InvalidChainFound(pindex);
3177  return true;
3178 }
3179 
3180 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
3181  return g_chainstate.InvalidateBlock(state, chainparams, pindex);
3182 }
3183 
3186 
3187  int nHeight = pindex->nHeight;
3188 
3189  // Remove the invalidity flag from this block and all its descendants.
3190  BlockMap::iterator it = mapBlockIndex.begin();
3191  while (it != mapBlockIndex.end()) {
3192  if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3193  it->second->nStatus &= ~BLOCK_FAILED_MASK;
3194  setDirtyBlockIndex.insert(it->second);
3195  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3196  setBlockIndexCandidates.insert(it->second);
3197  }
3198  if (it->second == pindexBestInvalid) {
3199  // Reset invalid block marker if it was pointing to one of those.
3200  pindexBestInvalid = nullptr;
3201  }
3202  g_failed_blocks.erase(it->second);
3203  }
3204  it++;
3205  }
3206 
3207  // Remove the invalidity flag from all ancestors too.
3208  while (pindex != nullptr) {
3209  if (pindex->nStatus & BLOCK_FAILED_MASK) {
3210  pindex->nStatus &= ~BLOCK_FAILED_MASK;
3211  setDirtyBlockIndex.insert(pindex);
3212  }
3213  pindex = pindex->pprev;
3214  }
3215  return true;
3216 }
3217 
3219  return g_chainstate.ResetBlockFailureFlags(pindex);
3220 }
3221 
3223 {
3224  // Check for duplicate
3225  uint256 hash = block.GetHash();
3226  BlockMap::iterator it = mapBlockIndex.find(hash);
3227  if (it != mapBlockIndex.end())
3228  return it->second;
3229 
3230  // Construct new block index object
3231  CBlockIndex* pindexNew = new CBlockIndex(block);
3232  // We assign the sequence id to blocks only when the full data is available,
3233  // to avoid miners withholding blocks but broadcasting headers, to get a
3234  // competitive advantage.
3235  pindexNew->nSequenceId = 0;
3236  BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3237  pindexNew->phashBlock = &((*mi).first);
3238  BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3239  if (miPrev != mapBlockIndex.end())
3240  {
3241  pindexNew->pprev = (*miPrev).second;
3242  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3243  pindexNew->BuildSkip();
3244  }
3245  pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
3246  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3247  if (nStatus & BLOCK_VALID_MASK) {
3248  pindexNew->RaiseValidity(nStatus);
3249  if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3250  pindexBestHeader = pindexNew;
3251  } else {
3252  pindexNew->RaiseValidity(BLOCK_VALID_TREE); // required validity level
3253  pindexNew->nStatus |= nStatus;
3254  }
3255 
3256  setDirtyBlockIndex.insert(pindexNew);
3257 
3258  // track prevBlockHash -> pindex (multimap)
3259  if (pindexNew->pprev) {
3260  mapPrevBlockIndex.emplace(pindexNew->pprev->GetBlockHash(), pindexNew);
3261  }
3262 
3263  return pindexNew;
3264 }
3265 
3268 {
3269  pindexNew->nTx = block.vtx.size();
3270  pindexNew->nChainTx = 0;
3271  pindexNew->nFile = pos.nFile;
3272  pindexNew->nDataPos = pos.nPos;
3273  pindexNew->nUndoPos = 0;
3274  pindexNew->nStatus |= BLOCK_HAVE_DATA;
3276  setDirtyBlockIndex.insert(pindexNew);
3277 
3278  if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
3279  // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3280  std::deque<CBlockIndex*> queue;
3281  queue.push_back(pindexNew);
3282 
3283  // Recursively process any descendant blocks that now may be eligible to be connected.
3284  while (!queue.empty()) {
3285  CBlockIndex *pindex = queue.front();
3286  queue.pop_front();
3287  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3288  {
3290  pindex->nSequenceId = nBlockSequenceId++;
3291  }
3292  if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3293  setBlockIndexCandidates.insert(pindex);
3294  }
3295  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3296  while (range.first != range.second) {
3297  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3298  queue.push_back(it->second);
3299  range.first++;
3300  mapBlocksUnlinked.erase(it);
3301  }
3302  }
3303  } else {
3304  if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3305  mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3306  }
3307  }
3308 
3309  return true;
3310 }
3311 
3312 static bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3313 {
3314  LOCK(cs_LastBlockFile);
3315 
3316  unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3317  if (vinfoBlockFile.size() <= nFile) {
3318  vinfoBlockFile.resize(nFile + 1);
3319  }
3320 
3321  if (!fKnown) {
3322  while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3323  nFile++;
3324  if (vinfoBlockFile.size() <= nFile) {
3325  vinfoBlockFile.resize(nFile + 1);
3326  }
3327  }
3328  pos.nFile = nFile;
3329  pos.nPos = vinfoBlockFile[nFile].nSize;
3330  }
3331 
3332  if ((int)nFile != nLastBlockFile) {
3333  if (!fKnown) {
3334  LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
3335  }
3336  FlushBlockFile(!fKnown);
3337  nLastBlockFile = nFile;
3338  }
3339 
3340  vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3341  if (fKnown)
3342  vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3343  else
3344  vinfoBlockFile[nFile].nSize += nAddSize;
3345 
3346  if (!fKnown) {
3347  unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3348  unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3349  if (nNewChunks > nOldChunks) {
3350  if (fPruneMode)
3351  fCheckForPruning = true;
3352  if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3353  FILE *file = OpenBlockFile(pos);
3354  if (file) {
3355  LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3356  AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3357  fclose(file);
3358  }
3359  }
3360  else
3361  return error("out of disk space");
3362  }
3363  }
3364 
3365  setDirtyFileInfo.insert(nFile);
3366  return true;
3367 }
3368 
3369 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3370 {
3371  pos.nFile = nFile;
3372 
3373  LOCK(cs_LastBlockFile);
3374 
3375  unsigned int nNewSize;
3376  pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3377  nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3378  setDirtyFileInfo.insert(nFile);
3379 
3380  unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3381  unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3382  if (nNewChunks > nOldChunks) {
3383  if (fPruneMode)
3384  fCheckForPruning = true;
3385  if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3386  FILE *file = OpenUndoFile(pos);
3387  if (file) {
3388  LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3389  AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3390  fclose(file);
3391  }
3392  }
3393  else
3394  return state.Error("out of disk space");
3395  }
3396 
3397  return true;
3398 }
3399 
3400 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3401 {
3402  // Check proof of work matches claimed amount
3403  if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3404  return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
3405 
3406  // Check DevNet
3407  if (!consensusParams.hashDevnetGenesisBlock.IsNull() &&
3408  block.hashPrevBlock == consensusParams.hashGenesisBlock &&
3409  block.GetHash() != consensusParams.hashDevnetGenesisBlock) {
3410  return state.DoS(100, error("CheckBlockHeader(): wrong devnet genesis"),
3411  REJECT_INVALID, "devnet-genesis");
3412  }
3413 
3414  return true;
3415 }
3416 
3417 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
3418 {
3419  // These are checks that are independent of context.
3420 
3421  if (block.fChecked)
3422  return true;
3423 
3424  // Check that the header is valid (particularly PoW). This is mostly
3425  // redundant with the call in AcceptBlockHeader.
3426  if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3427  return false;
3428 
3429  // Check the merkle root.
3430  if (fCheckMerkleRoot) {
3431  bool mutated;
3432  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
3433  if (block.hashMerkleRoot != hashMerkleRoot2)
3434  return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
3435 
3436  // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3437  // of transactions in a block without affecting the merkle root of a block,
3438  // while still invalidating it.
3439  if (mutated)
3440  return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
3441  }
3442 
3443  // All potential-corruption validation must be done before we do any
3444  // transaction validation, as otherwise we may mark the header as invalid
3445  // because we receive the wrong transactions for it.
3446 
3447  // Size limits (relaxed)
3448  if (block.vtx.empty() || block.vtx.size() > MaxBlockSize(true) || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MaxBlockSize(true))
3449  return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
3450 
3451  // First transaction must be coinbase, the rest must not be
3452  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3453  return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
3454  for (unsigned int i = 1; i < block.vtx.size(); i++)
3455  if (block.vtx[i]->IsCoinBase())
3456  return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
3457 
3458  // Check transactions
3459  for (const auto& tx : block.vtx)
3460  if (!CheckTransaction(*tx, state))
3461  return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
3462  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
3463 
3464  unsigned int nSigOps = 0;
3465  for (const auto& tx : block.vtx)
3466  {
3467  nSigOps += GetLegacySigOpCount(*tx);
3468  }
3469  // sigops limits (relaxed)
3470  if (nSigOps > MaxBlockSigOps(true))
3471  return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3472 
3473  if (fCheckPOW && fCheckMerkleRoot)
3474  block.fChecked = true;
3475 
3476  return true;
3477 }
3478 
3488 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
3489 {
3490  assert(pindexPrev != nullptr);
3491  const int nHeight = pindexPrev->nHeight + 1;
3492 
3493  // Check proof of work
3494  const Consensus::Params& consensusParams = params.GetConsensus();
3495  if(Params().NetworkIDString() == CBaseChainParams::MAIN && nHeight <= 68589){
3496  // architecture issues with DGW v1 and v2)
3497  unsigned int nBitsNext = GetNextWorkRequired(pindexPrev, &block, consensusParams);
3498  double n1 = ConvertBitsToDouble(block.nBits);
3499  double n2 = ConvertBitsToDouble(nBitsNext);
3500 
3501  if (abs(n1-n2) > n1*0.5)
3502  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),
3503  REJECT_INVALID, "bad-diffbits");
3504  } else {
3505  if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3506  return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, strprintf("incorrect proof of work at %d", nHeight));
3507  }
3508 
3509  // Check against checkpoints
3510  if (fCheckpointsEnabled) {
3511  // Don't accept any forks from the main chain prior to last checkpoint.
3512  // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3513  // MapBlockIndex.
3514  CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
3515  if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3516  return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3517  }
3518 
3519  // Check timestamp against prev
3520  if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3521  return state.Invalid(false, REJECT_INVALID, "time-too-old", strprintf("block's timestamp is too early %d %d", block.GetBlockTime(), pindexPrev->GetMedianTimePast()));
3522 
3523  // Check timestamp
3524  if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
3525  return state.Invalid(false, REJECT_INVALID, "time-too-new", strprintf("block timestamp too far in the future %d %d", block.GetBlockTime(), nAdjustedTime + 2 * 60 * 60));
3526 
3527  // check for version 2, 3 and 4 upgrades
3528  if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
3529  (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
3530  (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
3531  return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
3532  strprintf("rejected nVersion=0x%08x block", block.nVersion));
3533 
3534  return true;
3535 }
3536 
3543 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3544 {
3545  const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3546 
3547  // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3548  int nLockTimeFlags = 0;
3549  if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3550  nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3551  }
3552 
3553  int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3554  ? pindexPrev->GetMedianTimePast()
3555  : block.GetBlockTime();
3556 
3557  bool fDIP0001Active_context = nHeight >= consensusParams.DIP0001Height;
3558  bool fDIP0003Active_context = nHeight >= consensusParams.DIP0003Height;
3559 
3560  // Size limits
3561  unsigned int nMaxBlockSize = MaxBlockSize(fDIP0001Active_context);
3562  if (block.vtx.empty() || block.vtx.size() > nMaxBlockSize || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > nMaxBlockSize)
3563  return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
3564 
3565  // Check that all transactions are finalized and not over-sized
3566  // Also count sigops
3567  unsigned int nSigOps = 0;
3568  for (const auto& tx : block.vtx) {
3569  if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3570  return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3571  }
3572  if (!ContextualCheckTransaction(*tx, state, consensusParams, pindexPrev)) {
3573  return false;
3574  }
3575  nSigOps += GetLegacySigOpCount(*tx);
3576  }
3577 
3578  // Check sigops
3579  if (nSigOps > MaxBlockSigOps(fDIP0001Active_context))
3580  return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3581 
3582  // Enforce rule that the coinbase starts with serialized block height
3583  // After DIP3/DIP4 activation, we don't enforce the height in the input script anymore.
3584  // The CbTx special transaction payload will then contain the height, which is checked in CheckCbTx
3585  if (nHeight >= consensusParams.BIP34Height && !fDIP0003Active_context)
3586  {
3587  CScript expect = CScript() << nHeight;
3588  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3589  !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3590  return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3591  }
3592  }
3593 
3594  if (fDIP0003Active_context) {
3595  if (block.vtx[0]->nType != TRANSACTION_COINBASE) {
3596  return state.DoS(100, false, REJECT_INVALID, "bad-cb-type", false, "coinbase is not a CbTx");
3597  }
3598  }
3599 
3600  return true;
3601 }
3602 
3603 bool CChainState::AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
3604 {
3606  // Check for duplicate
3607  uint256 hash = block.GetHash();
3608  BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3609  CBlockIndex *pindex = nullptr;
3610 
3611  // TODO : ENABLE BLOCK CACHE IN SPECIFIC CASES
3612  if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3613 
3614  if (miSelf != mapBlockIndex.end()) {
3615  // Block header is already known.
3616  pindex = miSelf->second;
3617  if (ppindex)
3618  *ppindex = pindex;
3619  if (pindex->nStatus & BLOCK_FAILED_MASK)
3620  return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3621  return true;
3622  }
3623 
3624  if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
3625  return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3626 
3627  // Get prev block index
3628  CBlockIndex* pindexPrev = nullptr;
3629  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3630  if (mi == mapBlockIndex.end())
3631  return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
3632  pindexPrev = (*mi).second;
3633  assert(pindexPrev);
3634 
3635  if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3636  return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3637 
3638  if (pindexPrev->nStatus & BLOCK_CONFLICT_CHAINLOCK)
3639  // it's ok-ish, the other node is probably missing the latest chainlock
3640  return state.DoS(10, error("%s: prev block %s conflicts with chainlock", __func__, block.hashPrevBlock.ToString()), REJECT_INVALID, "bad-prevblk-chainlock");
3641 
3642  if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3643  return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3644 
3645  if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
3646  for (const CBlockIndex* failedit : g_failed_blocks) {
3647  if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
3648  assert(failedit->nStatus & BLOCK_FAILED_VALID);
3649  CBlockIndex* invalid_walk = pindexPrev;
3650  while (invalid_walk != failedit) {
3651  invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
3652  setDirtyBlockIndex.insert(invalid_walk);
3653  invalid_walk = invalid_walk->pprev;
3654  }
3655  return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3656  }
3657  }
3658  }
3659 
3660  if (llmq::chainLocksHandler->HasConflictingChainLock(pindexPrev->nHeight + 1, hash)) {
3661  if (pindex == nullptr) {
3663  }
3664  return state.DoS(10, error("%s: header %s conflicts with chainlock", __func__, hash.ToString()), REJECT_INVALID, "bad-chainlock");
3665  }
3666  }
3667  if (pindex == nullptr)
3668  pindex = AddToBlockIndex(block);
3669 
3670  if (ppindex)
3671  *ppindex = pindex;
3672 
3673  CheckBlockIndex(chainparams.GetConsensus());
3674 
3675  // Notify external listeners about accepted block header
3677 
3678  return true;
3679 }
3680 
3681 // Exposed wrapper for AcceptBlockHeader
3682 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
3683 {
3684  if (first_invalid != nullptr) first_invalid->SetNull();
3685  {
3686  LOCK(cs_main);
3687  for (const CBlockHeader& header : headers) {
3688  CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
3689  if (!g_chainstate.AcceptBlockHeader(header, state, chainparams, &pindex)) {
3690  if (first_invalid) *first_invalid = header;
3691  return false;
3692  }
3693  if (ppindex) {
3694  *ppindex = pindex;
3695  }
3696  }
3697  }
3698  NotifyHeaderTip();
3699  return true;
3700 }
3701 
3703 static CDiskBlockPos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const CDiskBlockPos* dbp) {
3704  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3705  CDiskBlockPos blockPos;
3706  if (dbp != nullptr)
3707  blockPos = *dbp;
3708  if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
3709  error("%s: FindBlockPos failed", __func__);
3710  return CDiskBlockPos();
3711  }
3712  if (dbp == nullptr) {
3713  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
3714  AbortNode("Failed to write block");
3715  return CDiskBlockPos();
3716  }
3717  }
3718  return blockPos;
3719 }
3720 
3722 bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
3723 {
3724  const CBlock& block = *pblock;
3725 
3726  if (fNewBlock) *fNewBlock = false;
3728 
3729  CBlockIndex *pindexDummy = nullptr;
3730  CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3731 
3732  if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3733  return false;
3734 
3735  // Try to process all requested blocks that we don't have, but only
3736  // process an unrequested block if it's new and has enough work to
3737  // advance our tip, and isn't too many blocks ahead.
3738  bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3739  bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
3740  // Blocks that are too out-of-order needlessly limit the effectiveness of
3741  // pruning, because pruning will not delete block files that contain any
3742  // blocks which are too close in height to the tip. Apply this test
3743  // regardless of whether pruning is enabled; it should generally be safe to
3744  // not process unrequested blocks.
3745  bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3746 
3747  // TODO: Decouple this function from the block download logic by removing fRequested
3748  // This requires some new chain data structure to efficiently look up if a
3749  // block is in a chain leading to a candidate for best tip, despite not
3750  // being such a candidate itself.
3751 
3752  // TODO: deal better with return value and error conditions for duplicate
3753  // and unrequested blocks.
3754  if (fAlreadyHave) return true;
3755  if (!fRequested) { // If we didn't ask for it:
3756  if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3757  if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
3758  if (fTooFarAhead) return true; // Block height is too high
3759 
3760  // Protect against DoS attacks from low-work chains.
3761  // If our tip is behind, a peer could try to send us
3762  // low-work blocks on a fake chain that we would never
3763  // request; don't process these.
3764  if (pindex->nChainWork < nMinimumChainWork) return true;
3765  }
3766  if (fNewBlock) *fNewBlock = true;
3767 
3768  if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
3769  !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
3770  if (state.IsInvalid() && !state.CorruptionPossible()) {
3771  pindex->nStatus |= BLOCK_FAILED_VALID;
3772  setDirtyBlockIndex.insert(pindex);
3773  }
3774  return error("%s: %s", __func__, FormatStateMessage(state));
3775  }
3776 
3777  // Header is valid/has work, merkle tree is good...RELAY NOW
3778  // (but if it does not build on our best tip, let the SendMessages loop relay it)
3779  if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
3780  GetMainSignals().NewPoWValidBlock(pindex, pblock);
3781 
3782  // Write block to history file
3783  try {
3784  CDiskBlockPos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
3785  if (blockPos.IsNull()) {
3786  state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
3787  return false;
3788  }
3789  if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3790  return error("AcceptBlock(): ReceivedBlockTransactions failed");
3791  } catch (const std::runtime_error& e) {
3792  return AbortNode(state, std::string("System error: ") + e.what());
3793  }
3794 
3795  if (fCheckForPruning)
3796  FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3797 
3798  CheckBlockIndex(chainparams.GetConsensus());
3799 
3800  return true;
3801 }
3802 
3803 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
3804 {
3806 
3807  {
3808  CBlockIndex *pindex = nullptr;
3809  if (fNewBlock) *fNewBlock = false;
3810  CValidationState state;
3811  // Ensure that CheckBlock() passes before calling AcceptBlock, as
3812  // belt-and-suspenders.
3813  bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
3814 
3815  LOCK(cs_main);
3816 
3817  if (ret) {
3818  // Store to disk
3819  ret = g_chainstate.AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
3820  }
3821  if (!ret) {
3822  GetMainSignals().BlockChecked(*pblock, state);
3823  return error("%s: AcceptBlock FAILED: %s", __func__, FormatStateMessage(state));
3824  }
3825  }
3826 
3827  NotifyHeaderTip();
3828 
3829  CValidationState state; // Only used to report errors, not invalidity - ignore it
3830  if (!g_chainstate.ActivateBestChain(state, chainparams, pblock))
3831  return error("%s: ActivateBestChain failed: %s", __func__, FormatStateMessage(state));
3832 
3833  LogPrintf("%s : ACCEPTED\n", __func__);
3834  return true;
3835 }
3836 
3837 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3838 {
3840  assert(pindexPrev && pindexPrev == chainActive.Tip());
3841 
3842  uint256 hash = block.GetHash();
3843  if (llmq::chainLocksHandler->HasConflictingChainLock(pindexPrev->nHeight + 1, hash)) {
3844  return state.DoS(10, error("%s: conflicting with chainlock", __func__), REJECT_INVALID, "bad-chainlock");
3845  }
3846 
3847  CCoinsViewCache viewNew(pcoinsTip.get());
3848  CBlockIndex indexDummy(block);
3849  indexDummy.pprev = pindexPrev;
3850  indexDummy.nHeight = pindexPrev->nHeight + 1;
3851 
3852  // begin tx and let it rollback
3853  auto dbTx = evoDb->BeginTransaction();
3854 
3855  // NOTE: CheckBlockHeader is called by CheckBlock
3856  if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
3857  return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3858  if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
3859  return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3860  if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
3861  return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3862  if (!g_chainstate.ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3863  return false;
3864  assert(state.IsValid());
3865 
3866  return true;
3867 }
3868 
3873 /* Calculate the amount of disk space the block & undo files currently use */
3875 {
3876  LOCK(cs_LastBlockFile);
3877 
3878  uint64_t retval = 0;
3879  for (const CBlockFileInfo &file : vinfoBlockFile) {
3880  retval += file.nSize + file.nUndoSize;
3881  }
3882  return retval;
3883 }
3884 
3885 /* Prune a block file (modify associated database entries)*/
3886 void PruneOneBlockFile(const int fileNumber)
3887 {
3888  LOCK(cs_LastBlockFile);
3889 
3890  for (const auto& entry : mapBlockIndex) {
3891  CBlockIndex* pindex = entry.second;
3892  if (pindex->nFile == fileNumber) {
3893  pindex->nStatus &= ~BLOCK_HAVE_DATA;
3894  pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3895  pindex->nFile = 0;
3896  pindex->nDataPos = 0;
3897  pindex->nUndoPos = 0;
3898  setDirtyBlockIndex.insert(pindex);
3899 
3900  // Prune from mapBlocksUnlinked -- any block we prune would have
3901  // to be downloaded again in order to consider its chain, at which
3902  // point it would be considered as a candidate for
3903  // mapBlocksUnlinked or setBlockIndexCandidates.
3904  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3905  while (range.first != range.second) {
3906  std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
3907  range.first++;
3908  if (_it->second == pindex) {
3909  mapBlocksUnlinked.erase(_it);
3910  }
3911  }
3912  }
3913  }
3914 
3915  vinfoBlockFile[fileNumber].SetNull();
3916  setDirtyFileInfo.insert(fileNumber);
3917 }
3918 
3919 
3920 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
3921 {
3922  for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3923  CDiskBlockPos pos(*it, 0);
3924  fs::remove(GetBlockPosFilename(pos, "blk"));
3925  fs::remove(GetBlockPosFilename(pos, "rev"));
3926  LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3927  }
3928 }
3929 
3930 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
3931 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
3932 {
3933  assert(fPruneMode && nManualPruneHeight > 0);
3934 
3935  LOCK2(cs_main, cs_LastBlockFile);
3936  if (chainActive.Tip() == nullptr)
3937  return;
3938 
3939  // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
3940  unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
3941  int count=0;
3942  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3943  if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3944  continue;
3945  PruneOneBlockFile(fileNumber);
3946  setFilesToPrune.insert(fileNumber);
3947  count++;
3948  }
3949  LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
3950 }
3951 
3952 /* This function is called from the RPC code for pruneblockchain */
3953 void PruneBlockFilesManual(int nManualPruneHeight)
3954 {
3955  CValidationState state;
3956  const CChainParams& chainparams = Params();
3957  FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
3958 }
3959 
3975 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3976 {
3977  LOCK2(cs_main, cs_LastBlockFile);
3978  if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
3979  return;
3980  }
3981  if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3982  return;
3983  }
3984 
3985  unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3986  uint64_t nCurrentUsage = CalculateCurrentUsage();
3987  // We don't check to prune until after we've allocated new space for files
3988  // So we should leave a buffer under our target to account for another allocation
3989  // before the next pruning.
3990  uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3991  uint64_t nBytesToPrune;
3992  int count=0;
3993 
3994  if (nCurrentUsage + nBuffer >= nPruneTarget) {
3995  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3996  nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3997 
3998  if (vinfoBlockFile[fileNumber].nSize == 0)
3999  continue;
4000 
4001  if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
4002  break;
4003 
4004  // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
4005  if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
4006  continue;
4007 
4008  PruneOneBlockFile(fileNumber);
4009  // Queue up the files for removal
4010  setFilesToPrune.insert(fileNumber);
4011  nCurrentUsage -= nBytesToPrune;
4012  count++;
4013  }
4014  }
4015 
4016  LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
4017  nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
4018  ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
4019  nLastBlockWeCanPrune, count);
4020 }
4021 
4022 bool CheckDiskSpace(uint64_t nAdditionalBytes)
4023 {
4024  uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
4025 
4026  // Check for nMinDiskSpace bytes (currently 50MB)
4027  if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
4028  return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
4029 
4030  return true;
4031 }
4032 
4033 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
4034 {
4035  if (pos.IsNull())
4036  return nullptr;
4037  fs::path path = GetBlockPosFilename(pos, prefix);
4038  fs::create_directories(path.parent_path());
4039  FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+");
4040  if (!file && !fReadOnly)
4041  file = fsbridge::fopen(path, "wb+");
4042  if (!file) {
4043  LogPrintf("Unable to open file %s\n", path.string());
4044  return nullptr;
4045  }
4046  if (pos.nPos) {
4047  if (fseek(file, pos.nPos, SEEK_SET)) {
4048  LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
4049  fclose(file);
4050  return nullptr;
4051  }
4052  }
4053  return file;
4054 }
4055 
4056 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
4057  return OpenDiskFile(pos, "blk", fReadOnly);
4058 }
4059 
4061 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
4062  return OpenDiskFile(pos, "rev", fReadOnly);
4063 }
4064 
4065 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
4066 {
4067  return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
4068 }
4069 
4071 {
4072  if (hash.IsNull())
4073  return nullptr;
4074 
4075  // Return existing
4076  BlockMap::iterator mi = mapBlockIndex.find(hash);
4077  if (mi != mapBlockIndex.end())
4078  return (*mi).second;
4079 
4080  // Create new
4081  CBlockIndex* pindexNew = new CBlockIndex();
4082  mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
4083  pindexNew->phashBlock = &((*mi).first);
4084 
4085  return pindexNew;
4086 }
4087 
4088 bool CChainState::LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree)
4089 {
4090  if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash){ return this->InsertBlockIndex(hash); }))
4091  return false;
4092 
4093  boost::this_thread::interruption_point();
4094 
4095  // Calculate nChainWork
4096  std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
4097  vSortedByHeight.reserve(mapBlockIndex.size());
4098  for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
4099  {
4100  CBlockIndex* pindex = item.second;
4101  vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
4102 
4103  // build mapPrevBlockIndex
4104  if (pindex->pprev) {
4105  mapPrevBlockIndex.emplace(pindex->pprev->GetBlockHash(), pindex);
4106  }
4107  }
4108  sort(vSortedByHeight.begin(), vSortedByHeight.end());
4109  for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
4110  {
4111  CBlockIndex* pindex = item.second;
4112  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
4113  pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
4114  // We can link the chain of blocks for which we've received transactions at some point.
4115  // Pruned nodes may have deleted the block.
4116  if (pindex->nTx > 0) {
4117  if (pindex->pprev) {
4118  if (pindex->pprev->nChainTx) {
4119  pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
4120  } else {
4121  pindex->nChainTx = 0;
4122  mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
4123  }
4124  } else {
4125  pindex->nChainTx = pindex->nTx;
4126  }
4127  }
4128  if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
4129  pindex->nStatus |= BLOCK_FAILED_CHILD;
4130  setDirtyBlockIndex.insert(pindex);
4131  }
4132  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
4133  setBlockIndexCandidates.insert(pindex);
4135  pindexBestInvalid = pindex;
4136  if (pindex->pprev)
4137  pindex->BuildSkip();
4138  if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
4139  pindexBestHeader = pindex;
4140  }
4141 
4142  return true;
4143 }
4144 
4145 bool static LoadBlockIndexDB(const CChainParams& chainparams)
4146 {
4147  if (!g_chainstate.LoadBlockIndex(chainparams.GetConsensus(), *pblocktree))
4148  return false;
4149 
4150  // Load block file info
4151  pblocktree->ReadLastBlockFile(nLastBlockFile);
4152  vinfoBlockFile.resize(nLastBlockFile + 1);
4153  LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
4154  for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
4155  pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
4156  }
4157  LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
4158  for (int nFile = nLastBlockFile + 1; true; nFile++) {
4159  CBlockFileInfo info;
4160  if (pblocktree->ReadBlockFileInfo(nFile, info)) {
4161  vinfoBlockFile.push_back(info);
4162  } else {
4163  break;
4164  }
4165  }
4166 
4167  // Check presence of blk files
4168  LogPrintf("Checking all blk files are present...\n");
4169  std::set<int> setBlkDataFiles;
4170  for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
4171  {
4172  CBlockIndex* pindex = item.second;
4173  if (pindex->nStatus & BLOCK_HAVE_DATA) {
4174  setBlkDataFiles.insert(pindex->nFile);
4175  }
4176  }
4177  for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
4178  {
4179  CDiskBlockPos pos(*it, 0);
4180  if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
4181  return false;
4182  }
4183  }
4184 
4185  // Check whether we have ever pruned block & undo files
4186  pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
4187  if (fHavePruned)
4188  LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4189 
4190  // Check whether we need to continue reindexing
4191  bool fReindexing = false;
4192  pblocktree->ReadReindexing(fReindexing);
4193  if(fReindexing) fReindex = true;
4194 
4195  // Check whether we have a transaction index
4196  pblocktree->ReadFlag("txindex", fTxIndex);
4197  LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
4198 
4199  // Check whether we have an address index
4200  pblocktree->ReadFlag("addressindex", fAddressIndex);
4201  LogPrintf("%s: address index %s\n", __func__, fAddressIndex ? "enabled" : "disabled");
4202 
4203  // Check whether we have a timestamp index
4204  pblocktree->ReadFlag("timestampindex", fTimestampIndex);
4205  LogPrintf("%s: timestamp index %s\n", __func__, fTimestampIndex ? "enabled" : "disabled");
4206 
4207  // Check whether we have a spent index
4208  pblocktree->ReadFlag("spentindex", fSpentIndex);
4209  LogPrintf("%s: spent index %s\n", __func__, fSpentIndex ? "enabled" : "disabled");
4210 
4211  return true;
4212 }
4213 
4214 bool LoadChainTip(const CChainParams& chainparams)
4215 {
4216  if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
4217 
4218  if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
4219  // In case we just added the genesis block, connect it now, so
4220  // that we always have a chainActive.Tip() when we return.
4221  LogPrintf("%s: Connecting genesis block...\n", __func__);
4222  CValidationState state;
4223  if (!ActivateBestChain(state, chainparams)) {
4224  return false;
4225  }
4226  }
4227 
4228  // Load pointer to end of best chain
4229  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
4230  if (it == mapBlockIndex.end())
4231  return false;
4232  chainActive.SetTip(it->second);
4233 
4235 
4236  LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
4238  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
4239  GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
4240  return true;
4241 }
4242 
4244 {
4245  uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
4246 }
4247 
4249 {
4250  uiInterface.ShowProgress("", 100, false);
4251 }
4252 
4253 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
4254 {
4255  LOCK(cs_main);
4256  if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
4257  return true;
4258 
4259  // begin tx and let it rollback
4260  auto dbTx = evoDb->BeginTransaction();
4261 
4262  // Verify blocks in the best chain
4263  if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
4264  nCheckDepth = chainActive.Height();
4265  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4266  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
4267  CCoinsViewCache coins(coinsview);
4268  CBlockIndex* pindexState = chainActive.Tip();
4269  CBlockIndex* pindexFailure = nullptr;
4270  int nGoodTransactions = 0;
4271  CValidationState state;
4272  int reportDone = 0;
4273  LogPrintf("[0%%]...");
4274  for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
4275  {
4276  boost::this_thread::interruption_point();
4277  int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4278  if (reportDone < percentageDone/10) {
4279  // report every 10% step
4280  LogPrintf("[%d%%]...", percentageDone);
4281  reportDone = percentageDone/10;
4282  }
4283  uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
4284  if (pindex->nHeight < chainActive.Height()-nCheckDepth)
4285  break;
4286  if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4287  // If pruning, only go back as far as we have data.
4288  LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
4289  break;
4290  }
4291  CBlock block;
4292  // check level 0: read from disk
4293  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
4294  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4295  // check level 1: verify block validity
4296  if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
4297  return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
4298  pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
4299  // check level 2: verify undo validity
4300  if (nCheckLevel >= 2 && pindex) {
4301  CBlockUndo undo;
4302  if (!pindex->GetUndoPos().IsNull()) {
4303  if (!UndoReadFromDisk(undo, pindex)) {
4304  return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4305  }
4306  }
4307  }
4308  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4309  if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
4310  assert(coins.GetBestBlock() == pindex->GetBlockHash());
4311  DisconnectResult res = g_chainstate.DisconnectBlock(block, pindex, coins);
4312  if (res == DISCONNECT_FAILED) {
4313  return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4314  }
4315  pindexState = pindex->pprev;
4316  if (res == DISCONNECT_UNCLEAN) {
4317  nGoodTransactions = 0;
4318  pindexFailure = pindex;
4319  } else {
4320  nGoodTransactions += block.vtx.size();
4321  }
4322  }
4323  if (ShutdownRequested())
4324  return true;
4325  }
4326  if (pindexFailure)
4327  return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4328 
4329  // check level 4: try reconnecting blocks
4330  if (nCheckLevel >= 4) {
4331  CBlockIndex *pindex = pindexState;
4332  while (pindex != chainActive.Tip()) {
4333  boost::this_thread::interruption_point();
4334  uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
4335  pindex = chainActive.Next(pindex);
4336  CBlock block;
4337  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
4338  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4339  if (!g_chainstate.ConnectBlock(block, state, pindex, coins, chainparams))
4340  return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4341  }
4342  }
4343 
4344  LogPrintf("[DONE].\n");
4345  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
4346 
4347  return true;
4348 }
4349 
4351 bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
4352 {
4353  // TODO: merge with ConnectBlock
4354  CBlock block;
4355  if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
4356  return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4357  }
4358 
4359  for (const CTransactionRef& tx : block.vtx) {
4360  if (!tx->IsCoinBase()) {
4361  for (const CTxIn &txin : tx->vin) {
4362  inputs.SpendCoin(txin.prevout);
4363  }
4364  }
4365  // Pass check = true as every addition may be an overwrite.
4366  AddCoins(inputs, *tx, pindex->nHeight, true);
4367  }
4368 
4369  CValidationState state;
4370  if (!ProcessSpecialTxsInBlock(block, pindex, state, false /*fJustCheck*/, false /*fScriptChecks*/)) {
4371  return error("RollforwardBlock(DASH): ProcessSpecialTxsInBlock for block %s failed with %s",
4372  pindex->GetBlockHash().ToString(), FormatStateMessage(state));
4373  }
4374 
4375  return true;
4376 }
4377 
4379 {
4380  LOCK(cs_main);
4381 
4382  CCoinsViewCache cache(view);
4383 
4384  std::vector<uint256> hashHeads = view->GetHeadBlocks();
4385  if (hashHeads.empty()) return true; // We're already in a consistent state.
4386  if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
4387 
4388  uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
4389  LogPrintf("Replaying blocks\n");
4390 
4391  const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
4392  const CBlockIndex* pindexNew; // New tip during the interrupted flush.
4393  const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4394 
4395  if (mapBlockIndex.count(hashHeads[0]) == 0) {
4396  return error("ReplayBlocks(): reorganization to unknown block requested");
4397  }
4398  pindexNew = mapBlockIndex[hashHeads[0]];
4399 
4400  if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4401  if (mapBlockIndex.count(hashHeads[1]) == 0) {
4402  return error("ReplayBlocks(): reorganization from unknown block requested");
4403  }
4404  pindexOld = mapBlockIndex[hashHeads[1]];
4405  pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4406  assert(pindexFork != nullptr);
4407  }
4408 
4409  auto dbTx = evoDb->BeginTransaction();
4410 
4411  // Rollback along the old branch.
4412  while (pindexOld != pindexFork) {
4413  // TODO: RollforwardBlock should update not only coins but also evodb and additional indexes.
4414  // Disable recovery from a crash during a fork until this is implemented.
4415  return error("ReplayBlocks(): recovery from a db crash during a fork is not supported yet");
4416  if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4417  CBlock block;
4418  if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
4419  return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4420  }
4421  LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4422  DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
4423  if (res == DISCONNECT_FAILED) {
4424  return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4425  }
4426  // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4427  // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4428  // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4429  // the result is still a version of the UTXO set with the effects of that block undone.
4430  }
4431  pindexOld = pindexOld->pprev;
4432  }
4433 
4434  // Roll forward from the forking point to the new tip.
4435  int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
4436  for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4437  const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
4438  LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
4439  if (!RollforwardBlock(pindex, cache, params)) return false;
4440  }
4441 
4442  cache.SetBestBlock(pindexNew->GetBlockHash());
4443  evoDb->WriteBestBlock(pindexNew->GetBlockHash());
4444  bool flushed = cache.Flush();
4445  assert(flushed);
4446  dbTx->Commit();
4447  uiInterface.ShowProgress("", 100, false);
4448  return true;
4449 }
4450 
4451 bool ReplayBlocks(const CChainParams& params, CCoinsView* view) {
4452  return g_chainstate.ReplayBlocks(params, view);
4453 }
4454 
4456  nBlockSequenceId = 1;
4457  g_failed_blocks.clear();
4458  setBlockIndexCandidates.clear();
4459 }
4460 
4461 // May NOT be used after any connections are up as much
4462 // of the peer-processing logic assumes a consistent
4463 // block index state
4465 {
4466  LOCK(cs_main);
4467  chainActive.SetTip(nullptr);
4468  pindexBestInvalid = nullptr;
4469  pindexBestHeader = nullptr;
4470  mempool.clear();
4471  mapBlocksUnlinked.clear();
4472  vinfoBlockFile.clear();
4473  nLastBlockFile = 0;
4474  setDirtyBlockIndex.clear();
4475  setDirtyFileInfo.clear();
4477  for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
4478  warningcache[b].clear();
4479  }
4480 
4481  for (BlockMap::value_type& entry : mapBlockIndex) {
4482  delete entry.second;
4483  }
4484  mapBlockIndex.clear();
4485  fHavePruned = false;
4486 
4488 }
4489 
4490 bool LoadBlockIndex(const CChainParams& chainparams)
4491 {
4492  // Load block index from databases
4493  bool needs_init = fReindex;
4494  if (!fReindex) {
4495  bool ret = LoadBlockIndexDB(chainparams);
4496  if (!ret) return false;
4497  needs_init = mapBlockIndex.empty();
4498  }
4499 
4500  if (needs_init) {
4501  // Everything here is for *new* reindex/DBs. Thus, though
4502  // LoadBlockIndexDB may have set fReindex if we shut down
4503  // mid-reindex previously, we don't check fReindex and
4504  // instead only check it prior to LoadBlockIndexDB to set
4505  // needs_init.
4506 
4507  LogPrintf("Initializing databases...\n");
4508  // Use the provided setting for -txindex in the new database
4509  fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
4510  pblocktree->WriteFlag("txindex", fTxIndex);
4511 
4512  // Use the provided setting for -addressindex in the new database
4513  fAddressIndex = gArgs.GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX);
4514  pblocktree->WriteFlag("addressindex", fAddressIndex);
4515 
4516  // Use the provided setting for -timestampindex in the new database
4518  pblocktree->WriteFlag("timestampindex", fTimestampIndex);
4519 
4520  // Use the provided setting for -spentindex in the new database
4521  fSpentIndex = gArgs.GetBoolArg("-spentindex", DEFAULT_SPENTINDEX);
4522  pblocktree->WriteFlag("spentindex", fSpentIndex);
4523  }
4524  return true;
4525 }
4526 
4527 bool CChainState::AddGenesisBlock(const CChainParams& chainparams, const CBlock& block, CValidationState& state)
4528 {
4529  CDiskBlockPos blockPos = SaveBlockToDisk(block, 0, chainparams, nullptr);
4530  if (blockPos.IsNull())
4531  return error("%s: writing genesis block to disk failed", __func__);
4532  CBlockIndex *pindex = AddToBlockIndex(block);
4533  if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4534  return error("%s: genesis block not accepted", __func__);
4535  return true;
4536 }
4537 
4539 {
4540  LOCK(cs_main);
4541 
4542  // Check whether we're already initialized by checking for genesis in
4543  // mapBlockIndex. Note that we can't use chainActive here, since it is
4544  // set based on the coins db, not the block index db, which is the only
4545  // thing loaded at this point.
4546  if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
4547  return true;
4548 
4549  try {
4550  CValidationState state;
4551 
4552  if (!AddGenesisBlock(chainparams, chainparams.GenesisBlock(), state))
4553  return false;
4554 
4555  if (chainparams.NetworkIDString() == CBaseChainParams::DEVNET) {
4556  // We can't continue if devnet genesis block is invalid
4557  std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(
4558  chainparams.DevNetGenesisBlock());
4559  bool fCheckBlock = CheckBlock(*shared_pblock, state, chainparams.GetConsensus());
4560  assert(fCheckBlock);
4561  if (!AcceptBlock(shared_pblock, state, chainparams, nullptr, true, nullptr, nullptr))
4562  return false;
4563  }
4564  } catch (const std::runtime_error &e) {
4565  return error("%s: failed to initialize block database: %s", __func__, e.what());
4566  }
4567 
4568  return true;
4569 }
4570 
4571 bool LoadGenesisBlock(const CChainParams& chainparams)
4572 {
4573  return g_chainstate.LoadGenesisBlock(chainparams);
4574 }
4575 
4576 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
4577 {
4578  // Map of disk positions for blocks with unknown parent (only used for reindex)
4579  static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4580  int64_t nStart = GetTimeMillis();
4581 
4582  int nLoaded = 0;
4583  try {
4584  unsigned int nMaxBlockSize = MaxBlockSize(true);
4585  // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4586  CBufferedFile blkdat(fileIn, 2*nMaxBlockSize, nMaxBlockSize+8, SER_DISK, CLIENT_VERSION);
4587  uint64_t nRewind = blkdat.GetPos();
4588  while (!blkdat.eof()) {
4589  boost::this_thread::interruption_point();
4590 
4591  blkdat.SetPos(nRewind);
4592  nRewind++; // start one byte further next time, in case of failure
4593  blkdat.SetLimit(); // remove former limit
4594  unsigned int nSize = 0;
4595  try {
4596  // locate a header
4597  unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
4598  blkdat.FindByte(chainparams.MessageStart()[0]);
4599  nRewind = blkdat.GetPos()+1;
4600  blkdat >> FLATDATA(buf);
4601  if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
4602  continue;
4603  // read size
4604  blkdat >> nSize;
4605  if (nSize < 80 || nSize > nMaxBlockSize)
4606  continue;
4607  } catch (const std::exception&) {
4608  // no valid block header found; don't complain
4609  break;
4610  }
4611  try {
4612  // read block
4613  uint64_t nBlockPos = blkdat.GetPos();
4614  if (dbp)
4615  dbp->nPos = nBlockPos;
4616  blkdat.SetLimit(nBlockPos + nSize);
4617  blkdat.SetPos(nBlockPos);
4618  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
4619  CBlock& block = *pblock;
4620  blkdat >> block;
4621  nRewind = blkdat.GetPos();
4622 
4623  // detect out of order blocks, and store them for later
4624  uint256 hash = block.GetHash();
4625  if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4626  LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4627  block.hashPrevBlock.ToString());
4628  if (dbp)
4629  mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4630  continue;
4631  }
4632 
4633  // process in case the block isn't known yet
4634  if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4635  LOCK(cs_main);
4636  CValidationState state;
4637  if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
4638  nLoaded++;
4639  if (state.IsError())
4640  break;
4641  } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4642  LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4643  }
4644 
4645  // Activate the genesis block so normal node progress can continue
4646  if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4647  CValidationState state;
4648  if (!ActivateBestChain(state, chainparams)) {
4649  break;
4650  }
4651  }
4652 
4653  NotifyHeaderTip();
4654 
4655  // Recursively process earlier encountered successors of this block
4656  std::deque<uint256> queue;
4657  queue.push_back(hash);
4658  while (!queue.empty()) {
4659  uint256 head = queue.front();
4660  queue.pop_front();
4661  std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4662  while (range.first != range.second) {
4663  std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4664  std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
4665  if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
4666  {
4667  LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
4668  head.ToString());
4669  LOCK(cs_main);
4670  CValidationState dummy;
4671  if (g_chainstate.AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
4672  {
4673  nLoaded++;
4674  queue.push_back(pblockrecursive->GetHash());
4675  }
4676  }
4677  range.first++;
4678  mapBlocksUnknownParent.erase(it);
4679  NotifyHeaderTip();
4680  }
4681  }
4682  } catch (const std::exception& e) {
4683  LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4684  }
4685  }
4686  } catch (const std::runtime_error& e) {
4687  AbortNode(std::string("System error: ") + e.what());
4688  }
4689  if (nLoaded > 0)
4690  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4691  return nLoaded > 0;
4692 }
4693 
4695 {
4696  if (!fCheckBlockIndex) {
4697  return;
4698  }
4699 
4700  LOCK(cs_main);
4701 
4702  // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4703  // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4704  // iterating the block tree require that chainActive has been initialized.)
4705  if (chainActive.Height() < 0) {
4706  assert(mapBlockIndex.size() <= 1);
4707  return;
4708  }
4709 
4710  // Build forward-pointing map of the entire block tree.
4711  std::multimap<CBlockIndex*,CBlockIndex*> forward;
4712  for (auto& entry : mapBlockIndex) {
4713  forward.insert(std::make_pair(entry.second->pprev, entry.second));
4714  }
4715 
4716  assert(forward.size() == mapBlockIndex.size());
4717 
4718  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
4719  CBlockIndex *pindex = rangeGenesis.first->second;
4720  rangeGenesis.first++;
4721  assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
4722 
4723  // Iterate over the entire block tree, using depth-first search.
4724  // Along the way, remember whether there are blocks on the path from genesis
4725  // block being explored which are the first to have certain properties.
4726  size_t nNodes = 0;
4727  int nHeight = 0;
4728  CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
4729  CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4730  CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
4731  CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4732  CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4733  CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4734  CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4735  while (pindex != nullptr) {
4736  nNodes++;
4737  if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4738  if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4739  if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4740  if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4741  if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4742  if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4743  if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4744 
4745  // Begin: actual consistency checks.
4746  if (pindex->pprev == nullptr) {
4747  // Genesis block checks.
4748  assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4749  assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4750  }
4751  if (pindex->nChainTx == 0) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
4752  // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4753  // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4754  if (!fHavePruned) {
4755  // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4756  assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4757  assert(pindexFirstMissing == pindexFirstNeverProcessed);
4758  } else {
4759  // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4760  if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4761  }
4762  if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4763  assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4764  // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4765  assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4766  assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
4767  assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4768  assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
4769  assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4770  assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
4771  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
4772  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
4773  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
4774  if (pindexFirstInvalid == nullptr) {
4775  // Checks for not-invalid blocks.
4776  assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4777  }
4778  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
4779  if (pindexFirstInvalid == nullptr) {
4780  // If this block sorts at least as good as the current tip and
4781  // is valid and we have all data for its parents, it must be in
4782  // setBlockIndexCandidates. chainActive.Tip() must also be there
4783  // even if some data has been pruned.
4784  if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
4785  assert(setBlockIndexCandidates.count(pindex));
4786  }
4787  // If some parent is missing, then it could be that this block was in
4788  // setBlockIndexCandidates but had to be removed because of the missing data.
4789  // In this case it must be in mapBlocksUnlinked -- see test below.
4790  }
4791  } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4792  assert(setBlockIndexCandidates.count(pindex) == 0);
4793  }
4794  // Check whether this block is in mapBlocksUnlinked.
4795  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4796  bool foundInUnlinked = false;
4797  while (rangeUnlinked.first != rangeUnlinked.second) {
4798  assert(rangeUnlinked.first->first == pindex->pprev);
4799  if (rangeUnlinked.first->second == pindex) {
4800  foundInUnlinked = true;
4801  break;
4802  }
4803  rangeUnlinked.first++;
4804  }
4805  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
4806  // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4807  assert(foundInUnlinked);
4808  }
4809  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4810  if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4811  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
4812  // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4813  assert(fHavePruned); // We must have pruned.
4814  // This block may have entered mapBlocksUnlinked if:
4815  // - it has a descendant that at some point had more work than the
4816  // tip, and
4817  // - we tried switching to that descendant but were missing
4818  // data for some intermediate block between chainActive and the
4819  // tip.
4820  // So if this block is itself better than chainActive.Tip() and it wasn't in
4821  // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4822  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4823  if (pindexFirstInvalid == nullptr) {
4824  assert(foundInUnlinked);
4825  }
4826  }
4827  }
4828  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4829  // End: actual consistency checks.
4830 
4831  // Try descending into the first subnode.
4832  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4833  if (range.first != range.second) {
4834  // A subnode was found.
4835  pindex = range.first->second;
4836  nHeight++;
4837  continue;
4838  }
4839  // This is a leaf node.
4840  // Move upwards until we reach a node of which we have not yet visited the last child.
4841  while (pindex) {
4842  // We are going to either move to a parent or a sibling of pindex.
4843  // If pindex was the first with a certain property, unset the corresponding variable.
4844  if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
4845  if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
4846  if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
4847  if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
4848  if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
4849  if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
4850  if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
4851  // Find our parent.
4852  CBlockIndex* pindexPar = pindex->pprev;
4853  // Find which child we just visited.
4854  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4855  while (rangePar.first->second != pindex) {
4856  assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4857  rangePar.first++;
4858  }
4859  // Proceed to the next one.
4860  rangePar.first++;
4861  if (rangePar.first != rangePar.second) {
4862  // Move to the sibling.
4863  pindex = rangePar.first->second;
4864  break;
4865  } else {
4866  // Move up further.
4867  pindex = pindexPar;
4868  nHeight--;
4869  continue;
4870  }
4871  }
4872  }
4873 
4874  // Check that we actually traversed the entire map.
4875  assert(nNodes == forward.size());
4876 }
4877 
4878 std::string CBlockFileInfo::ToString() const {
4879  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));
4880 }
4881 
4883 {
4884  LOCK(cs_LastBlockFile);
4885 
4886  return &vinfoBlockFile.at(n);
4887 }
4888 
4890 {
4892  return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
4893 }
4894 
4896 {
4897  LOCK(cs_main);
4898  return VersionBitsStatistics(chainActive.Tip(), params, pos, versionbitscache);
4899 }
4900 
4902 {
4903  LOCK(cs_main);
4905 }
4906 
4907 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
4908 
4909 bool LoadMempool(void)
4910 {
4911  const CChainParams& chainparams = Params();
4912  int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
4913  FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
4914  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
4915  if (file.IsNull()) {
4916  LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
4917  return false;
4918  }
4919 
4920  int64_t count = 0;
4921  int64_t expired = 0;
4922  int64_t failed = 0;
4923  int64_t already_there = 0;
4924  int64_t nNow = GetTime();
4925 
4926  try {
4927  uint64_t version;
4928  file >> version;
4929  if (version != MEMPOOL_DUMP_VERSION) {
4930  return false;
4931  }
4932  uint64_t num;
4933  file >> num;
4934  while (num--) {
4935  CTransactionRef tx;
4936  int64_t nTime;
4937  int64_t nFeeDelta;
4938  file >> tx;
4939  file >> nTime;
4940  file >> nFeeDelta;
4941 
4942  CAmount amountdelta = nFeeDelta;
4943  if (amountdelta) {
4944  mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
4945  }
4946  CValidationState state;
4947  if (nTime + nExpiryTimeout > nNow) {
4948  LOCK(cs_main);
4949  AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
4950  false /* bypass_limits */, 0 /* nAbsurdFee */);
4951  if (state.IsValid()) {
4952  ++count;
4953  } else {
4954  // mempool may contain the transaction already, e.g. from
4955  // wallet(s) having loaded it while we were processing
4956  // mempool transactions; consider these as valid, instead of
4957  // failed, but mark them as 'already there'
4958  if (mempool.exists(tx->GetHash())) {
4959  ++already_there;
4960  } else {
4961  ++failed;
4962  }
4963  }
4964  } else {
4965  ++expired;
4966  }
4967  if (ShutdownRequested())
4968  return false;
4969  }
4970  std::map<uint256, CAmount> mapDeltas;
4971  file >> mapDeltas;
4972 
4973  for (const auto& i : mapDeltas) {
4974  mempool.PrioritiseTransaction(i.first, i.second);
4975  }
4976  } catch (const std::exception& e) {
4977  LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
4978  return false;
4979  }
4980 
4981  LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
4982  return true;
4983 }
4984 
4985 bool DumpMempool(void)
4986 {
4987  int64_t start = GetTimeMicros();
4988 
4989  std::map<uint256, CAmount> mapDeltas;
4990  std::vector<TxMempoolInfo> vinfo;
4991 
4992  {
4993  LOCK(mempool.cs);
4994  for (const auto &i : mempool.mapDeltas) {
4995  mapDeltas[i.first] = i.second;
4996  }
4997  vinfo = mempool.infoAll();
4998  }
4999 
5000  int64_t mid = GetTimeMicros();
5001 
5002  try {
5003  FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
5004  if (!filestr) {
5005  return false;
5006  }
5007 
5008  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
5009 
5010  uint64_t version = MEMPOOL_DUMP_VERSION;
5011  file << version;
5012 
5013  file << (uint64_t)vinfo.size();
5014  for (const auto& i : vinfo) {
5015  file << *(i.tx);
5016  file << (int64_t)i.nTime;
5017  file << (int64_t)i.nFeeDelta;
5018  mapDeltas.erase(i.tx->GetHash());
5019  }
5020 
5021  file << mapDeltas;
5022  FileCommit(file.Get());
5023  file.fclose();
5024  RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
5025  int64_t last = GetTimeMicros();
5026  LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
5027  } catch (const std::exception& e) {
5028  LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
5029  return false;
5030  }
5031  return true;
5032 }
5033 
5035 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
5036  if (pindex == nullptr)
5037  return 0.0;
5038 
5039  int64_t nNow = time(nullptr);
5040 
5041  double fTxTotal;
5042 
5043  if (pindex->nChainTx <= data.nTxCount) {
5044  fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
5045  } else {
5046  fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
5047  }
5048 
5049  return pindex->nChainTx / fTxTotal;
5050 }
5051 
5053 {
5054 public:
5057  // block headers
5058  BlockMap::iterator it1 = mapBlockIndex.begin();
5059  for (; it1 != mapBlockIndex.end(); it1++)
5060  delete (*it1).second;
5061  mapBlockIndex.clear();
5062  }
CConditionVariable g_best_block_cv
Definition: validation.cpp:220
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: chain.h:195
static const unsigned int MAX_STANDARD_TX_SIGOPS
The maximum number of sigops we&#39;re willing to relay/mine in a single tx.
Definition: policy.h:28
CAmount nValue
Definition: transaction.h:147
bool ActivateBestChainStep(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace)
Try to make some progress towards making pindexMostWork the active block.
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:249
bool existsProviderTxConflict(const CTransaction &tx) const
Definition: txmempool.cpp:1229
std::multimap< CBlockIndex *, CBlockIndex * > mapBlocksUnlinked
Definition: validation.cpp:162
CTxMemPool & pool
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:648
bool GetBlockHash(uint256 &hashRet, int nBlockHeight)
Return true if hash can be found in chainActive at nBlockHeight height.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:66
CDiskBlockPos GetBlockPos() const
Definition: chain.h:261
CTxMemPool mempool
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:76
bool IsSpent() const
Definition: coins.h:75
bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, CValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex, bool fRequested, const CDiskBlockPos *dbp, bool *fNewBlock)
Store block on disk.
int Expire(int64_t time)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:1403
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE
Flags for nSequence and nLockTime locks.
Definition: consensus.h:28
std::vector< Coin > vprevout
Definition: undo.h:70
std::string ToString() const
Definition: chain.h:323
int64_t EndTime(const Consensus::Params &params) const override
int nMasternodePaymentsIncreaseBlock
Definition: params.h:135
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:217
bool IsCoinBase() const
Definition: coins.h:54
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:76
static FILE * OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly=false)
Open an undo file (rev?????.dat)
static void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
int nScriptCheckThreads
Definition: validation.cpp:222
static bool FlushStateToDisk(const CChainParams &chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool potential_overwrite)
Add a coin.
Definition: coins.cpp:66
void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason)
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:68
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:230
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:180
void addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
Definition: txmempool.cpp:555
uint256 GetRandHash()
Definition: random.cpp:384
static bool WriteTxIndexDataForBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex)
std::condition_variable CConditionVariable
Just a typedef for std::condition_variable, can be wrapped later if desired.
Definition: sync.h:106
static bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, const CChainParams &params, const CBlockIndex *pindexPrev, int64_t nAdjustedTime)
Context-dependent validity checks.
uint256 BIP34Hash
Definition: params.h:150
unsigned int nTxOffset
Definition: txdb.h:47
bool DumpMempool(void)
Dump the mempool to disk.
bool CheckTransaction(const CTransaction &tx, CValidationState &state)
Transaction validation functions.
Definition: tx_verify.cpp:152
std::pair< int, int64_t > CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
Calculates the block height and previous block&#39;s median time past at which the transaction will be co...
Definition: tx_verify.cpp:30
static const bool DEFAULT_PERMIT_BAREMULTISIG
Default for -permitbaremultisig.
Definition: validation.h:119
void UnloadBlockIndex()
Unload database information.
bool fAddressIndex
Definition: validation.cpp:226
void SetNull()
Definition: uint256.h:41
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
Definition: validation.cpp:950
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
static void CheckForkWarningConditions()
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:198
int64_t GetBlockTime() const
Definition: chain.h:297
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:5
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:127
double dTxRate
Definition: chainparams.h:31
void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload)
CScript scriptPubKey
Definition: transaction.h:148
descends from failed block
Definition: chain.h:159
static const unsigned int STANDARD_LOCKTIME_VERIFY_FLAGS
Used as the flags parameter to sequence and nLocktime checks in non-consensus code.
Definition: policy.h:60
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:1197
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or a pruned one if not found.
Definition: coins.cpp:116
static bool LoadBlockIndexDB(const CChainParams &chainparams)
static int64_t nTimePayeeValid
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Definition: txmempool.cpp:725
int GetUTXOHeight(const COutPoint &outpoint)
Definition: validation.cpp:449
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:203
void FileCommit(FILE *file)
Definition: util.cpp:1099
void SynchronousUpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:27
static int64_t nTimeConnectTotal
void CheckBlockIndex(const Consensus::Params &consensusParams)
bool GetAddressUnspent(uint160 addressHash, int type, std::vector< std::pair< CAddressUnspentKey, CAddressUnspentValue > > &unspentOutputs)
Definition: validation.cpp:934
bool SequenceLocks(const CTransaction &tx, int flags, std::vector< int > *prevHeights, const CBlockIndex &block)
Check if transaction is final per BIP 68 sequence numbers and can be included in a block...
Definition: tx_verify.cpp:102
int Threshold(const Consensus::Params &params, int nAttempt) const override
A UTXO entry.
Definition: coins.h:29
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindexDisconnected)
Definition: block.h:72
CBlockIndex * pindexBestForkBase
int64_t BeginTime(const Consensus::Params &params) const override
static const unsigned char REJECT_INSUFFICIENTFEE
Definition: validation.h:18
size_t GetTxSize() const
Definition: txmempool.h:105
static const unsigned int DEFAULT_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:16
static const unsigned int DEFAULT_MAX_MEMPOOL_SIZE
Default for -maxmempool, maximum megabytes of mempool memory usage.
Definition: policy.h:30
unsigned int MaxBlockSize(bool fDIP0001Active)
Definition: consensus.h:12
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
static const CAmount DEFAULT_TRANSACTION_MAXFEE
-maxtxfee default
Definition: validation.h:58
bool ShutdownRequested()
Definition: init.cpp:179
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
#define strprintf
Definition: tinyformat.h:1066
bool IsPayToScriptHash() const
Definition: script.cpp:212
static const uint64_t MEMPOOL_DUMP_VERSION
An in-memory indexed chain of blocks.
Definition: chain.h:442
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE
Maximum kilobytes for transactions to store for processing during reorg.
Definition: validation.h:74
static void AlertNotify(const std::string &strMessage)
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
CAmount maxTxFee
Absolute maximum transaction fee (in duffs) used by wallet and mempool (rejects high fee in sendrawtr...
Definition: validation.cpp:247
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:1389
static const int32_t VERSIONBITS_TOP_MASK
What bitmask determines whether versionbits is in use.
Definition: versionbits.h:16
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:229
unsigned int nFlags
Definition: validation.h:377
std::atomic_bool fReindex(false)
reverse_range< T > reverse_iterate(T &x)
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:114
int Period(const Consensus::Params &params) const override
BlockMap & mapBlockIndex
Definition: validation.cpp:215
static void FlushBlockFile(bool fFinalize=false)
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:1295
bool Condition(const CBlockIndex *pindex, const Consensus::Params &params) const override
static const CAmount COIN
Definition: amount.h:14
void TransactionAddedToMempool(const CTransactionRef &, int64_t)
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:93
static FILE * fileout
We use boost::call_once() to make sure mutexDebugLog and vMsgsBeforeOpenLog are initialized in a thre...
Definition: util.cpp:192
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be prun...
Definition: validation.h:207
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:64
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:155
const char * prefix
Definition: rest.cpp:574
int height
Definition: txmempool.h:45
static int64_t nTimeForks
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:134
bool IsBlockPayeeValid(const CTransaction &txNew, int nBlockHeight, CAmount blockReward)
static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS]
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int Height() const
Return the maximal height in the chain.
Definition: chain.h:484
void StartShutdown()
Definition: init.cpp:171
CCriticalSection cs_main
Definition: validation.cpp:213
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:36
void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state)
bool IsValid() const
Definition: validation.h:61
CTxOut out
unspent transaction output
Definition: coins.h:33
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 ...
Definition: serialize.h:225
#define expect(bit)
const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]
Definition: versionbits.cpp:8
bool fTimestampIndex
Definition: validation.cpp:227
cache implements a cache with properties similar to a cuckoo-set
Definition: cuckoocache.h:160
stage after last reached validness failed
Definition: chain.h:158
void clear()
Definition: txmempool.cpp:998
std::unordered_multimap< uint256, CBlockIndex *, BlockHasher > PrevBlockMap
Definition: validation.h:153
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:36
sph_u32 high
Definition: keccak.c:370
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:141
CChainState stores and provides an API to update our local knowledge of the current best chain and he...
Definition: validation.cpp:117
bool HasNoInputsOf(const CTransaction &tx) const
Check that none of this transactions inputs are in the mempool, and thus the tx is not dependent on o...
Definition: txmempool.cpp:1363
CBlockIndex * pindex
int BIP66Height
Block height at which BIP66 becomes active.
Definition: params.h:154
BIP9Stats VersionBitsTipStatistics(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the numerical statistics for the BIP9 state for a given deployment at the current tip...
unsigned int nSize
number of used bytes of block file
Definition: chain.h:35
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:244
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check)
Utility function to add all of a transaction&#39;s outputs to a cache.
Definition: coins.cpp:87
std::unique_ptr< CEvoDB > evoDb
Definition: evodb.cpp:7
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:499
int flags
Definition: dash-tx.cpp:462
bool check_mn_protocol
Whether to check current MN protocol or not.
Definition: versionbits.h:39
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:804
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:448
Definition: box.hpp:161
const CBlock & GenesisBlock() const
Definition: chainparams.h:58
static void DoWarning(const std::string &strWarning)
int nSuperblockCycle
Definition: params.h:144
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: utiltime.cpp:63
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:349
int ApplyTxInUndo(Coin &&undo, CCoinsViewCache &view, const COutPoint &out)
Restore the UTXO in a Coin at a given COutPoint.
CChainParams defines various tweakable parameters of a given instance of the Dash system...
Definition: chainparams.h:41
bool DoS(int level, bool ret=false, unsigned int chRejectCodeIn=0, const std::string &strRejectReasonIn="", bool corruptionIn=false, const std::string &strDebugMessageIn="")
Definition: validation.h:36
bool ReceivedBlockTransactions(const CBlock &block, CValidationState &state, CBlockIndex *pindexNew, const CDiskBlockPos &pos)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
uint32_t nTime
Definition: chain.h:212
ScriptError error
Definition: validation.h:379
undo data available in rev*.dat
Definition: chain.h:155
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: util.cpp:824
bool ReplayBlocks(const CChainParams &params, CCoinsView *view)
ThresholdState
Definition: versionbits.h:20
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
static bool WriteBlockToDisk(const CBlock &block, CDiskBlockPos &pos, const CMessageHeader::MessageStartChars &messageStart)
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:186
RAII-style controller object for a CCheckQueue that guarantees the passed queue is finished before co...
Definition: checkqueue.h:17
void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
Definition: validation.cpp:546
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:161
static const uint64_t nMinDiskSpace
Minimum disk space required - used in CheckDiskSpace()
Definition: validation.h:197
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:1502
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
bool cacheStore
Definition: validation.h:378
int64_t nTime
Definition: chainparams.h:29
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:82
void BlockChecked(const CBlock &, const CValidationState &)
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:237
unsigned char * begin()
Definition: uint256.h:57
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:345
static const unsigned char REJECT_INVALID
Definition: validation.h:13
CBlockIndex * pindexBestForkTip
static bool ContextualCheckBlock(const CBlock &block, CValidationState &state, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
NOTE: This function is not currently invoked by ConnectBlock(), so we should consider upgrade issues ...
static const unsigned char REJECT_OBSOLETE
Definition: validation.h:14
Signals for UI communication.
Definition: ui_interface.h:28
void RenameThread(const char *name)
Definition: util.cpp:1244
bool AddGenesisBlock(const CChainParams &chainparams, const CBlock &block, CValidationState &state)
int nHighSubsidyFactor
Definition: params.h:187
unsigned int nHeightLast
highest height of block in file
Definition: chain.h:38
#define FLATDATA(obj)
Definition: serialize.h:370
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:219
bool IsNull() const
Definition: uint256.h:33
const std::string strMessageMagic
Definition: validation.cpp:257
uint256 nSuperblockStartHash
Definition: params.h:143
bool IsCoinBase() const
Definition: transaction.h:272
static FILE * OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
bool fIsBareMultisigStd
Definition: validation.cpp:231
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:204
CTxOut m_tx_out
Definition: validation.h:374
static int64_t nTimeDashSpecific
static const bool DEFAULT_ADDRESSINDEX
Definition: validation.h:123
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
indirectmap< COutPoint, const CTransaction * > mapNextTx
Definition: txmempool.h:538
int nBudgetPaymentsStartBlock
Definition: params.h:139
double ConvertBitsToDouble(unsigned int nBits)
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:98
const std::vector< CTxIn > vin
Definition: transaction.h:215
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:455
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
unsigned int GetTransactionSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Count total signature operations for a transaction.
Definition: tx_verify.cpp:138
static const unsigned char REJECT_CHECKPOINT
Definition: validation.h:19
static CuckooCache::cache< uint256, SignatureCacheHasher > scriptExecutionCache
void UpdateTransactionsFromBlock(const std::vector< uint256 > &vHashesToUpdate)
When adding transactions from a disconnected block back to the mempool, new mempool entries may have ...
Definition: txmempool.cpp:111
uint256 g_best_block
Definition: validation.cpp:221
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &headers, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex, CBlockHeader *first_invalid)
Process incoming block headers.
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:69
static const std::string MAIN
BIP70 chain name strings (main, test or regtest)
void check(const CCoinsViewCache *pcoins) const
If sanity-checking is turned on, check makes sure the pool is consistent (does not contain two transa...
Definition: txmempool.cpp:1013
int nSubsidyHalvingInterval
Definition: params.h:133
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
CInstantSendManager * quorumInstantSendManager
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:300
int64_t nTxCount
Definition: chainparams.h:30
static constexpr int MAX_BLOCK_COINSDB_USAGE
No need to periodic flush if at least this much space still available.
Definition: txdb.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:141
bool fSpentIndex
Definition: validation.cpp:228
uint256 GetBlockHash() const
Definition: chain.h:292
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:142
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
Definition: ui_interface.h:105
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyHeaderTip
Best header has changed.
Definition: ui_interface.h:108
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:332
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:249
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object&#39;s serialization.
Definition: hash.h:254
Removed in size limiting.
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:795
bool UndoSpecialTxsInBlock(const CBlock &block, const CBlockIndex *pindex)
Definition: specialtx.cpp:150
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
Definition: streams.h:638
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
void fclose()
Definition: streams.h:433
conflicts with chainlock system
Definition: chain.h:162
iterator end()
Definition: prevector.h:320
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: utiltime.cpp:22
static const uint32_t MEMPOOL_HEIGHT
Fake height value used in Coin to signify they are only in the memory pool (since 0...
Definition: txmempool.h:38
uint64_t PruneAfterHeight() const
Definition: chainparams.h:66
uint64_t GetPos() const
Definition: streams.h:606
bool GetUTXOCoin(const COutPoint &outpoint, Coin &coin)
Definition: validation.cpp:439
bool IsPayToPublicKey() const
Used for obsolete pay-to-pubkey addresses indexing.
Definition: script.cpp:221
#define LOCK2(cs1, cs2)
Definition: sync.h:179
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:35
PrevBlockMap & mapPrevBlockIndex
Definition: validation.cpp:216
iterator end()
Definition: indirectmap.h:49
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:145
static CDiskBlockPos SaveBlockToDisk(const CBlock &block, int nHeight, const CChainParams &chainparams, const CDiskBlockPos *dbp)
Store block on disk.
bool fCheckpointsEnabled
Definition: validation.cpp:235
bool ReplayBlocks(const CChainParams &params, CCoinsView *view)
Replay blocks that aren&#39;t fully applied to the database.
bool ProcessSpecialTxsInBlock(const CBlock &block, const CBlockIndex *pindex, CValidationState &state, bool fJustCheck, bool fCheckCbTxMerleRoots)
Definition: specialtx.cpp:94
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: chain.h:220
PrevBlockMap mapPrevBlockIndex
Definition: validation.cpp:161
std::size_t size_t
Definition: bits.hpp:21
CChainLocksHandler * chainLocksHandler
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:1116
#define LogPrintf(...)
Definition: util.h:203
uint64_t nTimeFirst
earliest time of block in file
Definition: chain.h:39
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:317
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
static void NotifyHeaderTip()
CCriticalSection cs_nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Definition: validation.cpp:130
CBlockIndex * InsertBlockIndex(const uint256 &hash)
Create a new block index entry for a given block hash.
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
Definition: chain.h:148
Access to the block database (blocks/index/)
Definition: txdb.h:114
uint256 hashMerkleRoot
Definition: block.h:26
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: validation.h:78
bool IsInvalid() const
Definition: validation.h:64
static int64_t nTimeChainState
int nSuperblockStartBlock
Definition: params.h:142
Abstract view on the open txout dataset.
Definition: coins.h:145
void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
Definition: txmempool.cpp:1347
static int64_t nTimeTotal
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:246
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:218
unsigned int nDataPos
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:189
DeploymentPos
Definition: params.h:15
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:811
static constexpr unsigned int LOCKTIME_MEDIAN_TIME_PAST
Use GetMedianTimePast() instead of nTime for end point timestamp.
Definition: consensus.h:30
An input of a transaction.
Definition: transaction.h:70
bool LoadGenesisBlock(const CChainParams &chainparams)
static const int64_t MAX_FEE_ESTIMATION_TIP_AGE
Maximum age of our tip in seconds for us to be considered current for fee estimation.
Definition: validation.h:116
void RemoveChainLockConflictingLock(const uint256 &islockHash, const CInstantSendLock &islock)
ConnectTrace(CTxMemPool &_pool)
int VersionBitsStateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
#define LOCK(cs)
Definition: sync.h:178
bool CheckBlock(const CBlock &block, CValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
Functions for validating blocks and updating the block tree.
We want to be able to estimate feerates that are needed on tx&#39;s to be included in a certain number of...
Definition: fees.h:138
bool CheckTxInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:211
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:168
const uint256 & GetHash() const
Definition: transaction.h:256
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:299
static CCheckQueue< CScriptCheck > scriptcheckqueue(128)
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs, const CChainParams &params)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied...
static const unsigned int DEFAULT_BYTES_PER_SIGOP
Definition: validation.h:120
unsigned int MaxBlockSigOps(bool fDIP0001Active)
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: consensus.h:17
CBlockIndex * pindexBestInvalid
Definition: validation.cpp:163
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:149
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:471
uint256 uint256S(const char *str)
Definition: uint256.h:143
std::map< uint256, CAmount > mapDeltas
Definition: txmempool.h:539
static const unsigned char REJECT_NONSTANDARD
Definition: validation.h:16
static bool WriteUndoDataForBlock(const CBlockUndo &blockundo, CValidationState &state, CBlockIndex *pindex, const CChainParams &chainparams)
std::shared_ptr< CInstantSendLock > CInstantSendLockPtr
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:476
Abstract class that implements BIP9-style threshold logic, and caches results.
Definition: versionbits.h:55
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
static bool CheckInputsFromMempoolAndCache(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool &pool, unsigned int flags, bool cacheSigStore, PrecomputedTransactionData &txdata)
Definition: validation.cpp:587
uint256 hashPrevBlock
Definition: block.h:25
int DIP0003Height
Block height at which DIP0003 becomes active.
Definition: params.h:158
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: validation.h:80
std::string GetRejectReason() const
Definition: validation.h:81
CAmount GetMasternodePayment(int nHeight, CAmount blockValue, int nReallocActivationHeight)
uint32_t n
Definition: transaction.h:30
static int64_t nTimeIndex
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:674
const std::vector< CTxOut > vout
Definition: transaction.h:216
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:70
bool DisconnectTip(CValidationState &state, const CChainParams &chainparams, DisconnectedBlockTransactions *disconnectpool)
Disconnect chainActive&#39;s tip.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:72
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: util.cpp:1151
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:141
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
static int64_t nTimeProcessSpecial
std::shared_ptr< const CBlock > pblock
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:92
std::atomic< bool > fDIP0001ActiveAtTip
Definition: validation.cpp:240
CMainSignals & GetMainSignals()
bool ContextualCheckTransaction(const CTransaction &tx, CValidationState &state, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
Definition: validation.cpp:465
bool IsError() const
Definition: validation.h:67
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:12
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
bool ConnectTip(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool)
Connect a new block to chainActive.
unsigned int nHeightFirst
lowest height of block in file
Definition: chain.h:37
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:115
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:55
CInstantSendLockPtr GetConflictingLock(const CTransaction &tx)
int VersionBitsTipStateSinceHeight(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the block height at which the BIP9 deployment switched into the state for the block building on t...
bool exists(uint256 hash) const
Definition: txmempool.h:672
bool TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:349
bool operator()()
std::string ToString() const
Definition: chain.h:118
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
An output of a transaction.
Definition: transaction.h:144
void SetNull()
Definition: block.h:48
void AcceptedBlockHeader(const CBlockIndex *pindexNew)
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:154
std::string ToString() const
Definition: uint256.cpp:62
std::vector< uint256 > vHave
Definition: block.h:129
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data)
Returns last CBlockIndex* in mapBlockIndex that is a checkpoint.
Definition: checkpoints.cpp:18
uint32_t nMinerConfirmationWindow
Definition: params.h:170
bool SetPos(uint64_t nPos)
Definition: streams.h:611
static const std::string DEVNET
class CMainCleanup instance_of_cmaincleanup
bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Definition: validation.cpp:908
Queue for verifications that have to be performed.
Definition: checkqueue.h:30
Parameters that influence chain consensus.
Definition: params.h:130
CBlockIndex * FindMostWorkChain()
Return the tip of the chain with the most work in it, that isn&#39;t known to be invalid (it&#39;s however fa...
void ThreadScriptCheck()
Run an instance of the script checking thread.
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:233
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:255
int64_t GetBlockTime() const
Definition: block.h:65
BlockMap mapBlockIndex
Definition: validation.cpp:160
bool IsNull() const
Definition: chain.h:116
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:356
static const unsigned char REJECT_DUPLICATE
Definition: validation.h:15
bool fTxIndex
Definition: validation.cpp:225
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:1470
static void CheckBlockIndex(const Consensus::Params &consensusParams)
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:1069
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.cpp:136
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)
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.cpp:367
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download...
Definition: validation.cpp:238
256-bit unsigned big integer.
int64_t GetMedianTimePast() const
Definition: chain.h:309
CCriticalSection cs
Definition: txmempool.h:488
unsigned int nPos
Definition: chain.h:88
VersionBitsCache versionbitscache
static int64_t nTimeCallbacks
static int64_t nTimeCheck
void BlockConnected(CBlockIndex *pindex, std::shared_ptr< const CBlock > pblock)
bool ResetBlockFailureFlags(CBlockIndex *pindex)
static const unsigned int DATABASE_WRITE_INTERVAL
Time to wait (in seconds) between writing blocks/block index to disk.
Definition: validation.h:104
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:243
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:38
static int64_t nTimeConnect
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
Definition: versionbits.h:31
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:371
const int16_t nVersion
Definition: transaction.h:217
int BIP65Height
Block height at which BIP65 becomes active.
Definition: params.h:152
static int64_t nTimeReadFromDisk
static bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown=false)
static constexpr size_t MESSAGE_START_SIZE
Definition: protocol.h:31
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk, initializing state if we&#39;re running with -reindex...
void UnloadBlockIndex()
bool Error(const std::string &strRejectReasonIn)
Definition: validation.h:55
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:135
unsigned int nUndoPos
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:192
CSporkManager sporkManager
Definition: spork.cpp:29
std::shared_ptr< std::vector< CTransactionRef > > conflictedTxs
int32_t nBlockSequenceId
Blocks loaded from disk are assigned id 0, so start the counter at 1.
Definition: validation.cpp:132
#define LogPrint(category,...)
Definition: util.h:214
uint256 GetHash() const
Definition: block.cpp:14
int32_t nVersion
block header
Definition: chain.h:210
bool IsBlockValueValid(const CBlock &block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet)
IsBlockValueValid.
Capture information about block/transaction validation.
Definition: validation.h:22
class CChainState g_chainstate
256-bit opaque blob.
Definition: uint256.h:123
bool fCheckBlockIndex
Definition: validation.cpp:234
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
static bool AcceptToMemoryPoolWithTime(const CChainParams &chainparams, CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, int64_t nAcceptTime, bool bypass_limits, const CAmount nAbsurdFee, bool fDryRun)
(try to) add transaction to memory pool with a specified acceptance time
Definition: validation.cpp:873
const CTransaction * ptxTo
Definition: validation.h:375
ArgsManager gArgs
Definition: util.cpp:108
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:121
std::vector< CTransactionRef > vtx
Definition: block.h:76
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:451
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:513
std::atomic< bool > fDIP0003ActiveAtTip
Definition: validation.cpp:241
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:11
static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
const ChainTxData & TxData() const
Definition: chainparams.h:83
static const unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:44
ThresholdState GetStateFor(const CBlockIndex *pindexPrev, const Consensus::Params &params, ThresholdConditionCache &cache) const
Definition: versionbits.cpp:46
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:442
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
bool fRequireStandard
Definition: validation.cpp:232
static const int64_t MAX_MAX_SIG_CACHE_SIZE
Definition: sigcache.h:18
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API...
Definition: sync.h:54
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.cpp:134
bool CheckInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData &txdata, std::vector< CScriptCheck > *pvChecks=nullptr)
Check whether all inputs of this transaction are valid (no double spends, scripts & sigs...
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:107
void FindByte(char ch)
Definition: streams.h:653
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
void SetNull()
Definition: block.h:100
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
bool ConnectBlock(const CBlock &block, CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, const CChainParams &chainparams, bool fJustCheck=false)
Apply the effects of this block (with given index) on the UTXO set represented by coins...
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:12
Undo information for a CBlock.
Definition: undo.h:98
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:389
boost::signals2::signal< void()> NotifyAlertChanged
Status bar alerts changed.
Definition: ui_interface.h:93
bool LoadBlockIndex(const Consensus::Params &consensus_params, CBlockTreeDB &blocktree)
int GetUTXOConfirmations(const COutPoint &outpoint)
Definition: validation.cpp:456
Undo information for a CTransaction.
Definition: undo.h:66
std::atomic_bool fImporting(false)
std::vector< PerBlockConnectTrace > blocksConnected
bool GetfLargeWorkForkFound()
Definition: warnings.cpp:29
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:14
#define MILLI
Definition: validation.cpp:66
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: utiltime.cpp:56
CDiskBlockPos GetUndoPos() const
Definition: chain.h:270
void InitScriptExecutionCache()
Initializes the script-execution cache.
static const int32_t VERSIONBITS_TOP_BITS
What bits to set in version for versionbits blocks.
Definition: versionbits.h:14
CChain chainActive
Definition: validation.cpp:159
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, bool bypass_limits, const CAmount nAbsurdFee, bool fDryRun)
(try to) add transaction to memory pool
Definition: validation.cpp:890
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:808
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:284
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
bool TestBlockValidity(CValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
Check a block is completely valid from start to finish (only works on top of our current best block...
void NotifyInstantSendDoubleSpendAttempt(const CTransaction &currentTx, const CTransaction &previousTx)
void runCommand(const std::string &strCommand)
Definition: util.cpp:1236
bool LoadMempool(void)
Load the mempool from disk.
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
static const bool DEFAULT_TIMESTAMPINDEX
Definition: validation.h:124
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:453
sph_u32 low
Definition: keccak.c:370
bool HasConflictingChainLock(int nHeight, const uint256 &blockHash)
static int64_t nTimeValueValid
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and a...
Definition: validation.cpp:124
void SetMiscWarning(const std::string &strWarning)
Definition: warnings.cpp:17
static int64_t nTimeVerify
static int64_t nTimePostConnect
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
unsigned int nBlocks
number of blocks stored in file
Definition: chain.h:34
160-bit opaque blob.
Definition: uint256.h:112
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
Definition: chain.cpp:23
std::set< CBlockIndex * > g_failed_blocks
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to conn...
Definition: validation.cpp:156
#define AssertLockNotHeld(cs)
Definition: sync.h:88
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:301
static int count
Definition: tests.c:45
static bool IsCurrentForFeeEstimation()
Definition: validation.cpp:521
std::string GetDebugMessage() const
Definition: validation.h:82
bool error(const char *fmt, const Args &... args)
Definition: util.h:222
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:342
iterator begin()
Definition: prevector.h:318
unsigned int GetRejectCode() const
Definition: validation.h:80
bool LoadBlockIndexGuts(const Consensus::Params &consensusParams, std::function< CBlockIndex *(const uint256 &)> insertBlockIndex)
Definition: txdb.cpp:416
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: ui_interface.h:76
bool GetAddressIndex(uint160 addressHash, int type, std::vector< std::pair< CAddressIndexKey, CAmount > > &addressIndex, int start, int end)
Definition: validation.cpp:922
bool IsStandardTx(const CTransaction &tx, std::string &reason)
Check for standard transaction types.
Definition: policy.cpp:62
static bool AcceptToMemoryPoolWorker(const CChainParams &chainparams, CTxMemPool &pool, CValidationState &state, const CTransactionRef &ptx, bool *pfMissingInputs, int64_t nAcceptTime, bool bypass_limits, const CAmount &nAbsurdFee, std::vector< COutPoint > &coins_to_uncache, bool fDryRun)
Definition: validation.cpp:621
BlockStatus
Definition: chain.h:125
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:184
int64_t time
Definition: txmempool.h:46
uint32_t nRuleChangeActivationThreshold
Minimum blocks including miner confirmation of the total of nMinerConfirmationWindow blocks in a reta...
Definition: params.h:168
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:1211
unsigned int nIn
Definition: validation.h:376
bool CorruptionPossible() const
Definition: validation.h:77
bool getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Definition: txmempool.cpp:595
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time...
Definition: tx_verify.cpp:17
All validity bits.
Definition: chain.h:151
void SetBestChain(const CBlockLocator &)
boost::signals2::signal< void(CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved
Definition: txmempool.h:687
uint64_t nTimeLast
latest time of block in file
Definition: chain.h:40
bool AcceptBlockHeader(const CBlockHeader &block, CValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex)
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:928
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool validFeeEstimate=true)
Definition: txmempool.cpp:1424
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight)
Called when a block is connected.
Definition: txmempool.cpp:953
static const bool DEFAULT_SPENTINDEX
Definition: validation.h:125
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:121
FlushStateMode
Definition: validation.cpp:303
uint256 hashDevnetGenesisBlock
Definition: params.h:132
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
size_t DynamicMemoryUsage() const
Definition: txmempool.h:800
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
bool IsSporkActive(SporkId nSporkID)
IsSporkActive returns a bool for time-based sporks, and should be used to determine whether the spork...
Definition: spork.cpp:211
unsigned int nBytesPerSigOp
Definition: validation.cpp:233
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
int nMasternodePaymentsIncreasePeriod
Definition: params.h:136
static void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight)
WarningBitsConditionChecker(int bitIn)
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:54
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:152
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
#define MICRO
Definition: validation.cpp:65
const CBlock & DevNetGenesisBlock() const
Definition: chainparams.h:59
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
std::vector< PerBlockConnectTrace > & GetBlocksConnected()
void PruneAndFlush()
Prune block files and flush state to disk.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:110
bool fChecked
Definition: block.h:79
full block available in blk*.dat
Definition: chain.h:154
DisconnectResult
Definition: validation.cpp:94
static const unsigned int DATABASE_FLUSH_INTERVAL
Time to wait (in seconds) between flushing chainstate to disk.
Definition: validation.h:106
CAmount GetBlockSubsidy(int nPrevBits, int nPrevHeight, const Consensus::Params &consensusParams, bool fSuperblockPartOnly)
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
Definition: validation.h:50
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from...
Definition: streams.h:519
AssertLockHeld(g_cs_orphans)
A hasher class for SHA-256.
Definition: sha256.h:13
uint64_t CalculateCurrentUsage()
BLOCK PRUNING CODE.
std::unique_lock< std::mutex > WaitableLock
Just a typedef for std::unique_lock, can be wrapped later if desired.
Definition: sync.h:109
static void UpdateTip(const CBlockIndex *pindexNew, const CChainParams &chainParams)
Check warning conditions and do some notifications on new chain tip set.
static int64_t nTimeSubsidy
void addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view)
Definition: txmempool.cpp:468
CBlockIndex * AddToBlockIndex(const CBlockHeader &block, enum BlockStatus nStatus=BLOCK_VALID_TREE)
std::vector< CTxUndo > vtxundo
Definition: undo.h:101
int nFile
Definition: chain.h:87
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
COutPoint prevout
Definition: transaction.h:73
std::string ToString() const
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
void SetfLargeWorkForkFound(bool flag)
Definition: warnings.cpp:23
static void LimitMempoolSize(CTxMemPool &pool, size_t limit, unsigned long age)
Definition: validation.cpp:500
static const int32_t VERSIONBITS_NUM_BITS
Total bits available for versionbits.
Definition: versionbits.h:18
static const int CLIENT_VERSION
dashd-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
boost::signals2::signal< void(const std::string &title, int nProgress, bool resume_possible)> ShowProgress
Show progress e.g.
Definition: ui_interface.h:102
CBlockIndex * maxInputBlock
Definition: txmempool.h:50
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
const int16_t nType
Definition: transaction.h:218
static int64_t nBlocksTotal
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:739
double getdouble() const
int32_t nVersion
Definition: block.h:24
bool GetTimestampIndex(const unsigned int &high, const unsigned int &low, std::vector< uint256 > &hashes)
Definition: validation.cpp:897
bool IsPayToPublicKeyHash() const
Definition: script.cpp:201
iterator find(const K &key)
Definition: indirectmap.h:36
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
static int64_t nTimeFlush
static const bool DEFAULT_TXINDEX
Definition: validation.h:122
static unsigned int GetBlockScriptFlags(const CBlockIndex *pindex, const Consensus::Params &chainparams)
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:1317
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
Definition: txmempool.cpp:757
uint32_t nBits
Definition: chain.h:213
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:827
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
static bool CheckBlockHeader(const CBlockHeader &block, CValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true)
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
uint256 hashGenesisBlock
Definition: params.h:131
bool CheckSpecialTx(const CTransaction &tx, const CBlockIndex *pindexPrev, CValidationState &state)
Definition: specialtx.cpp:20
int nHighSubsidyBlocks
Definition: params.h:186
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:410
size_t nCoinCacheUsage
Definition: validation.cpp:236
CWaitableCriticalSection g_best_block_mutex
Definition: validation.cpp:219
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:92
Wrapped mutex: supports recursive locking, but no waiting TODO: We should move away from using the re...
Definition: sync.h:94
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
int DIP0001Height
Block height at which DIP0001 becomes active.
Definition: params.h:156
static const int64_t MAX_FUTURE_BLOCK_TIME
Maximum amount of time that a block timestamp is allowed to exceed the current network-adjusted time ...
Definition: chain.h:21
bool RewindBlockIndex(const CChainParams &params)
int64_t GetBlockProofEquivalentTime(const CBlockIndex &to, const CBlockIndex &from, const CBlockIndex &tip, const Consensus::Params &params)
Return the time it would take to redo the work difference between from and to, assuming the current h...
Definition: chain.cpp:136
uint32_t nBits
Definition: block.h:28
static const unsigned int REJECT_HIGHFEE
Too high fee.
Definition: validation.h:486
static int64_t nTimeISFilter
BIP9Stats VersionBitsStatistics(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
static void InvalidChainFound(CBlockIndex *pindexNew)
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params, bool fCheckMasternodesUpgraded)
Determine what nVersion a new block should use.
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
void BlockConnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex, const std::shared_ptr< const std::vector< CTransactionRef >> &)
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:125
bool eof() const
Definition: streams.h:579
static uint256 scriptExecutionCacheNonce(GetRandHash())
static void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
uint256 hash
Definition: transaction.h:29
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:174
PrecomputedTransactionData * txdata
Definition: validation.h:380
static const unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we&#39;re willing to relay/mine.
Definition: policy.h:24
static const unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS
For convenience, standard but not mandatory verify flags.
Definition: policy.h:57
Threshold condition checker that triggers when unknown versionbits are seen on the network...
Released under the MIT license