Fabcoin Core  0.16.2
P2P Digital Currency
validation.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <validation.h>
7 
8 #include <arith_uint256.h>
9 #include <chain.h>
10 #include <chainparams.h>
11 #include <checkpoints.h>
12 #include <checkqueue.h>
13 #include <consensus/consensus.h>
14 #include <consensus/merkle.h>
15 #include <consensus/tx_verify.h>
16 #include <consensus/validation.h>
17 #include <cuckoocache.h>
18 #include <fs.h>
19 #include <hash.h>
20 #include <init.h>
21 #include <policy/fees.h>
22 #include <policy/policy.h>
23 #include <policy/rbf.h>
24 #include <pow.h>
25 #include <primitives/block.h>
26 #include <primitives/transaction.h>
27 #include <random.h>
28 #include <reverse_iterator.h>
29 #include <script/script.h>
30 #include <script/sigcache.h>
31 #include <script/standard.h>
32 #include <timedata.h>
33 #include <tinyformat.h>
34 #include <txdb.h>
35 #include <txmempool.h>
36 #include <ui_interface.h>
37 #include <undo.h>
38 #include <util.h>
39 #include <utilmoneystr.h>
40 #include <utilstrencodings.h>
41 #include <validationinterface.h>
42 #include <versionbits.h>
43 #include <warnings.h>
44 #include <serialize.h>
45 #include <pubkey.h>
46 #include <key.h>
47 #include <wallet/wallet.h>
48 
49 #include <atomic>
50 #include <sstream>
51 
52 #include <boost/algorithm/string/replace.hpp>
53 #include <boost/algorithm/string/join.hpp>
54 #include <boost/thread.hpp>
55 
56 #if defined(NDEBUG)
57 # error "Fabcoin cannot be compiled without assertions."
58 #endif
59 
64 #include <iostream>
66 #include <bitset>
67 #include <pubkey.h>
68 #include <univalue.h>
69 
70 std::unique_ptr<FascState> globalState;
71 std::shared_ptr<dev::eth::SealEngineFace> globalSealEngine;
72 bool fRecordLogOpcodes = false;
73 bool fIsVMlogFile = false;
74 bool fGettingValuesDGP = false;
76 
78 
85 std::atomic_bool fImporting(false);
86 bool fReindex = false;
87 bool fTxIndex = false;
88 bool fLogEvents = false;
89 bool fHavePruned = false;
90 bool fPruneMode = false;
91 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
92 bool fRequireStandard = true;
93 bool fCheckBlockIndex = false;
94 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
95 size_t nCoinCacheUsage = 5000 * 300;
96 uint64_t nPruneTarget = 0;
97 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
98 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
99 
102 
103 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
104 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
105 
107 CTxMemPool mempool(&feeEstimator);
108 
109 static void CheckBlockIndex(const Consensus::Params& consensusParams);
110 static bool UpdateHashProof(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex* pindex, CCoinsViewCache& view);
111 
114 
115 const std::string strMessageMagic = "Bitcoin Signed Message:\n";
116 extern bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime);
117 extern std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);
118 extern bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair);
119 extern bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block);
120 extern unsigned int GetLegacySigOpCount(const CTransaction& tx);
121 extern unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs);
122 extern int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags);
123 extern int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags);
124 extern bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs);
125 
126 // Internal stuff
127 namespace {
128 
129  struct CBlockIndexWorkComparator
130  {
131  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
132  // First sort by most total work, ...
133  if (pa->nChainWork > pb->nChainWork) return false;
134  if (pa->nChainWork < pb->nChainWork) return true;
135 
136  // ... then by earliest time received, ...
137  if (pa->nSequenceId < pb->nSequenceId) return false;
138  if (pa->nSequenceId > pb->nSequenceId) return true;
139 
140  // Use pointer address as tie breaker (should only happen with blocks
141  // loaded from disk, as those all have id 0).
142  if (pa < pb) return false;
143  if (pa > pb) return true;
144 
145  // Identical blocks.
146  return false;
147  }
148  };
149 
150  CBlockIndex *pindexBestInvalid;
151 
157  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
161  std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
162 
163  CCriticalSection cs_LastBlockFile;
164  std::vector<CBlockFileInfo> vinfoBlockFile;
165  int nLastBlockFile = 0;
170  bool fCheckForPruning = false;
171 
176  CCriticalSection cs_nBlockSequenceId;
178  int32_t nBlockSequenceId = 1;
180  int32_t nBlockReverseSequenceId = -1;
182  arith_uint256 nLastPreciousChainwork = 0;
183 
202  std::set<CBlockIndex*> g_failed_blocks;
203 
205  std::set<CBlockIndex*> setDirtyBlockIndex;
206 
208  std::set<int> setDirtyFileInfo;
209 } // anon namespace
210 
212 {
213 private:
214  std::vector<CTransactionRef> conflictedTxs;
216 public:
218  pool.NotifyEntryRemoved.connect(boost::bind(&MemPoolConflictRemovalTracker::NotifyEntryRemoved, this, _1, _2));
219  }
221  if (reason == MemPoolRemovalReason::CONFLICT) {
222  conflictedTxs.push_back(txRemoved);
223  }
224  }
226  pool.NotifyEntryRemoved.disconnect(boost::bind(&MemPoolConflictRemovalTracker::NotifyEntryRemoved, this, _1, _2));
227  for (const auto& tx : conflictedTxs) {
229  }
230  conflictedTxs.clear();
231  }
232 };
234 {
235  // Find the first block the caller has in the main chain
236  for (const uint256& hash : locator.vHave) {
237  BlockMap::iterator mi = mapBlockIndex.find(hash);
238  if (mi != mapBlockIndex.end())
239  {
240  CBlockIndex* pindex = (*mi).second;
241  if (chain.Contains(pindex))
242  return pindex;
243  if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
244  return chain.Tip();
245  }
246  }
247  }
248  return chain.Genesis();
249 }
250 
255 
261 };
262 
263 // See definition for documentation
264 static int GetWitnessCommitmentIndex(const CBlock& block);
265 static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
266 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
267 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
268 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);
269 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
270 
271 bool CheckFinalTx(const CTransaction &tx, int flags)
272 {
273  AssertLockHeld(cs_main);
274 
275  // By convention a negative value for flags indicates that the
276  // current network-enforced consensus rules should be used. In
277  // a future soft-fork scenario that would mean checking which
278  // rules would be enforced for the next block and setting the
279  // appropriate flags. At the present time no soft-forks are
280  // scheduled, so no flags are set.
281  flags = std::max(flags, 0);
282 
283  // CheckFinalTx() uses chainActive.Height()+1 to evaluate
284  // nLockTime because when IsFinalTx() is called within
285  // CBlock::AcceptBlock(), the height of the block *being*
286  // evaluated is what is used. Thus if we want to know if a
287  // transaction can be part of the *next* block, we need to call
288  // IsFinalTx() with one more than chainActive.Height().
289  const int nBlockHeight = chainActive.Height() + 1;
290 
291  // BIP113 will require that time-locked transactions have nLockTime set to
292  // less than the median time of the previous block they're contained in.
293  // When the next block is created its previous block will be the current
294  // chain tip, so we use that to calculate the median time passed to
295  // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
296  const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
297  ? chainActive.Tip()->GetMedianTimePast()
298  : GetAdjustedTime();
299 
300  return IsFinalTx(tx, nBlockHeight, nBlockTime);
301 }
302 
304 {
305  AssertLockHeld(cs_main);
306  assert(lp);
307  // If there are relative lock times then the maxInputBlock will be set
308  // If there are no relative lock times, the LockPoints don't depend on the chain
309  if (lp->maxInputBlock) {
310  // Check whether chainActive is an extension of the block at which the LockPoints
311  // calculation was valid. If not LockPoints are no longer valid
312  if (!chainActive.Contains(lp->maxInputBlock)) {
313  return false;
314  }
315  }
316 
317  // LockPoints still valid
318  return true;
319 }
320 
321 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
322 {
323  AssertLockHeld(cs_main);
325 
326  CBlockIndex* tip = chainActive.Tip();
327  CBlockIndex index;
328  index.pprev = tip;
329  // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
330  // height based locks because when SequenceLocks() is called within
331  // ConnectBlock(), the height of the block *being*
332  // evaluated is what is used.
333  // Thus if we want to know if a transaction can be part of the
334  // *next* block, we need to use one more than chainActive.Height()
335  index.nHeight = tip->nHeight + 1;
336 
337  std::pair<int, int64_t> lockPair;
338  if (useExistingLockPoints) {
339  assert(lp);
340  lockPair.first = lp->height;
341  lockPair.second = lp->time;
342  }
343  else {
344  // pcoinsTip contains the UTXO set for chainActive.Tip()
345  CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
346  std::vector<int> prevheights;
347  prevheights.resize(tx.vin.size());
348  for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
349  const CTxIn& txin = tx.vin[txinIndex];
350  Coin coin;
351  if (!viewMemPool.GetCoin(txin.prevout, coin)) {
352  return error("%s: Missing input", __func__);
353  }
354  if (coin.nHeight == MEMPOOL_HEIGHT) {
355  // Assume all mempool transaction confirm in the next block
356  prevheights[txinIndex] = tip->nHeight + 1;
357  } else {
358  prevheights[txinIndex] = coin.nHeight;
359  }
360  }
361  lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
362  if (lp) {
363  lp->height = lockPair.first;
364  lp->time = lockPair.second;
365  // Also store the hash of the block with the highest height of
366  // all the blocks which have sequence locked prevouts.
367  // This hash needs to still be on the chain
368  // for these LockPoint calculations to be valid
369  // Note: It is impossible to correctly calculate a maxInputBlock
370  // if any of the sequence locked inputs depend on unconfirmed txs,
371  // except in the special case where the relative lock time/height
372  // is 0, which is equivalent to no sequence lock. Since we assume
373  // input height of tip+1 for mempool txs and test the resulting
374  // lockPair from CalculateSequenceLocks against tip+1. We know
375  // EvaluateSequenceLocks will fail if there was a non-zero sequence
376  // lock on a mempool input, so we can use the return value of
377  // CheckSequenceLocks to indicate the LockPoints validity
378  int maxInputHeight = 0;
379  for (int height : prevheights) {
380  // Can ignore mempool inputs since we'll fail if they had non-zero locks
381  if (height != tip->nHeight+1) {
382  maxInputHeight = std::max(maxInputHeight, height);
383  }
384  }
385  lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
386  }
387  }
388  return EvaluateSequenceLocks(index, lockPair);
389 }
390 
391 // Returns the script flags which should be checked for a given block
392 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
393 
394 static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
395  int expired = pool.Expire(GetTime() - age);
396  if (expired != 0) {
397  LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
398  }
399 
400  std::vector<COutPoint> vNoSpendsRemaining;
401  pool.TrimToSize(limit, &vNoSpendsRemaining);
402  for (const COutPoint& removed : vNoSpendsRemaining)
403  pcoinsTip->Uncache(removed);
404 }
405 
407 std::string FormatStateMessage(const CValidationState &state)
408 {
409  return strprintf("%s%s (code %i)",
410  state.GetRejectReason(),
411  state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
412  state.GetRejectCode());
413 }
414 
415 static bool IsCurrentForFeeEstimation()
416 {
417  AssertLockHeld(cs_main);
419  return false;
420  if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
421  return false;
422  if (chainActive.Height() < pindexBestHeader->nHeight - 1)
423  return false;
424  return true;
425 }
426 
427 bool static IsFABHardForkEnabled(int nHeight, const Consensus::Params& params) {
428  return (uint32_t)nHeight >= (uint32_t)params.FABHeight;
429 }
430 
431 bool IsFABHardForkEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params) {
432  if (pindexPrev == nullptr) {
433  return false;
434  }
435 
436  return IsFABHardForkEnabled(pindexPrev->nHeight, params);
437 }
438 
440  AssertLockHeld(cs_main);
441  return IsFABHardForkEnabled(chainActive.Tip(), params);
442 }
443 
444 /* Make mempool consistent after a reorg, by re-adding or recursively erasing
445  * disconnected block transactions from the mempool, and also removing any
446  * other transactions from the mempool that are no longer valid given the new
447  * tip/height.
448  *
449  * Note: we assume that disconnectpool only contains transactions that are NOT
450  * confirmed in the current chain nor already in the mempool (otherwise,
451  * in-mempool descendants of such transactions would be removed).
452  *
453  * Passing fAddToMempool=false will skip trying to add the transactions back,
454  * and instead just erase from the mempool as needed.
455  */
456 
457 void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
458 {
459  AssertLockHeld(cs_main);
460  std::vector<uint256> vHashUpdate;
461  // disconnectpool's insertion_order index sorts the entries from
462  // oldest to newest, but the oldest entry will be the last tx from the
463  // latest mined block that was disconnected.
464  // Iterate disconnectpool in reverse, so that we add transactions
465  // back to the mempool starting with the earliest transaction that had
466  // been previously seen in a block.
467  auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
468  while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
469  // ignore validation errors in resurrected transactions
470  CValidationState stateDummy;
471  if (!fAddToMempool || (*it)->IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, *it, false, nullptr, nullptr, true)) {
472  // If the transaction doesn't make it in to the mempool, remove any
473  // transactions that depend on it (which would now be orphans).
475  } else if (mempool.exists((*it)->GetHash())) {
476  vHashUpdate.push_back((*it)->GetHash());
477  }
478  ++it;
479  }
480  disconnectpool.queuedTx.clear();
481  // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
482  // no in-mempool children, which is generally not true when adding
483  // previously-confirmed transactions back to the mempool.
484  // UpdateTransactionsFromBlock finds descendants of any transactions in
485  // the disconnectpool that were added back and cleans up the mempool state.
487 
488  // We also need to remove any now-immature transactions
489  mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
490  // Re-limit mempool size, in case we added any transactions
491  LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
492 }
493 
494 // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
495 // were somehow broken and returning the wrong scriptPubKeys
496 static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
497  unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
498  AssertLockHeld(cs_main);
499 
500  // pool.cs should be locked already, but go ahead and re-take the lock here
501  // to enforce that mempool doesn't change between when we check the view
502  // and when we actually call through to CheckInputs
503  LOCK(pool.cs);
504 
505  assert(!tx.IsCoinBase());
506  for (const CTxIn& txin : tx.vin) {
507  const Coin& coin = view.AccessCoin(txin.prevout);
508 
509  // At this point we haven't actually checked if the coins are all
510  // available (or shouldn't assume we have, since CheckInputs does).
511  // So we just return failure if the inputs are not available here,
512  // and then only have to check equivalence for available inputs.
513  if (coin.IsSpent()) return false;
514 
515  const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
516  if (txFrom) {
517  assert(txFrom->GetHash() == txin.prevout.hash);
518  assert(txFrom->vout.size() > txin.prevout.n);
519  assert(txFrom->vout[txin.prevout.n] == coin.out);
520  } else {
521  const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
522  assert(!coinFromDisk.IsSpent());
523  assert(coinFromDisk.out == coin.out);
524  }
525  }
526 
527  return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
528 }
529 
530 static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx, bool fLimitFree,
531  bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
532  bool fOverrideMempoolLimit, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache, bool rawTx)
533 {
534  const CTransaction& tx = *ptx;
535  const uint256 hash = tx.GetHash();
536  AssertLockHeld(cs_main);
537  if (pfMissingInputs)
538  *pfMissingInputs = false;
539 
540  if (!CheckTransaction(tx, state))
541  return false; // state filled in by CheckTransaction
542 
543  // Coinbase is only valid in a block, not as a loose transaction
544  if (tx.IsCoinBase())
545  return state.DoS(100, false, REJECT_INVALID, "coinbase");
546 
547  // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
548  bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
549  if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
550  return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
551  }
552 
553  // Rather not work on nonstandard transactions (unless -testnet/-regtest)
554  std::string reason;
555  if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
556  return state.DoS(0, false, REJECT_NONSTANDARD, reason);
557 
558  // Only accept nLockTime-using transactions that can be mined in the next
559  // block; we don't want our mempool filled up with transactions that can't
560  // be mined yet.
561  if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
562  return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
563 
564  // is it already in the memory pool?
565  if (pool.exists(hash)) {
566  return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
567  }
568 
569  // Check for conflicts with in-memory transactions
570  std::set<uint256> setConflicts;
571  {
572  LOCK(pool.cs); // protect pool.mapNextTx
573  for (const CTxIn &txin : tx.vin)
574  {
575  auto itConflicting = pool.mapNextTx.find(txin.prevout);
576  if (itConflicting != pool.mapNextTx.end())
577  {
578  const CTransaction *ptxConflicting = itConflicting->second;
579  if (!setConflicts.count(ptxConflicting->GetHash()))
580  {
581  // Allow opt-out of transaction replacement by setting
582  // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
583  //
584  // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
585  // non-replaceable transactions. All inputs rather than just one
586  // is for the sake of multi-party protocols, where we don't
587  // want a single party to be able to disable replacement.
588  //
589  // The opt-out ignores descendants as anyone relying on
590  // first-seen mempool behavior should be checking all
591  // unconfirmed ancestors anyway; doing otherwise is hopelessly
592  // insecure.
593  bool fReplacementOptOut = true;
594  if (fEnableReplacement)
595  {
596  for (const CTxIn &_txin : ptxConflicting->vin)
597  {
598  if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
599  {
600  fReplacementOptOut = false;
601  break;
602  }
603  }
604  }
605  if (fReplacementOptOut) {
606  return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
607  }
608 
609  setConflicts.insert(ptxConflicting->GetHash());
610  }
611  }
612  }
613  }
614 
615  {
616  CCoinsView dummy;
617  CCoinsViewCache view(&dummy);
618 
619  CAmount nValueIn = 0;
620  LockPoints lp;
621  {
622  LOCK(pool.cs);
623  CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
624  view.SetBackend(viewMemPool);
625 
626  // do we already have it?
627  for (size_t out = 0; out < tx.vout.size(); out++) {
628  COutPoint outpoint(hash, out);
629  bool had_coin_in_cache = pcoinsTip->HaveCoinInCache(outpoint);
630  if (view.HaveCoin(outpoint)) {
631  if (!had_coin_in_cache) {
632  coins_to_uncache.push_back(outpoint);
633  }
634  return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
635  }
636  }
637 
638  // do all inputs exist?
639  for (const CTxIn txin : tx.vin) {
640  if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
641  coins_to_uncache.push_back(txin.prevout);
642  }
643  if (!view.HaveCoin(txin.prevout)) {
644  // Are inputs missing because we already have the tx?
645  for (size_t out = 0; out < tx.vout.size(); out++) {
646  // Optimistically just do efficient check of cache for outputs
647  if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
648  return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
649  }
650  }
651  // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
652  if (pfMissingInputs) {
653  *pfMissingInputs = true;
654  }
655  return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
656  }
657  }
658 
659  // Bring the best block into scope
660  view.GetBestBlock();
661 
662  nValueIn = view.GetValueIn(tx);
663 
664  // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
665  view.SetBackend(dummy);
666 
667  // Only accept BIP68 sequence locked transactions that can be mined in the next
668  // block; we don't want our mempool filled up with transactions that can't
669  // be mined yet.
670  // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
671  // CoinsViewCache instead of create its own
672  if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
673  return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
674  }
675 
676  // Check for non-standard pay-to-script-hash in inputs
677  if (fRequireStandard && !AreInputsStandard(tx, view))
678  return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
679 
680  // Check for non-standard witness in P2WSH
681  if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
682  return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
683 
684  int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
685 
686  CAmount nValueOut = tx.GetValueOut();
687  CAmount nFees = nValueIn-nValueOut;
688  dev::u256 txMinGasPrice = 0;
690  if(tx.HasCreateOrCall()){
691 
692  if ( (uint32_t)chainActive.Tip()->nHeight < (uint32_t)Params().GetConsensus().ContractHeight ) {
693  return state.DoS(1, false, REJECT_INVALID, "bad-txns-invalid-contract-before-fork");
694  }
695 
696  if(!CheckSenderScript(view, tx)){
697  return state.DoS(1, false, REJECT_INVALID, "bad-txns-invalid-sender-script");
698  }
699 
700  FascDGP fascDGP(globalState.get(), fGettingValuesDGP);
701  uint64_t minGasPrice = fascDGP.getMinGasPrice(chainActive.Tip()->nHeight + 1);
702  uint64_t blockGasLimit = fascDGP.getBlockGasLimit(chainActive.Tip()->nHeight + 1);
703  size_t count = 0;
704  for(const CTxOut& o : tx.vout)
705  count += o.scriptPubKey.HasOpCreate() || o.scriptPubKey.HasOpCall() ? 1 : 0;
706  FascTxConverter converter(tx, nullptr);
707  ExtractFascTX resultConverter;
708  if(!converter.extractionFascTransactions(resultConverter)){
709  return state.DoS(100, error("AcceptToMempool(): Contract transaction of the wrong format"), REJECT_INVALID, "bad-tx-bad-contract-format");
710  }
711  std::vector<FascTransaction> fascTransactions = resultConverter.first;
712  std::vector<EthTransactionParams> fascETP = resultConverter.second;
713 
714  dev::u256 sumGas = dev::u256(0);
715  dev::u256 gasAllTxs = dev::u256(0);
716  for(FascTransaction fascTransaction : fascTransactions){
717  sumGas += fascTransaction.gas() * fascTransaction.gasPrice();
718 
719  if(sumGas > dev::u256(INT64_MAX)) {
720  return state.DoS(100, error("AcceptToMempool(): Transaction's gas stipend overflows"), REJECT_INVALID, "bad-tx-gas-stipend-overflow");
721  }
722 
723  if(sumGas > dev::u256(nFees)) {
724  return state.DoS(100, error("AcceptToMempool(): Transaction fee does not cover the gas stipend"), REJECT_INVALID, "bad-txns-fee-notenough");
725  }
726 
727  if(txMinGasPrice != 0) {
728  txMinGasPrice = std::min(txMinGasPrice, fascTransaction.gasPrice());
729  } else {
730  txMinGasPrice = fascTransaction.gasPrice();
731  }
732  VersionVM v = fascTransaction.getVersion();
733  if(v.format!=0)
734  return state.DoS(100, error("AcceptToMempool(): Contract execution uses unknown version format"), REJECT_INVALID, "bad-tx-version-format");
735  if(v.rootVM != 1)
736  return state.DoS(100, error("AcceptToMempool(): Contract execution uses unknown root VM"), REJECT_INVALID, "bad-tx-version-rootvm");
737  if(v.vmVersion != 0)
738  return state.DoS(100, error("AcceptToMempool(): Contract execution uses unknown VM version"), REJECT_INVALID, "bad-tx-version-vmversion");
739  if(v.flagOptions != 0)
740  return state.DoS(100, error("AcceptToMempool(): Contract execution uses unknown flag options"), REJECT_INVALID, "bad-tx-version-flags");
741 
742  //check gas limit is not less than minimum mempool gas limit
743  if(fascTransaction.gas() < gArgs.GetArg("-minmempoolgaslimit", MEMPOOL_MIN_GAS_LIMIT))
744  return state.DoS(100, error("AcceptToMempool(): Contract execution has lower gas limit than allowed to accept into mempool"), REJECT_INVALID, "bad-tx-too-little-mempool-gas");
745 
746  //check gas limit is not less than minimum gas limit (unless it is a no-exec tx)
747  if(fascTransaction.gas() < MINIMUM_GAS_LIMIT && v.rootVM != 0)
748  return state.DoS(100, error("AcceptToMempool(): Contract execution has lower gas limit than allowed"), REJECT_INVALID, "bad-tx-too-little-gas");
749 
750  if(fascTransaction.gas() > UINT32_MAX)
751  return state.DoS(100, error("AcceptToMempool(): Contract execution can not specify greater gas limit than can fit in 32-bits"), REJECT_INVALID, "bad-tx-too-much-gas");
752 
753  gasAllTxs += fascTransaction.gas();
754  if(gasAllTxs > dev::u256(blockGasLimit))
755  return state.DoS(1, false, REJECT_INVALID, "bad-txns-gas-exceeds-blockgaslimit");
756 
757  //don't allow less than DGP set minimum gas price to prevent MPoS greedy mining/spammers
758  if(v.rootVM!=0 && (uint64_t)fascTransaction.gasPrice() < minGasPrice)
759  return state.DoS(100, error("AcceptToMempool(): Contract execution has lower gas price than allowed"), REJECT_INVALID, "bad-tx-low-gas-price");
760  }
761 
762  if(!CheckMinGasPrice(fascETP, minGasPrice))
763  return state.DoS(100, false, REJECT_INVALID, "bad-txns-small-gasprice");
764 
765  if(count > fascTransactions.size())
766  return state.DoS(100, false, REJECT_INVALID, "bad-txns-incorrect-format");
767 
768  if (rawTx && nAbsurdFee && dev::u256(nFees) > dev::u256(nAbsurdFee) + sumGas){
769  LogPrintf("absurdly-high-fee nAbsurdFee=%d nFees=%d sumGas=%d\n ", nAbsurdFee , nFees , sumGas);
770  return state.Invalid(false,
771  REJECT_HIGHFEE, "absurdly-high-fee",
772  strprintf("%d > %d", nFees, nAbsurdFee));
773  }
774  }
776 
777  // nModifiedFees includes any fee deltas from PrioritiseTransaction
778  CAmount nModifiedFees = nFees;
779  pool.ApplyDelta(hash, nModifiedFees);
780 
781  // Keep track of transactions that spend a coinbase, which we re-scan
782  // during reorgs to ensure COINBASE_MATURITY is still met.
783  bool fSpendsCoinbase = false;
784  for (const CTxIn &txin : tx.vin) {
785  const Coin &coin = view.AccessCoin(txin.prevout);
786  if (coin.IsCoinBase()) {
787  fSpendsCoinbase = true;
788  break;
789  }
790  }
791 
792  CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
793  fSpendsCoinbase, nSigOpsCost, lp, CAmount(txMinGasPrice));
794  unsigned int nSize = entry.GetTxSize();
795 
796  // Check that the transaction doesn't have an excessive number of
797  // sigops, making it impossible to mine. Since the coinbase transaction
798  // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
799  // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
800  // merely non-standard transaction.
801  if (nSigOpsCost > dgpMaxTxSigOps)
802  return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
803  strprintf("%d", nSigOpsCost));
804 
805  CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
806  if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
807  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
808  }
809 
810  // No transactions are allowed below minRelayTxFee except from disconnected blocks
811  if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
812  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
813  }
814 
815  if (!tx.HasCreateOrCall() && nAbsurdFee && nFees > nAbsurdFee ) {
816  LogPrintf("absurdly-high-fee nAbsurdFee=%d nFees=%d \n", nAbsurdFee , nFees );
817  return state.Invalid(false,
818  REJECT_HIGHFEE, "absurdly-high-fee",
819  strprintf("%d > %d", nFees, nAbsurdFee));
820  }
821 
822  // Calculate in-mempool ancestors, up to a limit.
823  CTxMemPool::setEntries setAncestors;
824  size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
825  size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
826  size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
827  size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
828  std::string errString;
829  if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
830  return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
831  }
832 
833  // A transaction that spends outputs that would be replaced by it is invalid. Now
834  // that we have the set of all ancestors we can detect this
835  // pathological case by making sure setConflicts and setAncestors don't
836  // intersect.
837  for (CTxMemPool::txiter ancestorIt : setAncestors)
838  {
839  const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
840  if (setConflicts.count(hashAncestor))
841  {
842  return state.DoS(10, false,
843  REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
844  strprintf("%s spends conflicting transaction %s",
845  hash.ToString(),
846  hashAncestor.ToString()));
847  }
848  }
849 
850  // Check if it's economically rational to mine this transaction rather
851  // than the ones it replaces.
852  CAmount nConflictingFees = 0;
853  size_t nConflictingSize = 0;
854  uint64_t nConflictingCount = 0;
855  CTxMemPool::setEntries allConflicting;
856 
857  // If we don't hold the lock allConflicting might be incomplete; the
858  // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
859  // mempool consistency for us.
860  LOCK(pool.cs);
861  const bool fReplacementTransaction = setConflicts.size();
862  if (fReplacementTransaction)
863  {
864  CFeeRate newFeeRate(nModifiedFees, nSize);
865  std::set<uint256> setConflictsParents;
866  const int maxDescendantsToVisit = 100;
867  CTxMemPool::setEntries setIterConflicting;
868  for (const uint256 &hashConflicting : setConflicts)
869  {
870  CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
871  if (mi == pool.mapTx.end())
872  continue;
873 
874  // Save these to avoid repeated lookups
875  setIterConflicting.insert(mi);
876 
877  // Don't allow the replacement to reduce the feerate of the
878  // mempool.
879  //
880  // We usually don't want to accept replacements with lower
881  // feerates than what they replaced as that would lower the
882  // feerate of the next block. Requiring that the feerate always
883  // be increased is also an easy-to-reason about way to prevent
884  // DoS attacks via replacements.
885  //
886  // The mining code doesn't (currently) take children into
887  // account (CPFP) so we only consider the feerates of
888  // transactions being directly replaced, not their indirect
889  // descendants. While that does mean high feerate children are
890  // ignored when deciding whether or not to replace, we do
891  // require the replacement to pay more overall fees too,
892  // mitigating most cases.
893  CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
894  if (newFeeRate <= oldFeeRate)
895  {
896  return state.DoS(0, false,
897  REJECT_INSUFFICIENTFEE, "insufficient fee", false,
898  strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
899  hash.ToString(),
900  newFeeRate.ToString(),
901  oldFeeRate.ToString()));
902  }
903 
904  for (const CTxIn &txin : mi->GetTx().vin)
905  {
906  setConflictsParents.insert(txin.prevout.hash);
907  }
908 
909  nConflictingCount += mi->GetCountWithDescendants();
910  }
911  // This potentially overestimates the number of actual descendants
912  // but we just want to be conservative to avoid doing too much
913  // work.
914  if (nConflictingCount <= maxDescendantsToVisit) {
915  // If not too many to replace, then calculate the set of
916  // transactions that would have to be evicted
917  for (CTxMemPool::txiter it : setIterConflicting) {
918  pool.CalculateDescendants(it, allConflicting);
919  }
920  for (CTxMemPool::txiter it : allConflicting) {
921  nConflictingFees += it->GetModifiedFee();
922  nConflictingSize += it->GetTxSize();
923  }
924  } else {
925  return state.DoS(0, false,
926  REJECT_NONSTANDARD, "too many potential replacements", false,
927  strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
928  hash.ToString(),
929  nConflictingCount,
930  maxDescendantsToVisit));
931  }
932 
933  for (unsigned int j = 0; j < tx.vin.size(); j++)
934  {
935  // We don't want to accept replacements that require low
936  // feerate junk to be mined first. Ideally we'd keep track of
937  // the ancestor feerates and make the decision based on that,
938  // but for now requiring all new inputs to be confirmed works.
939  if (!setConflictsParents.count(tx.vin[j].prevout.hash))
940  {
941  // Rather than check the UTXO set - potentially expensive -
942  // it's cheaper to just check if the new input refers to a
943  // tx that's in the mempool.
944  if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
945  return state.DoS(0, false,
946  REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
947  strprintf("replacement %s adds unconfirmed input, idx %d",
948  hash.ToString(), j));
949  }
950  }
951 
952  // The replacement must pay greater fees than the transactions it
953  // replaces - if we did the bandwidth used by those conflicting
954  // transactions would not be paid for.
955  if (nModifiedFees < nConflictingFees)
956  {
957  return state.DoS(0, false,
958  REJECT_INSUFFICIENTFEE, "insufficient fee", false,
959  strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
960  hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
961  }
962 
963  // Finally in addition to paying more fees than the conflicts the
964  // new transaction must pay for its own bandwidth.
965  CAmount nDeltaFees = nModifiedFees - nConflictingFees;
966  if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
967  {
968  return state.DoS(0, false,
969  REJECT_INSUFFICIENTFEE, "insufficient fee", false,
970  strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
971  hash.ToString(),
972  FormatMoney(nDeltaFees),
974  }
975  }
976 
977  unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
978  if (!chainparams.RequireStandard()) {
979  scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
980  }
981 
982  // Check against previous transactions
983  // This is done last to help prevent CPU exhaustion denial-of-service attacks.
984  PrecomputedTransactionData txdata(tx);
985  if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
986  // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
987  // need to turn both off, and compare against just turning off CLEANSTACK
988  // to see if the failure is specifically due to witness validation.
989  CValidationState stateDummy; // Want reported failures to be from first CheckInputs
990  if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
991  !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
992  // Only the witness is missing, so the transaction itself may be fine.
993  state.SetCorruptionPossible();
994  }
995  return false; // state filled in by CheckInputs
996  }
997 
998  // Check again against the current block tip's script verification
999  // flags to cache our script execution flags. This is, of course,
1000  // useless if the next block has different script flags from the
1001  // previous one, but because the cache tracks script flags for us it
1002  // will auto-invalidate and we'll just have a few blocks of extra
1003  // misses on soft-fork activation.
1004  //
1005  // This is also useful in case of bugs in the standard flags that cause
1006  // transactions to pass as valid when they're actually invalid. For
1007  // instance the STRICTENC flag was incorrectly allowing certain
1008  // CHECKSIG NOT scripts to pass, even though they were invalid.
1009  //
1010  // There is a similar check in CreateNewBlock() to prevent creating
1011  // invalid blocks (using TestBlockValidity), however allowing such
1012  // transactions into the mempool can be exploited as a DoS attack.
1013  unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
1014  if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
1015  {
1016  // If we're using promiscuousmempoolflags, we may hit this normally
1017  // Check if current block has some flags that scriptVerifyFlags
1018  // does not before printing an ominous warning
1019  if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
1020  return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
1021  __func__, hash.ToString(), FormatStateMessage(state));
1022  } else {
1023  if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
1024  return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
1025  __func__, hash.ToString(), FormatStateMessage(state));
1026  } else {
1027  LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
1028  }
1029  }
1030  }
1031 
1032  // Remove conflicting transactions from the mempool
1033  for (const CTxMemPool::txiter it : allConflicting)
1034  {
1035  LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s FAB additional fees, %d delta bytes\n",
1036  it->GetTx().GetHash().ToString(),
1037  hash.ToString(),
1038  FormatMoney(nModifiedFees - nConflictingFees),
1039  (int)nSize - (int)nConflictingSize);
1040  if (plTxnReplaced)
1041  plTxnReplaced->push_back(it->GetSharedTx());
1042  }
1043  pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
1044 
1045  // This transaction should only count for fee estimation if it isn't a
1046  // BIP 125 replacement transaction (may not be widely supported), the
1047  // node is not behind, and the transaction is not dependent on any other
1048  // transactions in the mempool.
1049  bool validForFeeEstimation = !fReplacementTransaction && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
1050 
1051  // Store transaction in memory
1052  pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
1053 
1054  // trim mempool and check if tx was trimmed
1055  if (!fOverrideMempoolLimit) {
1056  LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
1057  if (!pool.exists(hash))
1058  return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
1059  }
1060  }
1061 
1063 
1064  return true;
1065 }
1066 
1068 static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
1069  bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
1070  bool fOverrideMempoolLimit, const CAmount nAbsurdFee, bool rawTx = false)
1071 {
1072  std::vector<COutPoint> coins_to_uncache;
1073  bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, nAcceptTime, plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, coins_to_uncache, rawTx);
1074  if (!res) {
1075  for (const COutPoint& hashTx : coins_to_uncache)
1076  pcoinsTip->Uncache(hashTx);
1077  }
1078  // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
1079  CValidationState stateDummy;
1080  FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
1081  return res;
1082 }
1083 bool IsConfirmedInNPrevBlocks(const CDiskTxPos& txindex, const CBlockIndex* pindexFrom, int nMaxDepth, int& nActualDepth)
1084 {
1085  for (const CBlockIndex* pindex = pindexFrom; pindex && pindexFrom->nHeight - pindex->nHeight < nMaxDepth; pindex = pindex->pprev)
1086  {
1087  if (pindex->nDataPos == txindex.nPos && pindex->nFile == txindex.nFile)
1088  {
1089  nActualDepth = pindexFrom->nHeight - pindex->nHeight;
1090  return true;
1091  }
1092  }
1093  return false;
1094 }
1095 
1096 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree,
1097  bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
1098  bool fOverrideMempoolLimit, const CAmount nAbsurdFee, bool rawTx)
1099 {
1100  const CChainParams& chainparams = Params();
1101  return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, fLimitFree, pfMissingInputs, GetTime(), plTxnReplaced, fOverrideMempoolLimit, nAbsurdFee, rawTx);
1102 }
1103 
1105 bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
1106 {
1107  CBlockIndex *pindexSlow = nullptr;
1108 
1109  LOCK(cs_main);
1110 
1111  CTransactionRef ptx = mempool.get(hash);
1112  if (ptx)
1113  {
1114  txOut = ptx;
1115  return true;
1116  }
1117 
1118  if (fTxIndex) {
1119  CDiskTxPos postx;
1120  if (pblocktree->ReadTxIndex(hash, postx)) {
1121  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1122  if (file.IsNull())
1123  return error("%s: OpenBlockFile failed", __func__);
1124  CBlockHeader header;
1125  try {
1126  file >> header;
1127  fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1128  file >> txOut;
1129  } catch (const std::exception& e) {
1130  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1131  }
1132  hashBlock = header.GetHash();
1133  if (txOut->GetHash() != hash)
1134  return error("%s: txid mismatch", __func__);
1135  return true;
1136  }
1137  }
1138 
1139  if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1140  const Coin& coin = AccessByTxid(*pcoinsTip, hash);
1141  if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
1142  }
1143 
1144  if (pindexSlow) {
1145  CBlock block;
1146  if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1147  for (const auto& tx : block.vtx) {
1148  if (tx->GetHash() == hash) {
1149  txOut = tx;
1150  hashBlock = pindexSlow->GetBlockHash();
1151  return true;
1152  }
1153  }
1154  }
1155  }
1156 
1157  return false;
1158 }
1159 
1160 
1161 
1162 
1163 
1165 //
1166 // CBlock and CBlockIndex
1167 //
1168 
1169 static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1170 {
1171  // Open history file to append
1172  CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1173  if (fileout.IsNull())
1174  return error("WriteBlockToDisk: OpenBlockFile failed");
1175 
1176  // Write index header
1177  unsigned int nSize = GetSerializeSize(fileout, block);
1178  fileout << FLATDATA(messageStart) << nSize;
1179 
1180  // Write block
1181  long fileOutPos = ftell(fileout.Get());
1182  if (fileOutPos < 0)
1183  return error("WriteBlockToDisk: ftell failed");
1184  pos.nPos = (unsigned int)fileOutPos;
1185  fileout << block;
1186 
1187  return true;
1188 }
1189 
1190 template <typename Block>
1191 bool ReadBlockFromDisk(Block& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1192 {
1193  block.SetNull();
1194 
1195  // Open history file to read
1196  CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1197  if (filein.IsNull())
1198  return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1199 
1200  // Read block
1201  try {
1202  filein >> block;
1203  }
1204  catch (const std::exception& e) {
1205  return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1206  }
1207 
1208 
1209  // Check Equihash solution
1210  bool postfork = ( (uint32_t)block.nHeight >= (uint32_t)consensusParams.FABHeight );
1211  if (postfork && !CheckEquihashSolution(&block, Params())) {
1212  LogPrintf("Debug nHeight=%d FABHeight=%d postfork=%d \n", block.nHeight, consensusParams.FABHeight, postfork );
1213  return error("ReadBlockFromDisk: Errors in block header at %s (bad Equihash solution)", pos.ToString());
1214  }
1215  // Check the header
1216  if (!CheckProofOfWork(block.GetHash(), block.nBits, postfork, consensusParams))
1217  return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1218 
1219  return true;
1220 }
1221 
1222 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1223 {
1224  if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1225  return false;
1226  if (block.GetHash() != pindex->GetBlockHash())
1227  return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1228  pindex->ToString(), pindex->GetBlockPos().ToString());
1229  return true;
1230 }
1231 
1232 bool ReadFromDisk(CBlockHeader& block, unsigned int nFile, unsigned int nBlockPos)
1233 {
1234  return ReadBlockFromDisk(block, CDiskBlockPos(nFile, nBlockPos), Params().GetConsensus());
1235 }
1236 
1237 //This function for reading transaction can also be used to re-factorize GetTransaction.
1239 {
1240  CAutoFile filein(OpenBlockFile(txindex, true), SER_DISK, CLIENT_VERSION);
1241  if (filein.IsNull())
1242  return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
1243 
1244  // Read transaction
1245  CBlockHeader header;
1246  try {
1247  filein >> header;
1248  fseek(filein.Get(), txindex.nTxOffset, SEEK_CUR);
1249  filein >> tx;
1250  }
1251  catch (const std::exception& e) {
1252  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1253  }
1254 
1255  return true;
1256 }
1257 
1259 {
1260  if (!txdb.ReadTxIndex(prevout.hash, txindex))
1261  return false;
1262  if (!ReadFromDisk(tx, txindex))
1263  return false;
1264  if (prevout.n >= tx.vout.size())
1265  {
1266  return false;
1267  }
1268  return true;
1269 }
1270 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1271 {
1272  int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1273  // Force block reward to zero when right shift is undefined.
1274  if (halvings >= 64)
1275  return 0;
1276 
1277  CAmount nSubsidy = INITIAL_BLOCK_REWARD * COIN;
1278 
1280 
1281  if ( fRegTest )
1282  nSubsidy = INITIAL_BLOCK_REWARD_REGTEST * COIN;
1283 
1284  //Pre-mining
1285  if ( nHeight == 2 && !fRegTest ) {
1286  nSubsidy = 32000000 * COIN;
1287  }
1288 
1289  // Subsidy is cut in half every 1680,000 blocks which will occur approximately every 4 years.
1290  if ( !fRegTest )
1291  nSubsidy >>= halvings;
1292  return nSubsidy;
1293 }
1294 
1296 {
1297  const CChainParams& chainParams = Params();
1298 
1299  // Once this function has returned false, it must remain false.
1300  static std::atomic<bool> latchToFalse{false};
1301  // Optimization: pre-test latch before taking the lock.
1302  if (latchToFalse.load(std::memory_order_relaxed))
1303  return false;
1304 
1305  LOCK(cs_main);
1306  if (latchToFalse.load(std::memory_order_relaxed))
1307  return false;
1308  if (fImporting || fReindex)
1309  return true;
1310  if (chainActive.Tip() == nullptr)
1311  return true;
1312  if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1313  return true;
1314  if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1315  return true;
1316  LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1317  latchToFalse.store(true, std::memory_order_relaxed);
1318  return false;
1319 }
1320 
1322 
1323 static void AlertNotify(const std::string& strMessage)
1324 {
1326  std::string strCmd = gArgs.GetArg("-alertnotify", "");
1327  if (strCmd.empty()) return;
1328 
1329  // Alert text should be plain ascii coming from a trusted source, but to
1330  // be safe we first strip anything not in safeChars, then add single quotes around
1331  // the whole string before passing it to the shell:
1332  std::string singleQuote("'");
1333  std::string safeStatus = SanitizeString(strMessage);
1334  safeStatus = singleQuote+safeStatus+singleQuote;
1335  boost::replace_all(strCmd, "%s", safeStatus);
1336 
1337  boost::thread t(runCommand, strCmd); // thread runs free
1338 }
1339 
1340 static void CheckForkWarningConditions()
1341 {
1342  AssertLockHeld(cs_main);
1343  // Before we get past initial download, we cannot reliably alert about forks
1344  // (we assume we don't get stuck on a fork before finishing our initial sync)
1345  if (IsInitialBlockDownload())
1346  return;
1347 
1348  // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1349  // of our head, drop it
1350  if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1351  pindexBestForkTip = nullptr;
1352 
1353  if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1354  {
1356  {
1357  std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1358  pindexBestForkBase->phashBlock->ToString() + std::string("'");
1359  AlertNotify(warning);
1360  }
1361  if (pindexBestForkTip && pindexBestForkBase)
1362  {
1363  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__,
1365  pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1366  SetfLargeWorkForkFound(true);
1367  }
1368  else
1369  {
1370  LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1372  }
1373  }
1374  else
1375  {
1376  SetfLargeWorkForkFound(false);
1378  }
1379 }
1380 
1381 static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1382 {
1383  AssertLockHeld(cs_main);
1384  // If we are on a fork that is sufficiently large, set a warning flag
1385  CBlockIndex* pfork = pindexNewForkTip;
1386  CBlockIndex* plonger = chainActive.Tip();
1387  while (pfork && pfork != plonger)
1388  {
1389  while (plonger && plonger->nHeight > pfork->nHeight)
1390  plonger = plonger->pprev;
1391  if (pfork == plonger)
1392  break;
1393  pfork = pfork->pprev;
1394  }
1395 
1396  // We define a condition where we should warn the user about as a fork of at least 7 blocks
1397  // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1398  // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1399  // hash rate operating on the fork.
1400  // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1401  // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1402  // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1403  if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
1404  pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1405  chainActive.Height() - pindexNewForkTip->nHeight < 72)
1406  {
1407  pindexBestForkTip = pindexNewForkTip;
1408  pindexBestForkBase = pfork;
1409  }
1410 
1411  CheckForkWarningConditions();
1412 }
1413 
1414 void static InvalidChainFound(CBlockIndex* pindexNew)
1415 {
1416  if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1417  pindexBestInvalid = pindexNew;
1418 
1419  LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1420  pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1421  log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1422  pindexNew->GetBlockTime()));
1423  CBlockIndex *tip = chainActive.Tip();
1424  assert (tip);
1425  LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1426  tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1427  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1428  CheckForkWarningConditions();
1429 }
1430 
1431 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1432  if (!state.CorruptionPossible()) {
1433  pindex->nStatus |= BLOCK_FAILED_VALID;
1434  g_failed_blocks.insert(pindex);
1435  setDirtyBlockIndex.insert(pindex);
1436  setBlockIndexCandidates.erase(pindex);
1437  InvalidChainFound(pindex);
1438  }
1439 }
1440 
1441 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1442 {
1443  // mark inputs spent
1444  if (!tx.IsCoinBase()) {
1445  txundo.vprevout.reserve(tx.vin.size());
1446  for (const CTxIn &txin : tx.vin) {
1447  txundo.vprevout.emplace_back();
1448  bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
1449  assert(is_spent);
1450  }
1451  }
1452  // add outputs
1453  AddCoins(inputs, tx, nHeight);
1454 }
1455 
1456 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1457 {
1458  CTxUndo txundo;
1459  UpdateCoins(tx, inputs, txundo, nHeight);
1460 }
1461 
1463  const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1464  const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
1465  return VerifyScript(scriptSig, scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error);
1466 }
1467 
1469 {
1470  LOCK(cs_main);
1471  CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1472  return pindexPrev->nHeight + 1;
1473 }
1474 
1475 
1476 namespace Consensus {
1477  extern bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight);
1478 }// namespace Consensus
1479 static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
1480 static uint256 scriptExecutionCacheNonce(GetRandHash());
1481 
1483  // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
1484  // setup_bytes creates the minimum possible cache (2 elements).
1485  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);
1486  size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
1487  LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
1488  (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
1489 }
1490 
1505 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)
1506 {
1507  if (!tx.IsCoinBase())
1508  {
1509  if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1510  return false;
1511 
1512  if (pvChecks)
1513  pvChecks->reserve(tx.vin.size());
1514 
1515  // The first loop above does all the inexpensive checks.
1516  // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1517  // Helps prevent CPU exhaustion attacks.
1518 
1519  // Skip script verification when connecting blocks under the
1520  // assumevalid block. Assuming the assumevalid block is valid this
1521  // is safe because block merkle hashes are still computed and checked,
1522  // Of course, if an assumed valid block is invalid due to false scriptSigs
1523  // this optimization would allow an invalid chain to be accepted.
1524  if (fScriptChecks) {
1525  // First check if script executions have been cached with the same
1526  // flags. Note that this assumes that the inputs provided are
1527  // correct (ie that the transaction hash which is in tx's prevouts
1528  // properly commits to the scriptPubKey in the inputs view of that
1529  // transaction).
1530  uint256 hashCacheEntry;
1531  // We only use the first 19 bytes of nonce to avoid a second SHA
1532  // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
1533  static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
1534  CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
1535  AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
1536  if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
1537  return true;
1538  }
1539 
1540  for (unsigned int i = 0; i < tx.vin.size(); i++) {
1541  const COutPoint &prevout = tx.vin[i].prevout;
1542  const Coin& coin = inputs.AccessCoin(prevout);
1543  assert(!coin.IsSpent());
1544 
1545  // We very carefully only pass in things to CScriptCheck which
1546  // are clearly committed to by tx' witness hash. This provides
1547  // a sanity check that our caching is not introducing consensus
1548  // failures through additional data in, eg, the coins being
1549  // spent being checked as a part of CScriptCheck.
1550  const CScript& scriptPubKey = coin.out.scriptPubKey;
1551  const CAmount amount = coin.out.nValue;
1552 
1553  // Verify signature
1554  CScriptCheck check(scriptPubKey, amount, tx, i, flags, cacheSigStore, &txdata);
1555  if (pvChecks) {
1556  pvChecks->push_back(CScriptCheck());
1557  check.swap(pvChecks->back());
1558  } else if (!check()) {
1559  if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1560  // Check whether the failure was caused by a
1561  // non-mandatory script verification check, such as
1562  // non-standard DER encodings or non-null dummy
1563  // arguments; if so, don't trigger DoS protection to
1564  // avoid splitting the network between upgraded and
1565  // non-upgraded nodes.
1566  CScriptCheck check2(scriptPubKey, amount, tx, i,
1567  flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
1568  if (check2())
1569  return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1570  }
1571  // Failures of other flags indicate a transaction that is
1572  // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
1573  // such nodes as they are not following the protocol. That
1574  // said during an upgrade careful thought should be taken
1575  // as to the correct behavior - we may want to continue
1576  // peering with non-upgraded nodes even after soft-fork
1577  // super-majority signaling has occurred.
1578  return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1579  }
1580  }
1581 
1582  if (cacheFullScriptStore && !pvChecks) {
1583  // We executed all of the provided scripts, and were told to
1584  // cache the result. Do so now.
1585  scriptExecutionCache.insert(hashCacheEntry);
1586  }
1587  }
1588  }
1589 
1590  return true;
1591 }
1592 
1593 namespace {
1594 
1595 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1596 {
1597  // Open history file to append
1598  CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1599  if (fileout.IsNull())
1600  return error("%s: OpenUndoFile failed", __func__);
1601 
1602  // Write index header
1603  unsigned int nSize = GetSerializeSize(fileout, blockundo);
1604  fileout << FLATDATA(messageStart) << nSize;
1605 
1606  // Write undo data
1607  long fileOutPos = ftell(fileout.Get());
1608  if (fileOutPos < 0)
1609  return error("%s: ftell failed", __func__);
1610  pos.nPos = (unsigned int)fileOutPos;
1611  fileout << blockundo;
1612 
1613  // calculate & write checksum
1614  CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1615  hasher << hashBlock;
1616  hasher << blockundo;
1617  fileout << hasher.GetHash();
1618 
1619  return true;
1620 }
1621 
1622 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1623 {
1624  // Open history file to read
1625  CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1626  if (filein.IsNull())
1627  return error("%s: OpenUndoFile failed", __func__);
1628 
1629  // Read block
1630  uint256 hashChecksum;
1631  CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
1632  try {
1633  verifier << hashBlock;
1634  verifier >> blockundo;
1635  filein >> hashChecksum;
1636  }
1637  catch (const std::exception& e) {
1638  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1639  }
1640 
1641  // Verify checksum
1642  if (hashChecksum != verifier.GetHash())
1643  return error("%s: Checksum mismatch", __func__);
1644 
1645  return true;
1646 }
1647 
1649 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1650 {
1651  SetMiscWarning(strMessage);
1652  LogPrintf("*** %s\n", strMessage);
1654  userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1656  StartShutdown();
1657  return false;
1658 }
1659 
1660 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1661 {
1662  AbortNode(strMessage, userMessage);
1663  return state.Error(strMessage);
1664 }
1665 
1666 } // namespace
1667 
1669 {
1670  DISCONNECT_OK, // All good.
1671  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
1672  DISCONNECT_FAILED // Something else went wrong.
1673 };
1674 
1682 int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
1683 {
1684  bool fClean = true;
1685 
1686  if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
1687 
1688  if (undo.nHeight == 0) {
1689  // Missing undo metadata (height and coinbase). Older versions included this
1690  // information only in undo records for the last spend of a transactions'
1691  // outputs. This implies that it must be present for some other output of the same tx.
1692  const Coin& alternate = AccessByTxid(view, out.hash);
1693  if (!alternate.IsSpent()) {
1694  undo.nHeight = alternate.nHeight;
1695  undo.fCoinBase = alternate.fCoinBase;
1696  } else {
1697  return DISCONNECT_FAILED; // adding output for transaction without known metadata
1698  }
1699  }
1700  // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
1701  // sure that the coin did not already exist in the cache. As we have queried for that above
1702  // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
1703  // it is an overwrite.
1704  view.AddCoin(out, std::move(undo), !fClean);
1705 
1706  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1707 }
1708 
1711 static DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1712 {
1713  assert(pindex->GetBlockHash() == view.GetBestBlock());
1714 
1715  if (pfClean)
1716  *pfClean = false;
1717 
1718  bool fClean = true;
1719 
1720  CBlockUndo blockUndo;
1721  CDiskBlockPos pos = pindex->GetUndoPos();
1722  if (pos.IsNull()) {
1723  error("DisconnectBlock(): no undo data available");
1724  return DISCONNECT_FAILED;
1725  }
1726  if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) {
1727  error("DisconnectBlock(): failure reading undo data");
1728  return DISCONNECT_FAILED;
1729  }
1730 
1731  if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
1732  error("DisconnectBlock(): block and undo data inconsistent");
1733  return DISCONNECT_FAILED;
1734  }
1735 
1736  // undo transactions in reverse order
1737  for (int i = block.vtx.size() - 1; i >= 0; i--) {
1738  const CTransaction &tx = *(block.vtx[i]);
1739  uint256 hash = tx.GetHash();
1740  bool is_coinbase = tx.IsCoinBase();
1741 
1742  // Check that all outputs are available and match the outputs in the block itself
1743  // exactly.
1744  for (size_t o = 0; o < tx.vout.size(); o++) {
1745  if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
1746  COutPoint out(hash, o);
1747  Coin coin;
1748  bool is_spent = view.SpendCoin(out, &coin);
1749  if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
1750  fClean = false; // transaction output mismatch
1751  }
1752  }
1753  }
1754 
1755  // restore inputs
1756  if (i > 0) { // not coinbases
1757  CTxUndo &txundo = blockUndo.vtxundo[i-1];
1758  if (txundo.vprevout.size() != tx.vin.size()) {
1759  error("DisconnectBlock(): transaction and undo data inconsistent");
1760  return DISCONNECT_FAILED;
1761  }
1762  for (unsigned int j = tx.vin.size(); j-- > 0;) {
1763  const COutPoint &out = tx.vin[j].prevout;
1764  int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
1765  if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
1766  fClean = fClean && res != DISCONNECT_UNCLEAN;
1767  }
1768  // At this point, all of txundo.vprevout should have been moved out.
1769  }
1770  }
1771 
1772  // move best block pointer to prevout block
1773  view.SetBestBlock(pindex->pprev->GetBlockHash());
1774  globalState->setRoot(uintToh256(pindex->pprev->hashStateRoot)); // fasc
1775  globalState->setRootUTXO(uintToh256(pindex->pprev->hashUTXORoot)); // fasc
1776 
1777  if(pfClean == NULL && fLogEvents){
1778  pstorageresult->deleteResults(block.vtx);
1779  pblocktree->EraseHeightIndex(pindex->nHeight);
1780  }
1781 
1782  return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
1783 }
1784 
1785 void static FlushBlockFile(bool fFinalize = false)
1786 {
1787  LOCK(cs_LastBlockFile);
1788 
1789  CDiskBlockPos posOld(nLastBlockFile, 0);
1790 
1791  FILE *fileOld = OpenBlockFile(posOld);
1792  if (fileOld) {
1793  if (fFinalize)
1794  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1795  FileCommit(fileOld);
1796  fclose(fileOld);
1797  }
1798 
1799  fileOld = OpenUndoFile(posOld);
1800  if (fileOld) {
1801  if (fFinalize)
1802  TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1803  FileCommit(fileOld);
1804  fclose(fileOld);
1805  }
1806 }
1807 
1808 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1809 
1810 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1811 
1813  RenameThread("fabcoin-scriptch");
1814  scriptcheckqueue.Thread();
1815 }
1816 
1817 // Protected by cs_main
1819 
1820 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
1821 {
1822  LOCK(cs_main);
1823  int32_t nVersion = VERSIONBITS_TOP_BITS;
1824 
1825  for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
1826  ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
1827  if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
1828  nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
1829  }
1830  }
1831 
1832  return nVersion;
1833 }
1834 
1839 {
1840 private:
1841  int bit;
1842 
1843 public:
1844  WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
1845 
1846  int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
1847  int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
1848  int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
1849  int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
1850 
1851  bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
1852  {
1853  return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
1854  ((pindex->nVersion >> bit) & 1) != 0 &&
1855  ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
1856  }
1857 };
1858 
1859 // Protected by cs_main
1860 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
1861 
1862 static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
1863  AssertLockHeld(cs_main);
1864 
1865  // BIP16 didn't become active until Apr 1 2012
1866  int64_t nBIP16SwitchTime = 1333238400;
1867  bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1868 
1869  unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1870 
1871  // Start enforcing the DERSIG (BIP66) rule
1872  if (pindex->nHeight >= consensusparams.BIP66Height) {
1873  flags |= SCRIPT_VERIFY_DERSIG;
1874  }
1875 
1876  // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
1877  if (pindex->nHeight >= consensusparams.BIP65Height) {
1879  }
1880 
1881  // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
1882  if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
1884  }
1885 
1886  // Start enforcing WITNESS rules using versionbits logic.
1887  if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
1888  flags |= SCRIPT_VERIFY_WITNESS;
1889  flags |= SCRIPT_VERIFY_NULLDUMMY;
1890  }
1891 
1892  return flags;
1893 }
1894 
1895 
1896 
1897 static int64_t nTimeCheck = 0;
1898 static int64_t nTimeForks = 0;
1899 static int64_t nTimeVerify = 0;
1900 static int64_t nTimeConnect = 0;
1901 static int64_t nTimeIndex = 0;
1902 static int64_t nTimeCallbacks = 0;
1903 static int64_t nTimeTotal = 0;
1904 
1908 static bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
1909  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false)
1910 {
1911  AssertLockHeld(cs_main);
1912  assert(pindex);
1913  // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
1914  assert((pindex->phashBlock == nullptr) ||
1915  (*pindex->phashBlock == block.GetHash()));
1916  int64_t nTimeStart = GetTimeMicros();
1917 
1919  FascDGP fascDGP(globalState.get(), fGettingValuesDGP);
1920  auto q1_sch = fascDGP.getGasSchedule(pindex->nHeight + 1);
1921  globalSealEngine->setFascSchedule(q1_sch);
1922  uint32_t sizeBlockDGP = fascDGP.getBlockSize(pindex->nHeight + 1);
1923  uint64_t minGasPrice = fascDGP.getMinGasPrice(pindex->nHeight + 1);
1924  uint64_t blockGasLimit = fascDGP.getBlockGasLimit(pindex->nHeight + 1);
1925  dgpMaxBlockSize = sizeBlockDGP ? sizeBlockDGP : dgpMaxBlockSize;
1927  CBlock checkBlock(block.GetBlockHeader());
1928  std::vector<CTxOut> checkVouts;
1929 
1930  uint64_t countCumulativeGasUsed = 0;
1932 
1933  // Move this check from CheckBlock to ConnectBlock as it depends on DGP values
1934  auto params = chainparams.GetConsensus();
1935 
1936  //LogPrintf("Debug Block=%s", block.ToString());
1937 
1938  if (block.vtx.empty() || block.vtx.size() > dgpMaxBlockSize || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) > dgpMaxBlockSize) // fabcoin
1939  return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
1940 
1941  // Move this check from ContextualCheckBlock to ConnectBlock as it depends on DGP values
1942  if (GetBlockWeight(block, params) > dgpMaxBlockWeight) {
1943  return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
1944  }
1945  // Check it again in case a previous version let a bad block in
1946  if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
1947  return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
1948 
1949  // verify that the view's current state corresponds to the previous block
1950  uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
1951  assert(hashPrevBlock == view.GetBestBlock());
1952 
1953  // Special case for the genesis block, skipping connection of its transactions
1954  // (its coinbase is unspendable)
1955  if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1956  if (!fJustCheck)
1957  view.SetBestBlock(pindex->GetBlockHash());
1958  return true;
1959  }
1960 
1962  // State is filled in by UpdateHashProof, this is an addional step from fasc
1963  if (!UpdateHashProof(block, state, chainparams.GetConsensus(), pindex, view)) {
1964  return error("%s: ConnectBlock(): %s", __func__, state.GetRejectReason().c_str());
1965  }
1967 
1968  bool fScriptChecks = true;
1969  if (!hashAssumeValid.IsNull()) {
1970  // We've been configured with the hash of a block which has been externally verified to have a valid history.
1971  // A suitable default value is included with the software and updated from time to time. Because validity
1972  // relative to a piece of software is an objective fact these defaults can be easily reviewed.
1973  // This setting doesn't force the selection of any particular chain but makes validating some faster by
1974  // effectively caching the result of part of the verification.
1975  BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
1976  if (it != mapBlockIndex.end()) {
1977  if (it->second->GetAncestor(pindex->nHeight) == pindex &&
1978  pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
1979  pindexBestHeader->nChainWork >= UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
1980  // This block is a member of the assumed verified chain and an ancestor of the best header.
1981  // The equivalent time check discourages hash power from extorting the network via DOS attack
1982  // into accepting an invalid block through telling users they must manually set assumevalid.
1983  // Requiring a software change or burying the invalid block, regardless of the setting, makes
1984  // it hard to hide the implication of the demand. This also avoids having release candidates
1985  // that are hardly doing any signature verification at all in testing without having to
1986  // artificially set the default assumed verified block further back.
1987  // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
1988  // least as good as the expected chain.
1989  fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
1990  }
1991  }
1992  }
1993 
1994  int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1995  LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1996 
1997  // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1998  // unless those are already completely spent.
1999  // If such overwrites are allowed, coinbases and transactions depending upon those
2000  // can be duplicated to remove the ability to spend the first instance -- even after
2001  // being sent to another address.
2002  // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
2003  // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
2004  // already refuses previously-known transaction ids entirely.
2005  // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2006  // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2007  // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2008  // initial block download.
2009 
2010  bool fEnforceBIP30 = (!pindex->phashBlock);
2011 
2012  //bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
2013  // !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2014  // (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2015 
2016  // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2017  // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2018  // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2019  // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
2020  // duplicate transactions descending from the known pairs either.
2021  // 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.
2022  CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
2023  //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2024  fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
2025 
2026  if (fEnforceBIP30) {
2027  for (const auto& tx : block.vtx) {
2028  for (size_t o = 0; o < tx->vout.size(); o++) {
2029  if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
2030  return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2031  REJECT_INVALID, "bad-txns-BIP30");
2032  }
2033  }
2034  }
2035  }
2036 
2037  // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
2038  int nLockTimeFlags = 0;
2040  nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2041  }
2042 
2043  // Get the script flags for this block
2044  unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
2045 
2046  int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
2047  LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
2048 
2049  CBlockUndo blockundo;
2050 
2051  CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
2052 
2053  std::vector<int> prevheights;
2054  CAmount nFees = 0;
2055  int nInputs = 0;
2056  int64_t nSigOpsCost = 0;
2057  CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2058  std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2059  vPos.reserve(block.vtx.size());
2060  blockundo.vtxundo.reserve(block.vtx.size() - 1);
2062  std::map<dev::Address, std::pair<CHeightTxIndexKey, std::vector<uint256>>> heightIndexes;
2064  std::vector<PrecomputedTransactionData> txdata;
2065  txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2066  uint64_t blockGasUsed = 0;
2067  CAmount gasRefunds = 0;
2068  uint64_t nValueOut = 0;
2069  uint64_t nValueIn = 0;
2070  for (unsigned int i = 0; i < block.vtx.size(); i++)
2071  {
2072  const CTransaction &tx = *(block.vtx[i]);
2073 
2074  nInputs += tx.vin.size();
2075 
2076  if (!tx.IsCoinBase())
2077  {
2078  if (!view.HaveInputs(tx))
2079  return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2080  REJECT_INVALID, "bad-txns-inputs-missingorspent");
2081 
2082  // Check that transaction is BIP68 final
2083  // BIP68 lock checks (as opposed to nLockTime checks) must
2084  // be in ConnectBlock because they require the UTXO set
2085  prevheights.resize(tx.vin.size());
2086  for (size_t j = 0; j < tx.vin.size(); j++) {
2087  prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
2088  }
2089 
2090  if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
2091  return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
2092  REJECT_INVALID, "bad-txns-nonfinal");
2093  }
2094  }
2095 
2096  // GetTransactionSigOpCost counts 3 types of sigops:
2097  // * legacy (always)
2098  // * p2sh (when P2SH enabled in flags and excludes coinbase)
2099  // * witness (when witness enabled in flags and excludes coinbase)
2100  nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
2101  if (nSigOpsCost > dgpMaxBlockSigOps)
2102  return state.DoS(100, error("ConnectBlock(): too many sigops"),
2103  REJECT_INVALID, "bad-blk-sigops");
2104 
2105  txdata.emplace_back(tx);
2106  bool hasOpSpend = tx.HasOpSpend();
2107  if (!tx.IsCoinBase())
2108  {
2109  nFees += view.GetValueIn(tx)-tx.GetValueOut();
2110 
2111  std::vector<CScriptCheck> vChecks;
2112  bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2113  if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, false, txdata[i], (hasOpSpend || tx.HasCreateOrCall()) ? nullptr : (nScriptCheckThreads ? &vChecks : nullptr)))//nScriptCheckThreads ? &vChecks : nullptr))
2114  return error("ConnectBlock(): CheckInputs on %s failed with %s",
2115  tx.GetHash().ToString(), FormatStateMessage(state));
2116  control.Add(vChecks);
2117  for (const CTxIn& j : tx.vin) {
2118  if (!j.scriptSig.HasOpSpend()) {
2119  const CTxOut& prevout = view.AccessCoin(j.prevout).out;
2120  if ((prevout.scriptPubKey.HasOpCreate() || prevout.scriptPubKey.HasOpCall())) {
2121  return state.DoS(100, error("ConnectBlock(): Contract spend without OP_SPEND in scriptSig"),
2122  REJECT_INVALID, "bad-txns-invalid-contract-spend");
2123  }
2124  }
2125  }
2126  }
2127 
2128  if (tx.IsCoinBase()) {
2129  nValueOut += tx.GetValueOut();
2130  }
2131  else {
2132  int64_t nTxValueIn = view.GetValueIn(tx);
2133  int64_t nTxValueOut = tx.GetValueOut();
2134  nValueIn += nTxValueIn;
2135  nValueOut += nTxValueOut;
2136  }
2137 
2139  if (!tx.HasOpSpend()) {
2140  checkBlock.vtx.push_back(block.vtx[i]);
2141  }
2142  if (tx.HasCreateOrCall() && !hasOpSpend) {
2143  if ( (uint32_t) chainActive.Tip()->nHeight < (uint32_t) Params().GetConsensus().ContractHeight ) {
2144  return state.DoS(1, false, REJECT_INVALID, "bad-txns-invalid-contract-before-fork");
2145  }
2146 
2147  if (!CheckSenderScript(view, tx)) {
2148  return state.DoS(100, false, REJECT_INVALID, "bad-txns-invalid-sender-script");
2149  }
2150 
2151  FascTxConverter convert(tx, &view, &block.vtx);
2152 
2153  ExtractFascTX resultConvertFascTX;
2154  if (!convert.extractionFascTransactions(resultConvertFascTX)) {
2155  return state.DoS(100, error("ConnectBlock(): Contract transaction of the wrong format"), REJECT_INVALID, "bad-tx-bad-contract-format");
2156  }
2157  if (!CheckMinGasPrice(resultConvertFascTX.second, minGasPrice))
2158  return state.DoS(100, error("ConnectBlock(): Contract execution has lower gas price than allowed"), REJECT_INVALID, "bad-tx-low-gas-price");
2159 
2160 
2161  dev::u256 gasAllTxs = dev::u256(0);
2162  ByteCodeExec exec(block, resultConvertFascTX.first, blockGasLimit);
2163  //validate VM version and other ETH params before execution
2164  //Reject anything unknown (could be changed later by DGP)
2165  //TODO evaluate if this should be relaxed for soft-fork purposes
2166  bool nonZeroVersion = false;
2167  dev::u256 sumGas = dev::u256(0);
2168  CAmount nTxFee = view.GetValueIn(tx) - tx.GetValueOut();
2169  for (FascTransaction& qtx : resultConvertFascTX.first) {
2170  sumGas += qtx.gas() * qtx.gasPrice();
2171 
2172  if (sumGas > dev::u256(INT64_MAX)) {
2173  return state.DoS(100, error("ConnectBlock(): Transaction's gas stipend overflows"), REJECT_INVALID, "bad-tx-gas-stipend-overflow");
2174  }
2175 
2176  if (sumGas > dev::u256(nTxFee)) {
2177  return state.DoS(100, error("ConnectBlock(): Transaction fee does not cover the gas stipend"), REJECT_INVALID, "bad-txns-fee-notenough");
2178  }
2179 
2180  VersionVM v = qtx.getVersion();
2181  if (v.format != 0)
2182  return state.DoS(100, error("ConnectBlock(): Contract execution uses unknown version format"), REJECT_INVALID, "bad-tx-version-format");
2183  if (v.rootVM != 0) {
2184  nonZeroVersion = true;
2185  }
2186  else {
2187  if (nonZeroVersion) {
2188  //If an output is version 0, then do not allow any other versions in the same tx
2189  return state.DoS(100, error("ConnectBlock(): Contract tx has mixed version 0 and non-0 VM executions"), REJECT_INVALID, "bad-tx-mixed-zero-versions");
2190  }
2191  }
2192  if (!(v.rootVM == 0 || v.rootVM == 1))
2193  return state.DoS(100, error("ConnectBlock(): Contract execution uses unknown root VM"), REJECT_INVALID, "bad-tx-version-rootvm");
2194  if (v.vmVersion != 0)
2195  return state.DoS(100, error("ConnectBlock(): Contract execution uses unknown VM version"), REJECT_INVALID, "bad-tx-version-vmversion");
2196  if (v.flagOptions != 0)
2197  return state.DoS(100, error("ConnectBlock(): Contract execution uses unknown flag options"), REJECT_INVALID, "bad-tx-version-flags");
2198 
2199  //check gas limit is not less than minimum gas limit (unless it is a no-exec tx)
2200  if (qtx.gas() < MINIMUM_GAS_LIMIT && v.rootVM != 0)
2201  return state.DoS(100, error("ConnectBlock(): Contract execution has lower gas limit than allowed"), REJECT_INVALID, "bad-tx-too-little-gas");
2202 
2203  if (qtx.gas() > UINT32_MAX)
2204  return state.DoS(100, error("ConnectBlock(): Contract execution can not specify greater gas limit than can fit in 32-bits"), REJECT_INVALID, "bad-tx-too-much-gas");
2205 
2206  gasAllTxs += qtx.gas();
2207  if (gasAllTxs > dev::u256(blockGasLimit))
2208  return state.DoS(1, false, REJECT_INVALID, "bad-txns-gas-exceeds-blockgaslimit");
2209 
2210  //don't allow less than DGP set minimum gas price to prevent MPoS greedy mining/spammers
2211  if (v.rootVM != 0 && (uint64_t)qtx.gasPrice() < minGasPrice)
2212  return state.DoS(100, error("ConnectBlock(): Contract execution has lower gas price than allowed"), REJECT_INVALID, "bad-tx-low-gas-price");
2213  }
2214 
2215  if (!nonZeroVersion) {
2216  //if tx is 0 version, then the tx must already have been added by a previous contract execution
2217  if (!tx.HasOpSpend()) {
2218  return state.DoS(100, error("ConnectBlock(): Version 0 contract executions are not allowed unless created by the AAL "), REJECT_INVALID, "bad-tx-improper-version-0");
2219  }
2220  }
2221 
2222  if (!exec.performByteCode()) {
2223  return state.DoS(100, error("ConnectBlock(): Unknown error during contract execution"), REJECT_INVALID, "bad-tx-unknown-error");
2224  }
2225 
2226  std::vector<ResultExecute> resultExec(exec.getResult());
2227  ByteCodeExecResult bcer;
2228  if (!exec.processingResults(bcer)) {
2229  return state.DoS(100, error("ConnectBlock(): Error processing VM execution results"), REJECT_INVALID, "bad-vm-exec-processing");
2230  }
2231 
2232  countCumulativeGasUsed += bcer.usedGas;
2233  std::vector<TransactionReceiptInfo> tri;
2234  if (fLogEvents && !fJustCheck)
2235  {
2236  for (size_t k = 0; k < resultConvertFascTX.first.size(); k++) {
2237  dev::Address key = resultExec[k].execRes.newAddress;
2238  if (!heightIndexes.count(key)) {
2239  heightIndexes[key].first = CHeightTxIndexKey(pindex->nHeight, resultExec[k].execRes.newAddress);
2240  }
2241  heightIndexes[key].second.push_back(tx.GetHash());
2242  tri.push_back(TransactionReceiptInfo{ block.GetHash(), uint32_t(pindex->nHeight), tx.GetHash(), uint32_t(i), resultConvertFascTX.first[k].from(), resultConvertFascTX.first[k].to(),
2243  countCumulativeGasUsed, uint64_t(resultExec[k].execRes.gasUsed), resultExec[k].execRes.newAddress, resultExec[k].txRec.log(), resultExec[k].execRes.excepted });
2244  }
2245 
2246  pstorageresult->addResult(uintToh256(tx.GetHash()), tri);
2247  }
2248 
2249  blockGasUsed += bcer.usedGas;
2250  if (blockGasUsed > blockGasLimit) {
2251  return state.DoS(1000, error("ConnectBlock(): Block exceeds gas limit"), REJECT_INVALID, "bad-blk-gaslimit");
2252  }
2253  for (CTxOut refundVout : bcer.refundOutputs) {
2254  gasRefunds += refundVout.nValue;
2255  }
2256  checkVouts.insert(checkVouts.end(), bcer.refundOutputs.begin(), bcer.refundOutputs.end());
2257  for (CTransaction& t : bcer.valueTransfers) {
2258  checkBlock.vtx.push_back(MakeTransactionRef(std::move(t)));
2259  }
2260  if (fRecordLogOpcodes && !fJustCheck) {
2261  writeVMlog(resultExec, tx, block);
2262  }
2263 
2264  for (ResultExecute& re : resultExec) {
2265  if (re.execRes.newAddress != dev::Address() && !fJustCheck)
2266  dev::g_logPost(std::string("Address : " + re.execRes.newAddress.hex()), nullptr);
2267  }
2268  }
2270 
2271  CTxUndo undoDummy;
2272  if (i > 0) {
2273  blockundo.vtxundo.push_back(CTxUndo());
2274  }
2275  UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2276 
2277  vPos.push_back(std::make_pair(tx.GetHash(), pos));
2278  pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2279  }
2280  int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
2281  LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
2282 
2283  if (nFees < gasRefunds) { //make sure it won't overflow
2284  return state.DoS(1000, error("ConnectBlock(): Less total fees than gas refund fees"), REJECT_INVALID, "bad-blk-fees-greater-gasrefund");
2285  }
2286 
2287  if (!CheckReward(block, state, pindex->nHeight, chainparams.GetConsensus(), nFees, gasRefunds, checkVouts))
2288  return state.DoS(100,error("ConnectBlock(): Reward check failed"));
2289 
2290  if (!control.Wait())
2291  return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
2292 
2293  int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
2294  LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
2295 
2297  checkBlock.hashMerkleRoot = BlockMerkleRoot(checkBlock);
2298  checkBlock.hashStateRoot = h256Touint(globalState->rootHash());
2299  checkBlock.hashUTXORoot = h256Touint(globalState->rootHashUTXO());
2300 
2301  //If this error happens, it probably means that something with AAL created transactions didn't match up to what is expected
2302  if ((checkBlock.GetHash() != block.GetHash()) && !fJustCheck)
2303  {
2304  LogPrintf("Actual block data does not match block expected by AAL\n");
2305 
2306  CBlock dumpBlock(block);
2307  LogPrintf("Debug Dump watched block: Height %d, others == %s \n", block.nHeight, dumpBlock.ToString());
2308  CBlock dumpCheckBlock(checkBlock);
2309  LogPrintf("Debug Dump Checked block: Height %d, others == %s \n", checkBlock.nHeight, dumpCheckBlock.ToString());
2310 
2311  //Something went wrong with AAL, compare different elements and determine what the problem is
2312  if (checkBlock.hashMerkleRoot != block.hashMerkleRoot) {
2313  //there is a mismatched tx, so go through and determine which txs
2314  if (block.vtx.size() > checkBlock.vtx.size()) {
2315  LogPrintf("Unexpected AAL transactions in block. Actual txs: %i, expected txs: %i\n", block.vtx.size(), checkBlock.vtx.size());
2316  for (size_t i = 0; i<block.vtx.size(); i++) {
2317  if (i > checkBlock.vtx.size()) {
2318  LogPrintf("Unexpected transaction: %s\n", block.vtx[i]->ToString());
2319  }
2320  else {
2321  if (block.vtx[i]->GetHash() != block.vtx[i]->GetHash()) {
2322  LogPrintf("Mismatched transaction at entry %i\n", i);
2323  LogPrintf("Actual: %s\n", block.vtx[i]->ToString());
2324  LogPrintf("Expected: %s\n", checkBlock.vtx[i]->ToString());
2325  }
2326  }
2327  }
2328  }
2329  else if (block.vtx.size() < checkBlock.vtx.size()) {
2330  LogPrintf("Actual block is missing AAL transactions. Actual txs: %i, expected txs: %i\n", block.vtx.size(), checkBlock.vtx.size());
2331  for (size_t i = 0; i<checkBlock.vtx.size(); i++) {
2332  if (i > block.vtx.size()) {
2333  LogPrintf("Missing transaction: %s\n", checkBlock.vtx[i]->ToString());
2334  }
2335  else {
2336  if (block.vtx[i]->GetHash() != block.vtx[i]->GetHash()) {
2337  LogPrintf("Mismatched transaction at entry %i\n", i);
2338  LogPrintf("Actual: %s\n", block.vtx[i]->ToString());
2339  LogPrintf("Expected: %s\n", checkBlock.vtx[i]->ToString());
2340  }
2341  }
2342  }
2343  }
2344  else {
2345  //count is correct, but a tx is wrong
2346  for (size_t i = 0; i<checkBlock.vtx.size(); i++) {
2347  if (block.vtx[i]->GetHash() != block.vtx[i]->GetHash()) {
2348  LogPrintf("Mismatched transaction at entry %i\n", i);
2349  LogPrintf("Actual: %s\n", block.vtx[i]->ToString());
2350  LogPrintf("Expected: %s\n", checkBlock.vtx[i]->ToString());
2351  }
2352  }
2353  }
2354  }
2355  if (checkBlock.hashUTXORoot != block.hashUTXORoot) {
2356  LogPrintf("Actual block data does not match hashUTXORoot expected by AAL block\n");
2357  }
2358  if (checkBlock.hashStateRoot != block.hashStateRoot) {
2359  LogPrintf("Actual block data does not match hashStateRoot expected by AAL block\n");
2360  }
2361 
2362  return state.DoS(100, error("ConnectBlock(): Incorrect AAL transactions or hashes (hashStateRoot, hashUTXORoot)"),
2363  REJECT_INVALID, "incorrect-transactions-or-hashes-block");
2364  }
2365 
2366  if (fJustCheck)
2367  {
2368  dev::h256 prevHashStateRoot(dev::sha3(dev::rlp("")));
2369  dev::h256 prevHashUTXORoot(dev::sha3(dev::rlp("")));
2370  if(pindex->pprev->hashStateRoot != uint256() && pindex->pprev->hashUTXORoot != uint256()){
2371  prevHashStateRoot = uintToh256(pindex->pprev->hashStateRoot);
2372  prevHashUTXORoot = uintToh256(pindex->pprev->hashUTXORoot);
2373  }
2374  globalState->setRoot(prevHashStateRoot);
2375  globalState->setRootUTXO(prevHashUTXORoot);
2376  return true;
2377  }
2379 
2380  // Write undo information to disk
2381  if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2382  {
2383  if (pindex->GetUndoPos().IsNull()) {
2384  CDiskBlockPos _pos;
2385  if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2386  return error("ConnectBlock(): FindUndoPos failed");
2387  if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2388  return AbortNode(state, "Failed to write undo data");
2389 
2390  // update nUndoPos in block index
2391  pindex->nUndoPos = _pos.nPos;
2392  pindex->nStatus |= BLOCK_HAVE_UNDO;
2393  }
2394 
2396  setDirtyBlockIndex.insert(pindex);
2397  }
2398 
2399  if (fLogEvents)
2400  {
2401  for (const auto& e : heightIndexes)
2402  {
2403  if (!pblocktree->WriteHeightIndex(e.second.first, e.second.second))
2404  return AbortNode(state, "Failed to write height index");
2405  }
2406  }
2407  if (fTxIndex)
2408  if (!pblocktree->WriteTxIndex(vPos))
2409  return AbortNode(state, "Failed to write transaction index");
2410 
2411  // add this block to the view's block chain
2412  view.SetBestBlock(pindex->GetBlockHash());
2413 
2414  int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
2415  LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
2416 //----------
2417  static uint256 hashPrevBestCoinBase;
2418  GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2419  hashPrevBestCoinBase = block.vtx[0]->GetHash();
2420 //----------
2421  int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
2422  LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
2423 
2424  if (fLogEvents)
2425  pstorageresult->commitResults();
2426  return true;
2427 }
2428 
2435 bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
2436  int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
2437  LOCK(cs_main);
2438  static int64_t nLastWrite = 0;
2439  static int64_t nLastFlush = 0;
2440  static int64_t nLastSetChain = 0;
2441  std::set<int> setFilesToPrune;
2442  bool fFlushForPrune = false;
2443  bool fDoFullFlush = false;
2444  int64_t nNow = 0;
2445  try {
2446  {
2447  LOCK(cs_LastBlockFile);
2448  if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
2449  if (nManualPruneHeight > 0) {
2450  FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
2451  } else {
2452  FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
2453  fCheckForPruning = false;
2454  }
2455  if (!setFilesToPrune.empty()) {
2456  fFlushForPrune = true;
2457  if (!fHavePruned) {
2458  pblocktree->WriteFlag("prunedblockfiles", true);
2459  fHavePruned = true;
2460  }
2461  }
2462  }
2463  nNow = GetTimeMicros();
2464  // Avoid writing/flushing immediately after startup.
2465  if (nLastWrite == 0) {
2466  nLastWrite = nNow;
2467  }
2468  if (nLastFlush == 0) {
2469  nLastFlush = nNow;
2470  }
2471  if (nLastSetChain == 0) {
2472  nLastSetChain = nNow;
2473  }
2474  int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
2475  int64_t cacheSize = pcoinsTip->DynamicMemoryUsage() * DB_PEAK_USAGE_FACTOR;
2476  int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
2477  // 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).
2478  bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
2479  // The cache is over the limit, we have to write now.
2480  bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
2481  // 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.
2482  bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2483  // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2484  bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2485  // Combine all conditions that result in a full cache flush.
2486  fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2487  // Write blocks and block index to disk.
2488  if (fDoFullFlush || fPeriodicWrite) {
2489  // Depend on nMinDiskSpace to ensure we can write block index
2490  if (!CheckDiskSpace(0))
2491  return state.Error("out of disk space");
2492  // First make sure all block and undo data is flushed to disk.
2493  FlushBlockFile();
2494  // Then update all block file information (which may refer to block and undo files).
2495  {
2496  std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2497  vFiles.reserve(setDirtyFileInfo.size());
2498  for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2499  vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
2500  setDirtyFileInfo.erase(it++);
2501  }
2502  std::vector<const CBlockIndex*> vBlocks;
2503  vBlocks.reserve(setDirtyBlockIndex.size());
2504  for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2505  vBlocks.push_back(*it);
2506  setDirtyBlockIndex.erase(it++);
2507  }
2508  if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2509  return AbortNode(state, "Failed to write to block index database");
2510  }
2511  }
2512  // Finally remove any pruned files
2513  if (fFlushForPrune)
2514  UnlinkPrunedFiles(setFilesToPrune);
2515  nLastWrite = nNow;
2516  }
2517  // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2518  if (fDoFullFlush) {
2519  // Typical Coin structures on disk are around 48 bytes in size.
2520  // Pushing a new one to the database can cause it to be written
2521  // twice (once in the log, and once in the tables). This is already
2522  // an overestimation, as most will delete an existing entry or
2523  // overwrite one. Still, use a conservative safety factor of 2.
2524  if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
2525  return state.Error("out of disk space");
2526  // Flush the chainstate (which may refer to block index entries).
2527  if (!pcoinsTip->Flush())
2528  return AbortNode(state, "Failed to write to coin database");
2529  nLastFlush = nNow;
2530  }
2531  }
2532  if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2533  // Update best block in wallet (so we can detect restored wallets).
2534  GetMainSignals().SetBestChain(chainActive.GetLocator());
2535  nLastSetChain = nNow;
2536  }
2537  } catch (const std::runtime_error& e) {
2538  return AbortNode(state, std::string("System error while flushing: ") + e.what());
2539  }
2540  return true;
2541 }
2542 
2544  CValidationState state;
2545  const CChainParams& chainparams = Params();
2546  return FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
2547 }
2548 
2550  CValidationState state;
2551  fCheckForPruning = true;
2552  const CChainParams& chainparams = Params();
2553  FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
2554 }
2555 
2556 static void DoWarning(const std::string& strWarning)
2557 {
2558  static bool fWarned = false;
2559  SetMiscWarning(strWarning);
2560  if (!fWarned) {
2561  AlertNotify(strWarning);
2562  fWarned = true;
2563  }
2564 }
2565 
2567 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2568  chainActive.SetTip(pindexNew);
2569 
2570  // New best block
2572 
2573  cvBlockChange.notify_all();
2574 
2575  std::vector<std::string> warningMessages;
2576  if (!IsInitialBlockDownload())
2577  {
2578  int nUpgraded = 0;
2579  const CBlockIndex* pindex = chainActive.Tip();
2580  for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2581  WarningBitsConditionChecker checker(bit);
2582  ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2583  if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2584  const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2585  if (state == THRESHOLD_ACTIVE) {
2586  DoWarning(strWarning);
2587  } else {
2588  warningMessages.push_back(strWarning);
2589  }
2590  }
2591  }
2592  // Check the version of the last 100 blocks to see if we need to upgrade:
2593  for (int i = 0; i < 100 && pindex != nullptr; i++)
2594  {
2595  int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2596  if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2597  ++nUpgraded;
2598  pindex = pindex->pprev;
2599  }
2600  if (nUpgraded > 0)
2601  warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
2602  if (nUpgraded > 100/2)
2603  {
2604  std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2605  // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2606  DoWarning(strWarning);
2607  }
2608  }
2609  LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
2610  chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2611  log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2612  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2613  GuessVerificationProgress(chainParams.TxData(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2614  if (!warningMessages.empty())
2615  LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2616  LogPrintf("\n");
2617 
2618 }
2619 
2630 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
2631 {
2632  CBlockIndex *pindexDelete = chainActive.Tip();
2633  assert(pindexDelete);
2634  // Read block from disk.
2635  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
2636  CBlock& block = *pblock;
2637  if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2638  return AbortNode(state, "Failed to read block");
2639  // Apply the block atomically to the chain state.
2640  int64_t nStart = GetTimeMicros();
2641  {
2642  CCoinsViewCache view(pcoinsTip);
2643  assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
2644  if (DisconnectBlock(block, pindexDelete, view, nullptr) != DISCONNECT_OK)
2645  return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2646  bool flushed = view.Flush();
2647  assert(flushed);
2648  }
2649  LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2650  // Write the chain state to disk, if necessary.
2651  if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
2652  return false;
2653 
2654  if (disconnectpool) {
2655  // Save transactions to re-add to mempool at end of reorg
2656  for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
2657  disconnectpool->addTransaction(*it);
2658  }
2659  while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
2660  // Drop the earliest entry, and remove its children from the mempool.
2661  auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
2663  disconnectpool->removeEntry(it);
2664  }
2665  }
2666 
2667  // Update chainActive and related variables.
2668  UpdateTip(pindexDelete->pprev, chainparams);
2669  // Let wallets know transactions went from 1-confirmed to
2670  // 0-confirmed or conflicted:
2672  return true;
2673 }
2674 
2675 static int64_t nTimeReadFromDisk = 0;
2676 static int64_t nTimeConnectTotal = 0;
2677 static int64_t nTimeFlush = 0;
2678 static int64_t nTimeChainState = 0;
2679 static int64_t nTimePostConnect = 0;
2681 bool CheckSenderScript(const CCoinsViewCache& view, const CTransaction& tx){
2682  CScript script = view.AccessCoin(tx.vin[0].prevout).out.scriptPubKey;
2683  if(!script.IsPayToPubkeyHash() && !script.IsPayToPubkey()){
2684  return false;
2685  }
2686  return true;
2687 }
2688 
2689 std::vector<ResultExecute> CallContract(const dev::Address& addrContract, std::vector<unsigned char> opcode, const dev::Address& sender, uint64_t gasLimit){
2690  CBlock block;
2692 
2693  CBlockIndex* pblockindex = mapBlockIndex[chainActive.Tip()->GetBlockHash()];
2694  ReadBlockFromDisk(block, pblockindex, Params().GetConsensus());
2695  block.nTime = GetAdjustedTime();
2696 
2697 
2698  block.vtx.erase(block.vtx.begin()+1,block.vtx.end());
2699 
2700  FascDGP fascDGP(globalState.get(), fGettingValuesDGP);
2701  uint64_t blockGasLimit = fascDGP.getBlockGasLimit(chainActive.Tip()->nHeight + 1);
2702 
2703  if(gasLimit == 0){
2704  gasLimit = blockGasLimit - 1;
2705  }
2706  dev::Address senderAddress = sender == dev::Address() ? dev::Address("ffffffffffffffffffffffffffffffffffffffff") : sender;
2707  tx.vout.push_back(CTxOut(0, CScript() << OP_DUP << OP_HASH160 << senderAddress.asBytes() << OP_EQUALVERIFY << OP_CHECKSIG));
2708  block.vtx.push_back(MakeTransactionRef(CTransaction(tx)));
2709 
2710  FascTransaction callTransaction(0, 1, dev::u256(gasLimit), addrContract, opcode, dev::u256(0));
2711  callTransaction.forceSender(senderAddress);
2712  callTransaction.setVersion(VersionVM::GetEVMDefault());
2713 
2714 
2715  ByteCodeExec exec(block, std::vector<FascTransaction>(1, callTransaction), blockGasLimit);
2717  return exec.getResult();
2718 }
2719 
2720 bool CheckMinGasPrice(std::vector<EthTransactionParams>& etps, const uint64_t& minGasPrice){
2721  for(EthTransactionParams& etp : etps){
2722  if(etp.gasPrice < dev::u256(minGasPrice))
2723  return false;
2724  }
2725  return true;
2726 }
2727 
2728 bool CheckReward(const CBlock& block, CValidationState& state, int nHeight, const Consensus::Params& consensusParams, CAmount nFees, CAmount gasRefunds, const std::vector<CTxOut>& vouts)
2729 {
2730 
2731  std::vector<CTxOut> vTempVouts = block.vtx[0]->vout;
2732  std::vector<CTxOut>::iterator it;
2733  for (size_t i = 0; i < vouts.size(); i++) {
2734  it = std::find(vTempVouts.begin(), vTempVouts.end(), vouts[i]);
2735  if (it == vTempVouts.end()) {
2736  return state.DoS(100, error("CheckReward(): Gas refund missing"));
2737  }
2738  else {
2739  vTempVouts.erase(it);
2740  }
2741  }
2742 
2743  // Check block reward
2744  CAmount blockReward = nFees + GetBlockSubsidy(nHeight, consensusParams);
2745  if (block.vtx[0]->GetValueOut() > blockReward)
2746  return state.DoS(100, error("CheckReward(): coinbase pays too much (actual=%d vs limit=%d)",
2747  block.vtx[0]->GetValueOut(), blockReward), REJECT_INVALID, "bad-cb-amount");
2748 
2749  return true;
2750 }
2751 
2752 valtype GetSenderAddress(const CTransaction& tx, const CCoinsViewCache* coinsView, const std::vector<CTransactionRef>* blockTxs){
2753  CScript script;
2754  bool scriptFilled=false; //can't use script.empty() because an empty script is technically valid
2755 
2756  // First check the current (or in-progress) block for zero-confirmation change spending that won't yet be in txindex
2757  if(blockTxs){
2758  for(auto btx : *blockTxs){
2759  if(btx->GetHash() == tx.vin[0].prevout.hash){
2760  script = btx->vout[tx.vin[0].prevout.n].scriptPubKey;
2761  scriptFilled=true;
2762  break;
2763  }
2764  }
2765  }
2766  if(!scriptFilled && coinsView){
2767  script = coinsView->AccessCoin(tx.vin[0].prevout).out.scriptPubKey;
2768  scriptFilled = true;
2769  }
2770  if(!scriptFilled)
2771  {
2772  CTransactionRef txPrevout;
2773  uint256 hashBlock;
2774  if(GetTransaction(tx.vin[0].prevout.hash, txPrevout, Params().GetConsensus(), hashBlock, true)){
2775  script = txPrevout->vout[tx.vin[0].prevout.n].scriptPubKey;
2776  } else {
2777  LogPrintf("Error fetching transaction details of tx %s. This will probably cause more errors", tx.vin[0].prevout.hash.ToString());
2778  return valtype();
2779  }
2780  }
2781 
2782  CTxDestination addressBit;
2783  txnouttype txType=TX_NONSTANDARD;
2784  if(ExtractDestination(script, addressBit, &txType)){
2785  if ((txType == TX_PUBKEY || txType == TX_PUBKEYHASH) &&
2786  addressBit.type() == typeid(CKeyID)){
2787  CKeyID senderAddress(boost::get<CKeyID>(addressBit));
2788  return valtype(senderAddress.begin(), senderAddress.end());
2789  }
2790  }
2791  //prevout is not a standard transaction format, so just return 0
2792  return valtype();
2793 }
2794 
2795 UniValue vmLogToJSON(const ResultExecute& execRes, const CTransaction& tx, const CBlock& block){
2796  UniValue result(UniValue::VOBJ);
2797  if(tx != CTransaction())
2798  result.push_back(Pair("txid", tx.GetHash().GetHex()));
2799  result.push_back(Pair("address", execRes.execRes.newAddress.hex()));
2800  if(block.GetHash() != CBlock().GetHash()){
2801  result.push_back(Pair("time", block.GetBlockTime()));
2802  result.push_back(Pair("blockhash", block.GetHash().GetHex()));
2803  result.push_back(Pair("blockheight", chainActive.Tip()->nHeight + 1));
2804  } else {
2805  result.push_back(Pair("time", GetAdjustedTime()));
2806  result.push_back(Pair("blockheight", chainActive.Tip()->nHeight));
2807  }
2808  UniValue logEntries(UniValue::VARR);
2809  dev::eth::LogEntries logs = execRes.txRec.log();
2810  for(dev::eth::LogEntry log : logs){
2811  UniValue logEntrie(UniValue::VOBJ);
2812  logEntrie.push_back(Pair("address", log.address.hex()));
2813  UniValue topics(UniValue::VARR);
2814  for(dev::h256 l : log.topics){
2815  UniValue topicPair(UniValue::VOBJ);
2816  topicPair.push_back(Pair("raw", l.hex()));
2817  topics.push_back(topicPair);
2818  //TODO add "pretty" field for human readable data
2819  }
2820  UniValue dataPair(UniValue::VOBJ);
2821  dataPair.push_back(Pair("raw", HexStr(log.data)));
2822  logEntrie.push_back(Pair("data", dataPair));
2823  logEntrie.push_back(Pair("topics", topics));
2824  logEntries.push_back(logEntrie);
2825  }
2826  result.push_back(Pair("entries", logEntries));
2827  return result;
2828 }
2829 
2830 void writeVMlog(const std::vector<ResultExecute>& res, const CTransaction& tx, const CBlock& block){
2831  boost::filesystem::path fascDir = GetDataDir() / "vmExecLogs.json";
2832  std::stringstream ss;
2833  if(fIsVMlogFile){
2834  ss << ",";
2835  } else {
2836  std::ofstream file(fascDir.string(), std::ios::out | std::ios::app);
2837  file << "{\"logs\":[]}";
2838  file.close();
2839  }
2840 
2841  for(size_t i = 0; i < res.size(); i++){
2842  ss << vmLogToJSON(res[i], tx, block).write();
2843  if(i != res.size() - 1){
2844  ss << ",";
2845  } else {
2846  ss << "]}";
2847  }
2848  }
2849 
2850  std::ofstream file(fascDir.string(), std::ios::in | std::ios::out);
2851  file.seekp(-2, std::ios::end);
2852  file << ss.str();
2853  file.close();
2854  fIsVMlogFile = true;
2855 }
2856 
2858  for(FascTransaction& tx : txs){
2859  //validate VM version
2860  if(tx.getVersion().toRaw() != VersionVM::GetEVMDefault().toRaw()){
2861  return false;
2862  }
2863  dev::eth::EnvInfo envInfo(BuildEVMEnvironment());
2864  if(!tx.isCreation() && !globalState->addressInUse(tx.receiveAddress())){
2865  dev::eth::ExecutionResult execRes;
2868  continue;
2869  }
2870  result.push_back(globalState->execute(envInfo, *globalSealEngine.get(), tx, type, OnOpFunc()));
2871  }
2872  globalState->db().commit();
2873  globalState->dbUtxo().commit();
2874  globalSealEngine.get()->deleteAddresses.clear();
2875  return true;
2876 }
2877 
2879  for(size_t i = 0; i < result.size(); i++){
2880  uint64_t gasUsed = (uint64_t) result[i].execRes.gasUsed;
2881  if(result[i].execRes.excepted != dev::eth::TransactionException::None){
2882  if(txs[i].value() > 0){
2884  tx.vin.push_back(CTxIn(h256Touint(txs[i].getHashWith()), txs[i].getNVout(), CScript() << OP_SPEND));
2885  CScript script(CScript() << OP_DUP << OP_HASH160 << txs[i].sender().asBytes() << OP_EQUALVERIFY << OP_CHECKSIG);
2886  tx.vout.push_back(CTxOut(CAmount(txs[i].value()), script));
2887  resultBCE.valueTransfers.push_back(CTransaction(tx));
2888  }
2889  resultBCE.usedGas += gasUsed;
2890  } else {
2891  if(txs[i].gas() > UINT64_MAX ||
2892  result[i].execRes.gasUsed > UINT64_MAX ||
2893  txs[i].gasPrice() > UINT64_MAX){
2894  return false;
2895  }
2896  uint64_t gas = (uint64_t) txs[i].gas();
2897  uint64_t gasPrice = (uint64_t) txs[i].gasPrice();
2898 
2899  resultBCE.usedGas += gasUsed;
2900  int64_t amount = (gas - gasUsed) * gasPrice;
2901  if(amount < 0){
2902  return false;
2903  }
2904  if(amount > 0){
2905  CScript script(CScript() << OP_DUP << OP_HASH160 << txs[i].sender().asBytes() << OP_EQUALVERIFY << OP_CHECKSIG);
2906  resultBCE.refundOutputs.push_back(CTxOut(amount, script));
2907  resultBCE.refundSender += amount;
2908  }
2909  }
2910  if(result[i].tx != CTransaction()){
2911  resultBCE.valueTransfers.push_back(result[i].tx);
2912  }
2913  }
2914  return true;
2915 }
2916 
2918  dev::eth::EnvInfo env;
2919  CBlockIndex* tip = chainActive.Tip();
2920  env.setNumber(dev::u256(tip->nHeight + 1));
2921  env.setTimestamp(dev::u256(block.nTime));
2922  env.setDifficulty(dev::u256(block.nBits));
2923 
2925  lh.resize(256);
2926  for(int i=0;i<256;i++){
2927  if(!tip)
2928  break;
2929  lh[i]= uintToh256(*tip->phashBlock);
2930  tip = tip->pprev;
2931  }
2932  env.setLastHashes(std::move(lh));
2933  env.setGasLimit(blockGasLimit);
2934 
2935  env.setAuthor(EthAddrFromScript(block.vtx[0]->vout[0].scriptPubKey));
2936  return env;
2937 }
2938 
2940  CTxDestination addressBit;
2941  txnouttype txType=TX_NONSTANDARD;
2942  if(ExtractDestination(script, addressBit, &txType)){
2943  if ((txType == TX_PUBKEY || txType == TX_PUBKEYHASH) &&
2944  addressBit.type() == typeid(CKeyID)){
2945  CKeyID addressKey(boost::get<CKeyID>(addressBit));
2946  std::vector<unsigned char> addr(addressKey.begin(), addressKey.end());
2947  return dev::Address(addr);
2948  }
2949  }
2950  //if not standard or not a pubkey or pubkeyhash output, then return 0
2951  return dev::Address();
2952 }
2953 
2955  std::vector<FascTransaction> resultTX;
2956  std::vector<EthTransactionParams> resultETP;
2957  for(size_t i = 0; i < txBit.vout.size(); i++){
2958  if(txBit.vout[i].scriptPubKey.HasOpCreate() || txBit.vout[i].scriptPubKey.HasOpCall()){
2959  if(receiveStack(txBit.vout[i].scriptPubKey)){
2960  EthTransactionParams params;
2961  if(parseEthTXParams(params)){
2962  resultTX.push_back(createEthTX(params, i));
2963  resultETP.push_back(params);
2964  }else{
2965  return false;
2966  }
2967  }else{
2968  return false;
2969  }
2970  }
2971  }
2972  fasctx = std::make_pair(resultTX, resultETP);
2973  return true;
2974 }
2975 
2976 bool FascTxConverter::receiveStack(const CScript& scriptPubKey){
2977  EvalScript(stack, scriptPubKey, SCRIPT_EXEC_BYTE_CODE, BaseSignatureChecker(), SIGVERSION_BASE, nullptr);
2978  if (stack.empty())
2979  return false;
2980 
2981  CScript scriptRest(stack.back().begin(), stack.back().end());
2982  stack.pop_back();
2983 
2984  opcode = (opcodetype)(*scriptRest.begin());
2985  if((opcode == OP_CREATE && stack.size() < 4) || (opcode == OP_CALL && stack.size() < 5)){
2986  stack.clear();
2987  return false;
2988  }
2989 
2990  return true;
2991 }
2992 
2994  try{
2995  dev::Address receiveAddress;
2996  valtype vecAddr;
2997  if (opcode == OP_CALL)
2998  {
2999  vecAddr = stack.back();
3000  stack.pop_back();
3001  receiveAddress = dev::Address(vecAddr);
3002  }
3003  if(stack.size() < 4)
3004  return false;
3005 
3006  if(stack.back().size() < 1){
3007  return false;
3008  }
3009  valtype code(stack.back());
3010  stack.pop_back();
3011  uint64_t gasPrice = CScriptNum::vch_to_uint64(stack.back());
3012  stack.pop_back();
3013  uint64_t gasLimit = CScriptNum::vch_to_uint64(stack.back());
3014  stack.pop_back();
3015  if(gasPrice > INT64_MAX || gasLimit > INT64_MAX){
3016  return false;
3017  }
3018  //we track this as CAmount in some places, which is an int64_t, so constrain to INT64_MAX
3019  if(gasPrice !=0 && gasLimit > INT64_MAX / gasPrice){
3020  //overflows past 64bits, reject this tx
3021  return false;
3022  }
3023  if(stack.back().size() > 4){
3024  return false;
3025  }
3027  stack.pop_back();
3028  params.version = version;
3029  params.gasPrice = dev::u256(gasPrice);
3030  params.receiveAddress = receiveAddress;
3031  params.code = code;
3032  params.gasLimit = dev::u256(gasLimit);
3033  return true;
3034  }
3035  catch(const scriptnum_error& err){
3036  LogPrintf("Incorrect parameters to VM.");
3037  return false;
3038  }
3039 }
3040 
3042  FascTransaction txEth;
3043  if (etp.receiveAddress == dev::Address() && opcode != OP_CALL){
3044  txEth = FascTransaction(txBit.vout[nOut].nValue, etp.gasPrice, etp.gasLimit, etp.code, dev::u256(0));
3045  }
3046  else{
3047  txEth = FascTransaction(txBit.vout[nOut].nValue, etp.gasPrice, etp.gasLimit, etp.receiveAddress, etp.code, dev::u256(0));
3048  }
3049  dev::Address sender(GetSenderAddress(txBit, view, blockTransactions));
3050  txEth.forceSender(sender);
3051  txEth.setHashWith(uintToh256(txBit.GetHash()));
3052  txEth.setNVout(nOut);
3053  txEth.setVersion(etp.version);
3054 
3055  return txEth;
3056 }
3058 
3060  CBlockIndex* pindex = nullptr;
3061  std::shared_ptr<const CBlock> pblock;
3062  std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
3063  PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
3064 };
3082 private:
3083  std::vector<PerBlockConnectTrace> blocksConnected;
3085 
3086 public:
3087  ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
3088  pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
3089  }
3090 
3092  pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
3093  }
3094 
3095  void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
3096  assert(!blocksConnected.back().pindex);
3097  assert(pindex);
3098  assert(pblock);
3099  blocksConnected.back().pindex = pindex;
3100  blocksConnected.back().pblock = std::move(pblock);
3101  blocksConnected.emplace_back();
3102  }
3103 
3104  std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
3105  // We always keep one extra block at the end of our list because
3106  // blocks are added after all the conflicted transactions have
3107  // been filled in. Thus, the last entry should always be an empty
3108  // one waiting for the transactions from the next block. We pop
3109  // the last entry here to make sure the list we return is sane.
3110  assert(!blocksConnected.back().pindex);
3111  assert(blocksConnected.back().conflictedTxs->empty());
3112  blocksConnected.pop_back();
3113  return blocksConnected;
3114  }
3115 
3117  assert(!blocksConnected.back().pindex);
3118  if (reason == MemPoolRemovalReason::CONFLICT) {
3119  blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
3120  }
3121  }
3122 };
3123 
3130 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
3131 {
3132  assert(pindexNew->pprev == chainActive.Tip());
3133  // Read block from disk.
3134  int64_t nTime1 = GetTimeMicros();
3135  std::shared_ptr<const CBlock> pthisBlock;
3136  if (!pblock) {
3137  std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
3138  if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
3139  return AbortNode(state, "Failed to read block");
3140  pthisBlock = pblockNew;
3141  } else {
3142  pthisBlock = pblock;
3143  }
3144  const CBlock& blockConnecting = *pthisBlock;
3145  // Apply the block atomically to the chain state.
3146  int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
3147  int64_t nTime3;
3148  LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
3149  {
3150  CCoinsViewCache view(pcoinsTip);
3151  dev::h256 oldHashStateRoot(globalState->rootHash()); // fasc
3152  dev::h256 oldHashUTXORoot(globalState->rootHashUTXO()); // fasc
3153  bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
3154  GetMainSignals().BlockChecked(blockConnecting, state);
3155  if (!rv) {
3156  if (state.IsInvalid())
3157  InvalidBlockFound(pindexNew, state);
3158  globalState->setRoot(oldHashStateRoot); // fasc
3159  globalState->setRootUTXO(oldHashUTXORoot); // fasc
3160  pstorageresult->clearCacheResult();
3161  return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
3162  }
3163  nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
3164  LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
3165  bool flushed = view.Flush();
3166  assert(flushed);
3167  }
3168  int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
3169  LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
3170  // Write the chain state to disk, if necessary.
3171  if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
3172  return false;
3173  int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
3174  LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
3175  // Remove conflicting transactions from the mempool.;
3176  mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
3177  disconnectpool.removeForBlock(blockConnecting.vtx);
3178  // Update chainActive & related variables.
3179  UpdateTip(pindexNew, chainparams);
3180 
3181  int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
3182  LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
3183  LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
3184 
3185  connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
3186  return true;
3187 }
3188 
3193 static CBlockIndex* FindMostWorkChain() {
3194  do {
3195  CBlockIndex *pindexNew = nullptr;
3196 
3197  // Find the best candidate header.
3198  {
3199  std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
3200  if (it == setBlockIndexCandidates.rend())
3201  return nullptr;
3202  pindexNew = *it;
3203  }
3204 
3205  // Check whether all blocks on the path between the currently active chain and the candidate are valid.
3206  // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
3207  CBlockIndex *pindexTest = pindexNew;
3208  bool fInvalidAncestor = false;
3209  while (pindexTest && !chainActive.Contains(pindexTest)) {
3210  assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
3211 
3212  // Pruned nodes may have entries in setBlockIndexCandidates for
3213  // which block files have been deleted. Remove those as candidates
3214  // for the most work chain if we come across them; we can't switch
3215  // to a chain unless we have all the non-active-chain parent blocks.
3216  bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
3217  bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
3218  if (fFailedChain || fMissingData) {
3219  // Candidate chain is not usable (either invalid or missing data)
3220  if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
3221  pindexBestInvalid = pindexNew;
3222  CBlockIndex *pindexFailed = pindexNew;
3223  // Remove the entire chain from the set.
3224  while (pindexTest != pindexFailed) {
3225  if (fFailedChain) {
3226  pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
3227  } else if (fMissingData) {
3228  // If we're missing data, then add back to mapBlocksUnlinked,
3229  // so that if the block arrives in the future we can try adding
3230  // to setBlockIndexCandidates again.
3231  mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
3232  }
3233  setBlockIndexCandidates.erase(pindexFailed);
3234  pindexFailed = pindexFailed->pprev;
3235  }
3236  setBlockIndexCandidates.erase(pindexTest);
3237  fInvalidAncestor = true;
3238  break;
3239  }
3240  pindexTest = pindexTest->pprev;
3241  }
3242  if (!fInvalidAncestor)
3243  return pindexNew;
3244  } while(true);
3245 }
3246 
3248 static void PruneBlockIndexCandidates() {
3249  // Note that we can't delete the current block itself, as we may need to return to it later in case a
3250  // reorganization to a better block fails.
3251  std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3252  while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
3253  setBlockIndexCandidates.erase(it++);
3254  }
3255  // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3256  assert(!setBlockIndexCandidates.empty());
3257 }
3258 
3263 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
3264 {
3265  AssertLockHeld(cs_main);
3266  const CBlockIndex *pindexOldTip = chainActive.Tip();
3267  const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
3268 
3269  // Disconnect active blocks which are no longer in the best chain.
3270  bool fBlocksDisconnected = false;
3271  DisconnectedBlockTransactions disconnectpool;
3272  while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
3273  if (!DisconnectTip(state, chainparams, &disconnectpool)) {
3274  // This is likely a fatal error, but keep the mempool consistent,
3275  // just in case. Only remove from the mempool in this case.
3276  UpdateMempoolForReorg(disconnectpool, false);
3277  return false;
3278  }
3279  fBlocksDisconnected = true;
3280  }
3281 
3282  // Build list of new blocks to connect.
3283  std::vector<CBlockIndex*> vpindexToConnect;
3284  int nHeight = pindexFork ? pindexFork->nHeight : -1;
3285  bool fContinue = true;
3286  while (fContinue && nHeight != pindexMostWork->nHeight) {
3287  // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3288  // a few blocks along the way.
3289  int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3290  vpindexToConnect.clear();
3291  vpindexToConnect.reserve(nTargetHeight - nHeight);
3292  CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3293  while (pindexIter && pindexIter->nHeight != nHeight) {
3294  vpindexToConnect.push_back(pindexIter);
3295  pindexIter = pindexIter->pprev;
3296  }
3297  nHeight = nTargetHeight;
3298 
3299  // Connect new blocks.
3300  for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
3301  if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
3302  if (state.IsInvalid()) {
3303  // The block violates a consensus rule.
3304  if (!state.CorruptionPossible())
3305  InvalidChainFound(vpindexToConnect.back());
3306  state = CValidationState();
3307  fInvalidFound = true;
3308  fContinue = false;
3309  break;
3310  } else {
3311  // A system error occurred (disk space, database error, ...).
3312  // Make the mempool consistent with the current tip, just in case
3313  // any observers try to use it before shutdown.
3314  UpdateMempoolForReorg(disconnectpool, false);
3315  return false;
3316  }
3317  } else {
3318  PruneBlockIndexCandidates();
3319  if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
3320  // We're in a better position than we were. Return temporarily to release the lock.
3321  fContinue = false;
3322  break;
3323  }
3324  }
3325  }
3326  }
3327 
3328  if (fBlocksDisconnected) {
3329  // If any blocks were disconnected, disconnectpool may be non empty. Add
3330  // any disconnected transactions back to the mempool.
3331  UpdateMempoolForReorg(disconnectpool, true);
3332  }
3333  mempool.check(pcoinsTip);
3334 
3335  // Callbacks/notifications for a new best chain.
3336  if (fInvalidFound)
3337  CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
3338  else
3339  CheckForkWarningConditions();
3340 
3341  return true;
3342 }
3343 
3344 static void NotifyHeaderTip() {
3345  bool fNotify = false;
3346  bool fInitialBlockDownload = false;
3347  static CBlockIndex* pindexHeaderOld = nullptr;
3348  CBlockIndex* pindexHeader = nullptr;
3349  {
3350  LOCK(cs_main);
3351  pindexHeader = pindexBestHeader;
3352 
3353  if (pindexHeader != pindexHeaderOld) {
3354  fNotify = true;
3355  fInitialBlockDownload = IsInitialBlockDownload();
3356  pindexHeaderOld = pindexHeader;
3357  }
3358  }
3359  // Send block tip changed notifications without cs_main
3360  if (fNotify) {
3361  uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
3362  }
3363 }
3364 
3370 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
3371  // Note that while we're often called here from ProcessNewBlock, this is
3372  // far from a guarantee. Things in the P2P/RPC will often end up calling
3373  // us in the middle of ProcessNewBlock - do not assume pblock is set
3374  // sanely for performance or correctness!
3375 
3376  CBlockIndex *pindexMostWork = nullptr;
3377  CBlockIndex *pindexNewTip = nullptr;
3378  int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
3379  do {
3380  boost::this_thread::interruption_point();
3381  if (ShutdownRequested())
3382  break;
3383 
3384  const CBlockIndex *pindexFork;
3385  bool fInitialDownload;
3386  {
3387  LOCK(cs_main);
3388  ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
3389 
3390  CBlockIndex *pindexOldTip = chainActive.Tip();
3391  if (pindexMostWork == nullptr) {
3392  pindexMostWork = FindMostWorkChain();
3393  }
3394 
3395  // Whether we have anything to do at all.
3396  if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip())
3397  return true;
3398 
3399  bool fInvalidFound = false;
3400  std::shared_ptr<const CBlock> nullBlockPtr;
3401  if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
3402  return false;
3403 
3404  if (fInvalidFound) {
3405  // Wipe cache, we may need another branch now.
3406  pindexMostWork = nullptr;
3407  }
3408  pindexNewTip = chainActive.Tip();
3409  pindexFork = chainActive.FindFork(pindexOldTip);
3410  fInitialDownload = IsInitialBlockDownload();
3411 
3412  for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
3413  assert(trace.pblock && trace.pindex);
3414  GetMainSignals().BlockConnected(trace.pblock, trace.pindex, *trace.conflictedTxs);
3415  }
3416  }
3417  // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3418 
3419  // Notifications/callbacks that can run without cs_main
3420 
3421  // Notify external listeners about the new tip.
3422  GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
3423 
3424  // Always notify the UI if a new block tip was connected
3425  if (pindexFork != pindexNewTip) {
3426  uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
3427  }
3428 
3429  if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
3430  } while (pindexNewTip != pindexMostWork);
3431  CheckBlockIndex(chainparams.GetConsensus());
3432 
3433  // Write changes periodically to disk, after relay.
3434  if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
3435  return false;
3436  }
3437 
3438  return true;
3439 }
3440 
3441 
3442 bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
3443 {
3444  {
3445  LOCK(cs_main);
3446  if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
3447  // Nothing to do, this block is not at the tip.
3448  return true;
3449  }
3450  if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
3451  // The chain has been extended since the last call, reset the counter.
3452  nBlockReverseSequenceId = -1;
3453  }
3454  nLastPreciousChainwork = chainActive.Tip()->nChainWork;
3455  setBlockIndexCandidates.erase(pindex);
3456  pindex->nSequenceId = nBlockReverseSequenceId;
3457  if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
3458  // We can't keep reducing the counter if somebody really wants to
3459  // call preciousblock 2**31-1 times on the same set of tips...
3460  nBlockReverseSequenceId--;
3461  }
3462  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
3463  setBlockIndexCandidates.insert(pindex);
3464  PruneBlockIndexCandidates();
3465  }
3466  }
3467 
3468  return ActivateBestChain(state, params);
3469 }
3470 
3471 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
3472 {
3473  AssertLockHeld(cs_main);
3474 
3475  // We first disconnect backwards and then mark the blocks as invalid.
3476  // This prevents a case where pruned nodes may fail to invalidateblock
3477  // and be left unable to start as they have no tip candidates (as there
3478  // are no blocks that meet the "have data and are not invalid per
3479  // nStatus" criteria for inclusion in setBlockIndexCandidates).
3480 
3481  pindex->nStatus |= BLOCK_FAILED_VALID;
3482  setDirtyBlockIndex.insert(pindex);
3483  setBlockIndexCandidates.erase(pindex);
3484  bool pindex_was_in_chain = false;
3485  CBlockIndex *invalid_walk_tip = chainActive.Tip();
3486 
3487  DisconnectedBlockTransactions disconnectpool;
3488  while (chainActive.Contains(pindex)) {
3489  CBlockIndex *pindexWalk = chainActive.Tip();
3490  pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3491  setDirtyBlockIndex.insert(pindexWalk);
3492  setBlockIndexCandidates.erase(pindexWalk);
3493  pindex_was_in_chain = true;
3494  // ActivateBestChain considers blocks already in chainActive
3495  // unconditionally valid already, so force disconnect away from it.
3496  if (!DisconnectTip(state, chainparams, &disconnectpool)) {
3497  // It's probably hopeless to try to make the mempool consistent
3498  // here if DisconnectTip failed, but we can try.
3499  mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3500  UpdateMempoolForReorg(disconnectpool, false);
3501  return false;
3502  }
3503  }
3504 
3505  // Now mark the blocks we just disconnected as descendants invalid
3506  // (note this may not be all descendants).
3507  while (pindex_was_in_chain && invalid_walk_tip != pindex) {
3508  invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
3509  setDirtyBlockIndex.insert(invalid_walk_tip);
3510  setBlockIndexCandidates.erase(invalid_walk_tip);
3511  invalid_walk_tip = invalid_walk_tip->pprev;
3512  }
3513  LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
3514 
3515  // Mark the block itself as invalid.
3516  pindex->nStatus |= BLOCK_FAILED_VALID;
3517  setDirtyBlockIndex.insert(pindex);
3518  setBlockIndexCandidates.erase(pindex);
3519  g_failed_blocks.insert(pindex);
3520 
3521  // DisconnectTip will add transactions to disconnectpool; try to add these
3522  // back to the mempool.
3523  UpdateMempoolForReorg(disconnectpool, true);
3524 
3525  // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3526  // add it again.
3527  BlockMap::iterator it = mapBlockIndex.begin();
3528  while (it != mapBlockIndex.end()) {
3529  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3530  setBlockIndexCandidates.insert(it->second);
3531  }
3532  it++;
3533  }
3534 
3535  InvalidChainFound(pindex);
3536  mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3538  return true;
3539 }
3540 
3542  AssertLockHeld(cs_main);
3543 
3544  int nHeight = pindex->nHeight;
3545 
3546  // Remove the invalidity flag from this block and all its descendants.
3547  BlockMap::iterator it = mapBlockIndex.begin();
3548  while (it != mapBlockIndex.end()) {
3549  if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3550  it->second->nStatus &= ~BLOCK_FAILED_MASK;
3551  setDirtyBlockIndex.insert(it->second);
3552  if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3553  setBlockIndexCandidates.insert(it->second);
3554  }
3555  if (it->second == pindexBestInvalid) {
3556  // Reset invalid block marker if it was pointing to one of those.
3557  pindexBestInvalid = nullptr;
3558  }
3559  g_failed_blocks.erase(it->second);
3560  }
3561  it++;
3562  }
3563 
3564  // Remove the invalidity flag from all ancestors too.
3565  while (pindex != nullptr) {
3566  if (pindex->nStatus & BLOCK_FAILED_MASK) {
3567  pindex->nStatus &= ~BLOCK_FAILED_MASK;
3568  setDirtyBlockIndex.insert(pindex);
3569  }
3570  pindex = pindex->pprev;
3571  }
3572  return true;
3573 }
3574 
3575 static CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3576 {
3577  // Check for duplicate
3578  uint256 hash = block.GetHash();
3579  BlockMap::iterator it = mapBlockIndex.find(hash);
3580  if (it != mapBlockIndex.end())
3581  return it->second;
3582 
3583  // Construct new block index object
3584  CBlockIndex* pindexNew = new CBlockIndex(block);
3585  assert(pindexNew);
3586  // We assign the sequence id to blocks only when the full data is available,
3587  // to avoid miners withholding blocks but broadcasting headers, to get a
3588  // competitive advantage.
3589  pindexNew->nSequenceId = 0;
3590  BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
3591  pindexNew->phashBlock = &((*mi).first);
3592  BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3593  if (miPrev != mapBlockIndex.end())
3594  {
3595  pindexNew->pprev = (*miPrev).second;
3596  pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3597  pindexNew->BuildSkip();
3598  }
3599  pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
3600  pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3601  pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3602  if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3603  pindexBestHeader = pindexNew;
3604 
3605  setDirtyBlockIndex.insert(pindexNew);
3606 
3607  return pindexNew;
3608 }
3609 
3611 static bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
3612 {
3613  pindexNew->nTx = block.vtx.size();
3614  pindexNew->nChainTx = 0;
3615  pindexNew->nFile = pos.nFile;
3616  pindexNew->nDataPos = pos.nPos;
3617  pindexNew->nUndoPos = 0;
3618  pindexNew->nStatus |= BLOCK_HAVE_DATA;
3619  if (IsWitnessEnabled(pindexNew->pprev, Params().GetConsensus())) {
3620  pindexNew->nStatus |= BLOCK_OPT_WITNESS;
3621  }
3623  setDirtyBlockIndex.insert(pindexNew);
3624 
3625  if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
3626  // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3627  std::deque<CBlockIndex*> queue;
3628  queue.push_back(pindexNew);
3629 
3630  // Recursively process any descendant blocks that now may be eligible to be connected.
3631  while (!queue.empty()) {
3632  CBlockIndex *pindex = queue.front();
3633  queue.pop_front();
3634  pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3635  {
3636  LOCK(cs_nBlockSequenceId);
3637  pindex->nSequenceId = nBlockSequenceId++;
3638  }
3639  if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3640  setBlockIndexCandidates.insert(pindex);
3641  }
3642  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3643  while (range.first != range.second) {
3644  std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3645  queue.push_back(it->second);
3646  range.first++;
3647  mapBlocksUnlinked.erase(it);
3648  }
3649  }
3650  } else {
3651  if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3652  mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3653  }
3654  }
3655 
3656  return true;
3657 }
3658 
3659 static bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3660 {
3661  LOCK(cs_LastBlockFile);
3662 
3663  unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3664  if (vinfoBlockFile.size() <= nFile) {
3665  vinfoBlockFile.resize(nFile + 1);
3666  }
3667 
3668  if (!fKnown) {
3669  while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3670  nFile++;
3671  if (vinfoBlockFile.size() <= nFile) {
3672  vinfoBlockFile.resize(nFile + 1);
3673  }
3674  }
3675  pos.nFile = nFile;
3676  pos.nPos = vinfoBlockFile[nFile].nSize;
3677  }
3678 
3679  if ((int)nFile != nLastBlockFile) {
3680  if (!fKnown) {
3681  LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
3682  }
3683  FlushBlockFile(!fKnown);
3684  nLastBlockFile = nFile;
3685  }
3686 
3687  vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3688  if (fKnown)
3689  vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3690  else
3691  vinfoBlockFile[nFile].nSize += nAddSize;
3692 
3693  if (!fKnown) {
3694  unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3695  unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3696  if (nNewChunks > nOldChunks) {
3697  if (fPruneMode)
3698  fCheckForPruning = true;
3699  if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3700  FILE *file = OpenBlockFile(pos);
3701  if (file) {
3702  LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3703  AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3704  fclose(file);
3705  }
3706  }
3707  else
3708  return state.Error("out of disk space");
3709  }
3710  }
3711 
3712  setDirtyFileInfo.insert(nFile);
3713  return true;
3714 }
3715 
3716 static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3717 {
3718  pos.nFile = nFile;
3719 
3720  LOCK(cs_LastBlockFile);
3721 
3722  unsigned int nNewSize;
3723  pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3724  nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3725  setDirtyFileInfo.insert(nFile);
3726 
3727  unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3728  unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3729  if (nNewChunks > nOldChunks) {
3730  if (fPruneMode)
3731  fCheckForPruning = true;
3732  if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3733  FILE *file = OpenUndoFile(pos);
3734  if (file) {
3735  LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3736  AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3737  fclose(file);
3738  }
3739  }
3740  else
3741  return state.Error("out of disk space");
3742  }
3743 
3744  return true;
3745 }
3746 
3747 static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
3748 {
3749  // Check Equihash solution is valid
3750  bool postfork = (uint32_t)block.nHeight >= (uint32_t)consensusParams.FABHeight;
3751  //LogPrintf("Debug CheckBlockHeader nHeight=%d %d %d ", block.nHeight, consensusParams.FABHeight, postfork );
3752  //LogPrintf("Debug blockheader=%s", block.ToString());
3753 
3754  if (fCheckPOW && postfork && !CheckEquihashSolution(&block, Params())) {
3755  LogPrintf("CheckBlockHeader(): Equihash solution invalid at height %d\n", block.nHeight);
3756  return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
3757  REJECT_INVALID, "invalid-solution");
3758  }
3759 
3760  // Check proof of work matches claimed amount
3761  if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, postfork, consensusParams)) {
3762  CBlock dumpBlock(block);
3763  LogPrintf("Dump block: Height %d, postfork=%d others == %s \n", block.nHeight, postfork, dumpBlock.ToString());
3764  return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
3765  }
3766 
3767  return true;
3768 }
3769 
3770 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot )
3771 {
3772  // These are checks that are independent of context.
3773 
3774  if (block.fChecked)
3775  return true;
3776 
3777  // Check that the header is valid (particularly PoW). This is mostly
3778  // redundant with the call in AcceptBlockHeader.
3779  if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
3780  return false;
3781 
3782  // Check the merkle root.
3783  if (fCheckMerkleRoot) {
3784  bool mutated;
3785  uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
3786  if (block.hashMerkleRoot != hashMerkleRoot2)
3787  return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
3788 
3789  // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3790  // of transactions in a block without affecting the merkle root of a block,
3791  // while still invalidating it.
3792  if (mutated)
3793  return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
3794  }
3795 
3796  // All potential-corruption validation must be done before we do any
3797  // transaction validation, as otherwise we may mark the header as invalid
3798  // because we receive the wrong transactions for it.
3799  // Note that witness malleability is checked in ContextualCheckBlock, so no
3800  // checks that use witness data may be performed here.
3801 
3802  // First transaction must be coinbase, the rest must not be
3803  if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
3804  return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
3805  for (unsigned int i = 1; i < block.vtx.size(); i++)
3806  if (block.vtx[i]->IsCoinBase())
3807  return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
3808  //Don't allow contract opcodes in coinbase
3809  if(block.vtx[0]->HasOpSpend() || block.vtx[0]->HasCreateOrCall()){
3810  return state.DoS(100, false, REJECT_INVALID, "bad-cb-contract", false, "coinbase must not contain OP_SPEND, OP_CALL, or OP_CREATE");
3811  }
3812 
3813  bool lastWasContract=false;
3814  // Check transactions
3815  for (const auto& tx : block.vtx) {
3816  //if (!CheckTransaction(*tx, state, false))
3817  if (!CheckTransaction(*tx, state, true))
3818  return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
3819  strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
3820  //OP_SPEND can only exist immediately after a contract tx in a block, or after another OP_SPEND
3821  //So, if the previous tx was not a contract tx, fail it.
3822  if(tx->HasOpSpend()){
3823  if(!lastWasContract){
3824  return state.DoS(100, false, REJECT_INVALID, "bad-opspend-tx", false, "OP_SPEND transaction without corresponding contract transaction");
3825  }
3826  }
3827  lastWasContract = tx->HasCreateOrCall() || tx->HasOpSpend();
3828  }
3829 
3830  unsigned int nSigOps = 0;
3831  for (const auto& tx : block.vtx)
3832  {
3833  nSigOps += GetLegacySigOpCount(*tx);
3834  }
3835  if (nSigOps * WITNESS_SCALE_FACTOR > dgpMaxBlockSigOps)
3836  return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3837 
3838  if (fCheckPOW && fCheckMerkleRoot)
3839  block.fChecked = true;
3840 
3841  return true;
3842 }
3843 
3844 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
3845 {
3846  LOCK(cs_main);
3848 }
3849 
3850 // Compute at which vout of the block's coinbase transaction the witness
3851 // commitment occurs, or -1 if not found.
3852 static int GetWitnessCommitmentIndex(const CBlock& block)
3853 {
3854  int commitpos = -1;
3855  if (!block.vtx.empty()) {
3856  for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
3857  if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
3858  commitpos = o;
3859  }
3860  }
3861  }
3862  return commitpos;
3863 }
3864 
3865 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3866 {
3867  int commitpos = GetWitnessCommitmentIndex(block);
3868  static const std::vector<unsigned char> nonce(32, 0x00);
3869  if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
3870  CMutableTransaction tx(*block.vtx[0]);
3871  tx.vin[0].scriptWitness.stack.resize(1);
3872  tx.vin[0].scriptWitness.stack[0] = nonce;
3873  block.vtx[0] = MakeTransactionRef(std::move(tx));
3874  }
3875 }
3876 
3877 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
3878 {
3879  std::vector<unsigned char> commitment;
3880  int commitpos = GetWitnessCommitmentIndex(block);
3881  std::vector<unsigned char> ret(32, 0x00);
3882  if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
3883  if (commitpos == -1) {
3884  uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
3885  CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
3886  CTxOut out;
3887  out.nValue = 0;
3888  out.scriptPubKey.resize(38);
3889  out.scriptPubKey[0] = OP_RETURN;
3890  out.scriptPubKey[1] = 0x24;
3891  out.scriptPubKey[2] = 0xaa;
3892  out.scriptPubKey[3] = 0x21;
3893  out.scriptPubKey[4] = 0xa9;
3894  out.scriptPubKey[5] = 0xed;
3895  memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
3896  commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
3897  CMutableTransaction tx(*block.vtx[0]);
3898  tx.vout.push_back(out);
3899  block.vtx[0] = MakeTransactionRef(std::move(tx));
3900  }
3901  }
3902  UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
3903  return commitment;
3904 }
3905 
3909 static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
3910 {
3911  assert(pindexPrev != nullptr);
3912  const int nHeight = pindexPrev->nHeight + 1;
3913 
3914  // Check proof of work
3915  const Consensus::Params& consensusParams = params.GetConsensus();
3916  if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3917  return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
3918 
3919  // Check against checkpoints
3920  if (fCheckpointsEnabled) {
3921  // Don't accept any forks from the main chain prior to last checkpoint.
3922  // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
3923  // MapBlockIndex.
3924  CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
3925  if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3926  return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
3927  }
3928 
3929  // Check block height for blocks after FAB fork. TODO-J
3930  //if (nHeight >= consensusParams.FABHeight && block.nHeight != (uint32_t)nHeight)
3931  // return state.Invalid(false, REJECT_INVALID, "bad-height", "incorrect block height");
3932 
3933  //LogPrintf(" Debug block.GetBlockTime() =%d pindexPrev->GetMedianTimePast=%d nAdjustedTime=%d MAX_FUTURE_BLOCK_TIME=%d ", block.GetBlockTime(), pindexPrev->GetMedianTimePast(), nAdjustedTime, MAX_FUTURE_BLOCK_TIME );
3934 
3935  // Check timestamp against prev
3936  //if (pindexPrev && block.IsProofOfStake() && block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3937  if (pindexPrev && block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3938  return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
3939 
3940  // Check timestamp
3941  //if (block.IsProofOfStake() && block.GetBlockTime() > FutureDrift(nAdjustedTime)){
3942  if (block.GetBlockTime() > nAdjustedTime + std::min(consensusParams.MaxFutureBlockTime, MAX_FUTURE_BLOCK_TIME)){
3943  LogPrintf(" Debug block.GetBlockTime() =%d =%d MAX_FUTURE_BLOCK_TIME=%d MaxFutureBlockTime=%d", block.GetBlockTime(), nAdjustedTime, MAX_FUTURE_BLOCK_TIME, consensusParams.MaxFutureBlockTime);
3944  return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
3945  }
3946 
3947  // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3948  // check for version 2, 3 and 4 upgrades
3949  if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
3950  (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
3951  (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
3952  return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
3953  strprintf("rejected nVersion=0x%08x block", block.nVersion));
3954 
3955  return true;
3956 }
3957 
3958 static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
3959 {
3960  const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
3961 
3962  // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3963  int nLockTimeFlags = 0;
3964  if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3965  nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3966  }
3967 
3968  int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3969  ? pindexPrev->GetMedianTimePast()
3970  : block.GetBlockTime();
3971 
3972  // Check that all transactions are finalized
3973  for (const auto& tx : block.vtx) {
3974  if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
3975  return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3976  }
3977  }
3978 
3979  // Enforce rule that the coinbase starts with serialized block height
3980  if (nHeight >= consensusParams.BIP34Height)
3981  {
3982  CScript expect = CScript() << nHeight;
3983  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
3984  !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
3985  return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3986  }
3987  }
3988 
3989  // Validation for witness commitments.
3990  // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
3991  // coinbase (where 0x0000....0000 is used instead).
3992  // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
3993  // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
3994  // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
3995  // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
3996  // multiple, the last one is used.
3997  bool fHaveWitness = false;
3998  if ( IsWitnessEnabled(pindexPrev, consensusParams) ) {
3999  int commitpos = GetWitnessCommitmentIndex(block);
4000  if (commitpos != -1) {
4001  bool malleated = false;
4002  uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
4003  // The malleation check is ignored; as the transaction tree itself
4004  // already does not permit it, it is impossible to trigger in the
4005  // witness tree.
4006  if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
4007  return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
4008  }
4009  CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
4010  if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
4011  return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
4012  }
4013  fHaveWitness = true;
4014  }
4015  }
4016 
4017  // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
4018  if (!fHaveWitness) {
4019  for (const auto& tx : block.vtx) {
4020  if (tx->HasWitness()) {
4021  return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
4022  }
4023  }
4024  }
4025 
4026  return true;
4027 }
4028  static bool UpdateHashProof(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex* pindex, CCoinsViewCache& view)
4029  {
4030 
4031  // Check proof-of-work
4032  if (block.nBits != GetNextWorkRequired(pindex->pprev, &block, consensusParams))
4033  return state.DoS(100, error("UpdateHashProof() : incorrect %s", "proof-of-work" ));
4034 
4035  uint256 hashProof;
4036  hashProof = block.GetHash();
4037  pindex->hashProof = hashProof;
4038 
4039  // Record proof hash value
4040  return true;
4041  }
4042 
4043 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
4044 {
4045  AssertLockHeld(cs_main);
4046  // Check for duplicate
4047  uint256 hash = block.GetHash();
4048  BlockMap::iterator miSelf = mapBlockIndex.find(hash);
4049  CBlockIndex *pindex = nullptr;
4050 
4051  if (hash != chainparams.GetConsensus().hashGenesisBlock) {
4052  //LogPrintf("debug AcceptBlockHeader() bypass-already-known header %s(%d)\n", block.GetHash().ToString() , block.nHeight);
4053  if (miSelf != mapBlockIndex.end()) {
4054  // Block header is already known.
4055  pindex = miSelf->second;
4056  if (ppindex)
4057  *ppindex = pindex;
4058  if (pindex->nStatus & BLOCK_FAILED_MASK)
4059  return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
4060  return true;
4061  }
4062 
4063  //int nBlockMaxConflict = gArgs.GetArg("-blockmaxconflict", DEFAULT_BLOCK_MAX_CONFLICT);
4064  int nBlockMaxConflict = gArgs.GetArg("-blockmaxconflict", 0);
4065  int conflict_blocks = chainActive.Tip()->nHeight - (block.nHeight -1);
4066 
4067  if ( (nBlockMaxConflict > 0 ) && (conflict_blocks >= nBlockMaxConflict ) ) {
4068  LogPrintf("Invalid block=%s(%d) conflicted with currenainActive.Tip()=%s(%d) about %d blocks before, more than blockmaxconflict(%d) setting.\n" , block.GetHash().ToString(), block.nHeight, chainActive.Tip()->GetBlockHash().ToString(), chainActive.Tip()->nHeight, conflict_blocks , nBlockMaxConflict ) ;
4069 
4070  return state.DoS(10, error("block conflicted with current bestblock chain more than blockmaxconflict setting"), REJECT_INVALID, "invalid-blocks-over-blockmaxconflict");
4071  }
4072 
4073  //LogPrintf("debug AcceptBlockHeader CheckBlockHeader %s(%d)\n", block.GetHash().ToString() , block.nHeight);
4074  if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
4075  return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
4076 
4077  // Get prev block index
4078  //LogPrintf("debug AcceptBlockHeader check-prev-block-index %s(%d) - %s\n", block.GetHash().ToString() , block.nHeight, block.hashPrevBlock.ToString());
4079  CBlockIndex* pindexPrev = nullptr;
4080  BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
4081  if (mi == mapBlockIndex.end())
4082  return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
4083  pindexPrev = (*mi).second;
4084  if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
4085  return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
4086 
4087  //LogPrintf("debug ContextualCheckBlockHeader() %s(%d)\n", block.GetHash().ToString(), block.nHeight);
4088  if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
4089  return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
4090 
4091  if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
4092  for (const CBlockIndex* failedit : g_failed_blocks) {
4093  if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
4094  assert(failedit->nStatus & BLOCK_FAILED_VALID);
4095  CBlockIndex* invalid_walk = pindexPrev;
4096  while (invalid_walk != failedit) {
4097  invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
4098  setDirtyBlockIndex.insert(invalid_walk);
4099  invalid_walk = invalid_walk->pprev;
4100  }
4101  return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
4102  }
4103  }
4104  }
4105  }
4106 
4107  if (pindex == nullptr) {
4108  //LogPrintf("debug AddToBlockIndex() %s(%d)\n", block.GetHash().ToString(), block.nHeight);
4109  pindex = AddToBlockIndex(block);
4110  }
4111 
4112  if (ppindex)
4113  *ppindex = pindex;
4114 
4115  //LogPrintf("debug CheckBlockIndex() %s(%d)\n", block.GetHash().ToString(), block.nHeight);
4116  CheckBlockIndex(chainparams.GetConsensus());
4117 
4118  return true;
4119 }
4120 
4121 // Exposed wrapper for AcceptBlockHeader
4122 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
4123 {
4124  if (first_invalid != nullptr) first_invalid->SetNull();
4125  {
4126  LOCK(cs_main);
4127  for (const CBlockHeader& header : headers) {
4128  CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
4129  //LogPrintf("debug AcceptBlockHeader() %s(%d) headers.size=%d \n", header.GetHash().ToString(), header.nHeight, headers.size() );
4130  if (!AcceptBlockHeader(header, state, chainparams, &pindex)) {
4131  if (first_invalid) *first_invalid = header;
4132  return false;
4133  }
4134  if (ppindex) {
4135  *ppindex = pindex;
4136  }
4137  }
4138  }
4139  NotifyHeaderTip();
4140  return true;
4141 }
4142 
4144 static bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
4145 {
4146  const CBlock& block = *pblock;
4147 
4148  if (fNewBlock) *fNewBlock = false;
4149  AssertLockHeld(cs_main);
4150 
4151  CBlockIndex *pindexDummy = nullptr;
4152  CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
4153 
4154  if (!AcceptBlockHeader(block, state, chainparams, &pindex))
4155  return false;
4156 
4157  if (!UpdateHashProof(block, state, chainparams.GetConsensus(), pindex, *pcoinsTip)) {
4158  return error("%s: AcceptBlock(): %s", __func__, state.GetRejectReason().c_str());
4159  }
4160 
4161  // Get block height
4162  int nHeight = pindex->nHeight;
4163 
4164  // Check that the block satisfies synchronized checkpoint
4165  if (!Checkpoints::CheckSync(nHeight))
4166  return error("AcceptBlock() : rejected by synchronized checkpoint");
4167 
4168  // Enforce rule that the coinbase starts with serialized block height
4169  CScript expect = CScript() << nHeight;
4170  if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
4171  !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin()))
4172  return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
4173 
4174  // Try to process all requested blocks that we don't have, but only
4175  // process an unrequested block if it's new and has enough work to
4176  // advance our tip, and isn't too many blocks ahead.
4177  bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
4178  bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
4179  // Blocks that are too out-of-order needlessly limit the effectiveness of
4180  // pruning, because pruning will not delete block files that contain any
4181  // blocks which are too close in height to the tip. Apply this test
4182  // regardless of whether pruning is enabled; it should generally be safe to
4183  // not process unrequested blocks.
4184  bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
4185 
4186  // TODO: Decouple this function from the block download logic by removing fRequested
4187  // This requires some new chain data structure to efficiently look up if a
4188  // block is in a chain leading to a candidate for best tip, despite not
4189  // being such a candidate itself.
4190 
4191  // TODO: deal better with return value and error conditions for duplicate
4192  // and unrequested blocks.
4193  if (fAlreadyHave) return true;
4194  if (!fRequested) { // If we didn't ask for it:
4195  if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
4196  if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
4197  if (fTooFarAhead) return true; // Block height is too high
4198 
4199  // Protect against DoS attacks from low-work chains.
4200  // If our tip is behind, a peer could try to send us
4201  // low-work blocks on a fake chain that we would never
4202  // request; don't process these.
4203  if (pindex->nChainWork < nMinimumChainWork) return true;
4204  }
4205  if (fNewBlock) *fNewBlock = true;
4206 
4207  if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
4208  !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
4209  if (state.IsInvalid() && !state.CorruptionPossible()) {
4210  pindex->nStatus |= BLOCK_FAILED_VALID;
4211  setDirtyBlockIndex.insert(pindex);
4212  }
4213  return error("%s: %s", __func__, FormatStateMessage(state));
4214  }
4215 
4216  // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
4217  // (but if it does not build on our best tip, let the SendMessages loop relay it)
4218  if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
4219  GetMainSignals().NewPoWValidBlock(pindex, pblock);
4220 
4221  // Write block to history file
4222  try {
4223  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4224  CDiskBlockPos blockPos;
4225  if (dbp != nullptr)
4226  blockPos = *dbp;
4227  if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr))
4228  return error("AcceptBlock(): FindBlockPos failed");
4229  if (dbp == nullptr)
4230  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4231  AbortNode(state, "Failed to write block");
4232  if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
4233  return error("AcceptBlock(): ReceivedBlockTransactions failed");
4234  } catch (const std::runtime_error& e) {
4235  return AbortNode(state, std::string("System error: ") + e.what());
4236  }
4237 
4238  if (fCheckForPruning)
4239  FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
4240 
4241  return true;
4242 }
4243 
4244 bool static IsCanonicalBlockSignature(const std::shared_ptr<const CBlock> pblock, bool checkLowS)
4245 {
4246  //TODO-J this fucntion is for POS, leave it empty
4247  return true;
4248 }
4249 
4250 bool CheckCanonicalBlockSignature(const std::shared_ptr<const CBlock> pblock)
4251 {
4252  //block signature encoding
4253  bool ret = IsCanonicalBlockSignature(pblock, false);
4254 
4255  //block signature encoding (low-s)
4256  if(ret) ret = IsCanonicalBlockSignature(pblock, true);
4257 
4258  return ret;
4259 }
4260 
4261 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
4262 {
4263  {
4264  CBlockIndex *pindex = nullptr;
4265  if (fNewBlock) *fNewBlock = false;
4266  CValidationState state;
4267  // Ensure that CheckBlock() passes before calling AcceptBlock, as
4268  // belt-and-suspenders.
4269  //LogPrintf("debug CheckBlock %s(%d)\n", pblock->GetHash().ToString(), pblock->nHeight);
4270  bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
4271 
4272  if (!ret) {
4273  GetMainSignals().BlockChecked(*pblock, state);
4274  return error("%s: CheckBlock FAILED", __func__);
4275  }
4276 
4277  LOCK(cs_main);
4278 
4279  if (ret) {
4280  // Store to disk
4281  //LogPrintf("debug AcceptBlock %s(%d)\n", pblock->GetHash().ToString(), pblock->nHeight);
4282  ret = AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
4283  }
4284 
4285  //LogPrintf("debug CheckBlockIndex %s(%d)\n", pblock->GetHash().ToString(), pblock->nHeight);
4286  CheckBlockIndex(chainparams.GetConsensus());
4287  if (!ret) {
4288  GetMainSignals().BlockChecked(*pblock, state);
4289  return error("%s: AcceptBlock FAILED", __func__);
4290  }
4291  }
4292 
4293  //LogPrintf("debug NotifyHeaderTip %s(%d)\n", pblock->GetHash().ToString(), pblock->nHeight);
4294  NotifyHeaderTip();
4295 
4296  CValidationState state; // Only used to report errors, not invalidity - ignore it
4297  //LogPrintf("debug ActivateBestChain %s(%d)\n", pblock->GetHash().ToString(), pblock->nHeight);
4298  if (!ActivateBestChain(state, chainparams, pblock))
4299  return error("%s: ActivateBestChain failed", __func__);
4300 
4301  return true;
4302 }
4303 
4304 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
4305 {
4306  AssertLockHeld(cs_main);
4307  assert(pindexPrev && pindexPrev == chainActive.Tip());
4308  CCoinsViewCache viewNew(pcoinsTip);
4309  CBlockIndex indexDummy(block);
4310  indexDummy.pprev = pindexPrev;
4311  indexDummy.nHeight = pindexPrev->nHeight + 1;
4312 
4313  // NOTE: CheckBlockHeader is called by CheckBlock
4314  if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
4315  return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
4316  if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
4317  return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
4318  if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
4319  return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
4320  dev::h256 oldHashStateRoot(globalState->rootHash()); // fasc
4321  dev::h256 oldHashUTXORoot(globalState->rootHashUTXO()); // fasc
4322 
4323  if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true)) {
4324 
4325  globalState->setRoot(oldHashStateRoot); // fasc
4326  globalState->setRootUTXO(oldHashUTXORoot); // fasc
4328 
4329  return false;
4330  }
4331  assert(state.IsValid());
4332 
4333  return true;
4334 }
4335 
4340 /* Calculate the amount of disk space the block & undo files currently use */
4341 static uint64_t CalculateCurrentUsage()
4342 {
4343  uint64_t retval = 0;
4344  for (const CBlockFileInfo &file : vinfoBlockFile) {
4345  retval += file.nSize + file.nUndoSize;
4346  }
4347  return retval;
4348 }
4349 
4350 /* Prune a block file (modify associated database entries)*/
4351 void PruneOneBlockFile(const int fileNumber)
4352 {
4353  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
4354  CBlockIndex* pindex = it->second;
4355  if (pindex->nFile == fileNumber) {
4356  pindex->nStatus &= ~BLOCK_HAVE_DATA;
4357  pindex->nStatus &= ~BLOCK_HAVE_UNDO;
4358  pindex->nFile = 0;
4359  pindex->nDataPos = 0;
4360  pindex->nUndoPos = 0;
4361  setDirtyBlockIndex.insert(pindex);
4362 
4363  // Prune from mapBlocksUnlinked -- any block we prune would have
4364  // to be downloaded again in order to consider its chain, at which
4365  // point it would be considered as a candidate for
4366  // mapBlocksUnlinked or setBlockIndexCandidates.
4367  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
4368  while (range.first != range.second) {
4369  std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
4370  range.first++;
4371  if (_it->second == pindex) {
4372  mapBlocksUnlinked.erase(_it);
4373  }
4374  }
4375  }
4376  }
4377 
4378  vinfoBlockFile[fileNumber].SetNull();
4379  setDirtyFileInfo.insert(fileNumber);
4380 }
4381 
4382 
4383 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
4384 {
4385  for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
4386  CDiskBlockPos pos(*it, 0);
4387  fs::remove(GetBlockPosFilename(pos, "blk"));
4388  fs::remove(GetBlockPosFilename(pos, "rev"));
4389  LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
4390  }
4391 }
4392 
4393 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
4394 static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
4395 {
4396  assert(fPruneMode && nManualPruneHeight > 0);
4397 
4398  LOCK2(cs_main, cs_LastBlockFile);
4399  if (chainActive.Tip() == nullptr)
4400  return;
4401 
4402  // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
4403  unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
4404  int count=0;
4405  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
4406  if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
4407  continue;
4408  PruneOneBlockFile(fileNumber);
4409  setFilesToPrune.insert(fileNumber);
4410  count++;
4411  }
4412  LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
4413 }
4414 
4415 /* This function is called from the RPC code for pruneblockchain */
4416 void PruneBlockFilesManual(int nManualPruneHeight)
4417 {
4418  CValidationState state;
4419  const CChainParams& chainparams = Params();
4420  FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
4421 }
4422 
4438 static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
4439 {
4440  LOCK2(cs_main, cs_LastBlockFile);
4441  if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
4442  return;
4443  }
4444  if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
4445  return;
4446  }
4447 
4448  unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
4449  uint64_t nCurrentUsage = CalculateCurrentUsage();
4450  // We don't check to prune until after we've allocated new space for files
4451  // So we should leave a buffer under our target to account for another allocation
4452  // before the next pruning.
4453  uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
4454  uint64_t nBytesToPrune;
4455  int count=0;
4456 
4457  if (nCurrentUsage + nBuffer >= nPruneTarget) {
4458  for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
4459  nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
4460 
4461  if (vinfoBlockFile[fileNumber].nSize == 0)
4462  continue;
4463 
4464  if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
4465  break;
4466 
4467  // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
4468  if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
4469  continue;
4470 
4471  PruneOneBlockFile(fileNumber);
4472  // Queue up the files for removal
4473  setFilesToPrune.insert(fileNumber);
4474  nCurrentUsage -= nBytesToPrune;
4475  count++;
4476  }
4477  }
4478 
4479  LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
4480  nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
4481  ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
4482  nLastBlockWeCanPrune, count);
4483 }
4484 
4485 bool CheckDiskSpace(uint64_t nAdditionalBytes)
4486 {
4487  uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
4488 
4489  // Check for nMinDiskSpace bytes (currently 50MB)
4490  if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
4491  return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
4492 
4493  return true;
4494 }
4495 
4496 static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
4497 {
4498  if (pos.IsNull())
4499  return nullptr;
4500  fs::path path = GetBlockPosFilename(pos, prefix);
4501  fs::create_directories(path.parent_path());
4502  FILE* file = fsbridge::fopen(path, "rb+");
4503  if (!file && !fReadOnly)
4504  file = fsbridge::fopen(path, "wb+");
4505  if (!file) {
4506  LogPrintf("Unable to open file %s\n", path.string());
4507  return nullptr;
4508  }
4509  if (pos.nPos) {
4510  if (fseek(file, pos.nPos, SEEK_SET)) {
4511  LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
4512  fclose(file);
4513  return nullptr;
4514  }
4515  }
4516  return file;
4517 }
4518 
4519 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
4520  return OpenDiskFile(pos, "blk", fReadOnly);
4521 }
4522 
4524 static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
4525  return OpenDiskFile(pos, "rev", fReadOnly);
4526 }
4527 
4528 fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
4529 {
4530  return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
4531 }
4532 
4534 {
4535  if (hash.IsNull())
4536  return nullptr;
4537 
4538  // Return existing
4539  BlockMap::iterator mi = mapBlockIndex.find(hash);
4540  if (mi != mapBlockIndex.end())
4541  return (*mi).second;
4542 
4543  // Create new
4544  CBlockIndex* pindexNew = new CBlockIndex();
4545  if (!pindexNew)
4546  throw std::runtime_error(std::string(__func__) + ": new CBlockIndex failed");
4547  mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
4548  pindexNew->phashBlock = &((*mi).first);
4549 
4550  return pindexNew;
4551 }
4552 
4553 bool static LoadBlockIndexDB(const CChainParams& chainparams)
4554 {
4556  return false;
4557 
4558  boost::this_thread::interruption_point();
4559 
4560  // Calculate nChainWork
4561  std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
4562  vSortedByHeight.reserve(mapBlockIndex.size());
4563  for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
4564  {
4565  CBlockIndex* pindex = item.second;
4566  vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
4567  }
4568  sort(vSortedByHeight.begin(), vSortedByHeight.end());
4569  for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
4570  {
4571  CBlockIndex* pindex = item.second;
4572  pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
4573  pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
4574  // We can link the chain of blocks for which we've received transactions at some point.
4575  // Pruned nodes may have deleted the block.
4576  if (pindex->nTx > 0) {
4577  if (pindex->pprev) {
4578  if (pindex->pprev->nChainTx) {
4579  pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
4580  } else {
4581  pindex->nChainTx = 0;
4582  mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
4583  }
4584  } else {
4585  pindex->nChainTx = pindex->nTx;
4586  }
4587  }
4588  if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
4589  pindex->nStatus |= BLOCK_FAILED_CHILD;
4590  setDirtyBlockIndex.insert(pindex);
4591  }
4592  if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
4593  setBlockIndexCandidates.insert(pindex);
4594  if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
4595  pindexBestInvalid = pindex;
4596  if (pindex->pprev)
4597  pindex->BuildSkip();
4598  if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
4599  pindexBestHeader = pindex;
4600  }
4601 
4602  // Load block file info
4603  pblocktree->ReadLastBlockFile(nLastBlockFile);
4604  vinfoBlockFile.resize(nLastBlockFile + 1);
4605  LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
4606  for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
4607  pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
4608  }
4609  LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
4610  for (int nFile = nLastBlockFile + 1; true; nFile++) {
4611  CBlockFileInfo info;
4612  if (pblocktree->ReadBlockFileInfo(nFile, info)) {
4613  vinfoBlockFile.push_back(info);
4614  } else {
4615  break;
4616  }
4617  }
4618 
4619  // Check presence of blk files
4620  LogPrintf("Checking all blk files are present...\n");
4621  std::set<int> setBlkDataFiles;
4622  for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
4623  {
4624  CBlockIndex* pindex = item.second;
4625  if (pindex->nStatus & BLOCK_HAVE_DATA) {
4626  setBlkDataFiles.insert(pindex->nFile);
4627  }
4628  }
4629  for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
4630  {
4631  CDiskBlockPos pos(*it, 0);
4632  if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
4633  return false;
4634  }
4635  }
4636 
4637  // Check whether we have ever pruned block & undo files
4638  pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
4639  if (fHavePruned)
4640  LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4641 
4642  // Check whether we need to continue reindexing
4643  bool fReindexing = false;
4644  pblocktree->ReadReindexing(fReindexing);
4645  fReindex |= fReindexing;
4646 
4647  // Check whether we have a transaction index
4648  pblocktree->ReadFlag("txindex", fTxIndex);
4649  LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
4650  // Check whether we have a transaction index
4651  pblocktree->ReadFlag("logevents", fLogEvents);
4652  LogPrintf("%s: log events index %s\n", __func__, fLogEvents ? "enabled" : "disabled");
4653 
4654  //-------------------------
4655  // Load pointer to end of best chain
4656  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
4657  if (it == mapBlockIndex.end())
4658  return true;
4659  chainActive.SetTip(it->second);
4660 
4661  PruneBlockIndexCandidates();
4662 
4663  LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
4664  chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
4665  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
4666  GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
4667  //------------------------------
4668  return true;
4669 }
4670 
4671 bool LoadChainTip(const CChainParams& chainparams)
4672 {
4673  if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
4674 
4675  if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
4676  // In case we just added the genesis block, connect it now, so
4677  // that we always have a chainActive.Tip() when we return.
4678  LogPrintf("%s: Connecting genesis block...\n", __func__);
4679  CValidationState state;
4680  if (!ActivateBestChain(state, chainparams)) {
4681  return false;
4682  }
4683  }
4684 
4685  // Load pointer to end of best chain
4686  BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
4687  if (it == mapBlockIndex.end())
4688  return false;
4689  chainActive.SetTip(it->second);
4690 
4691  PruneBlockIndexCandidates();
4692 
4693  LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
4694  chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
4695  DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
4696  GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
4697  return true;
4698 }
4699 
4701 {
4702  uiInterface.ShowProgress(_("Verifying blocks..."), 0);
4703 }
4704 
4706 {
4707  uiInterface.ShowProgress("", 100);
4708 }
4709 
4710 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
4711 {
4712  LOCK(cs_main);
4713  if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
4714  return true;
4715 
4716  // Verify blocks in the best chain
4717  if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
4718  nCheckDepth = chainActive.Height();
4719  nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4720  LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
4721  CCoinsViewCache coins(coinsview);
4722  CBlockIndex* pindexState = chainActive.Tip();
4723  CBlockIndex* pindexFailure = nullptr;
4724  int nGoodTransactions = 0;
4725  CValidationState state;
4726  int reportDone = 0;
4728  dev::h256 oldHashStateRoot(globalState->rootHash());
4729  dev::h256 oldHashUTXORoot(globalState->rootHashUTXO());
4730  FascDGP fascDGP(globalState.get(), fGettingValuesDGP);
4732  LogPrintf("[0%%]...");
4733  for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
4734  {
4735  boost::this_thread::interruption_point();
4736  int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
4737  if (reportDone < percentageDone/10) {
4738  // report every 10% step
4739  LogPrintf("[%d%%]...", percentageDone);
4740  reportDone = percentageDone/10;
4741  }
4742  uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone);
4743  if (pindex->nHeight < chainActive.Height()-nCheckDepth)
4744  break;
4745  if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
4746  // If pruning, only go back as far as we have data.
4747  LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
4748  break;
4749  }
4751  uint32_t sizeBlockDGP = fascDGP.getBlockSize(pindex->nHeight);
4752  dgpMaxBlockSize = sizeBlockDGP ? sizeBlockDGP : dgpMaxBlockSize;
4755  CBlock block;
4756  // check level 0: read from disk
4757  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
4758  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4759  // check level 1: verify block validity
4760  if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
4761  return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
4762  pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
4763  // check level 2: verify undo validity
4764  if (nCheckLevel >= 2 && pindex) {
4765  CBlockUndo undo;
4766  CDiskBlockPos pos = pindex->GetUndoPos();
4767  if (!pos.IsNull()) {
4768  if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
4769  return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4770  }
4771  }
4772  // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4773  if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
4774  assert(coins.GetBestBlock() == pindex->GetBlockHash());
4775  bool fClean=true;
4776  DisconnectResult res = DisconnectBlock(block, pindex, coins, &fClean);
4777  if (res == DISCONNECT_FAILED) {
4778  return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4779  }
4780  pindexState = pindex->pprev;
4781  if (res == DISCONNECT_UNCLEAN) {
4782  nGoodTransactions = 0;
4783  pindexFailure = pindex;
4784  } else {
4785  nGoodTransactions += block.vtx.size();
4786  }
4787  }
4788  if (ShutdownRequested())
4789  return true;
4790  }
4791  if (pindexFailure)
4792  return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4793 
4794  // check level 4: try reconnecting blocks
4795  if (nCheckLevel >= 4) {
4796  CBlockIndex *pindex = pindexState;
4797  while (pindex != chainActive.Tip()) {
4798  boost::this_thread::interruption_point();
4799  uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
4800  pindex = chainActive.Next(pindex);
4801  CBlock block;
4802  if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
4803  return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4804  dev::h256 oldHashStateRoot(globalState->rootHash()); // fasc
4805  dev::h256 oldHashUTXORoot(globalState->rootHashUTXO()); // fasc
4806 
4807  if (!ConnectBlock(block, state, pindex, coins, chainparams)) {
4808 
4809  globalState->setRoot(oldHashStateRoot); // fasc
4810  globalState->setRootUTXO(oldHashUTXORoot); // fasc
4812 
4813  return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4814  }
4815  }
4816  } else {
4817  globalState->setRoot(oldHashStateRoot); // fasc
4818  globalState->setRootUTXO(oldHashUTXORoot); // fasc
4819  }
4820 
4821  LogPrintf("[DONE].\n");
4822  LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
4823 
4824  return true;
4825 }
4826 
4828 static bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
4829 {
4830  // TODO: merge with ConnectBlock
4831  CBlock block;
4832  if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
4833  return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4834  }
4835 
4836  for (const CTransactionRef& tx : block.vtx) {
4837  if (!tx->IsCoinBase()) {
4838  for (const CTxIn &txin : tx->vin) {
4839  inputs.SpendCoin(txin.prevout);
4840  }
4841  }
4842  // Pass check = true as every addition may be an overwrite.
4843  AddCoins(inputs, *tx, pindex->nHeight, true);
4844  }
4845  return true;
4846 }
4847 
4848 bool ReplayBlocks(const CChainParams& params, CCoinsView* view)
4849 {
4850  LOCK(cs_main);
4851 
4852  CCoinsViewCache cache(view);
4853 
4854  std::vector<uint256> hashHeads = view->GetHeadBlocks();
4855  if (hashHeads.empty()) return true; // We're already in a consistent state.
4856  if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
4857 
4858  uiInterface.ShowProgress(_("Replaying blocks..."), 0);
4859  LogPrintf("Replaying blocks\n");
4860 
4861  const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
4862  const CBlockIndex* pindexNew; // New tip during the interrupted flush.
4863  const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
4864 
4865  if (mapBlockIndex.count(hashHeads[0]) == 0) {
4866  return error("ReplayBlocks(): reorganization to unknown block requested");
4867  }
4868  pindexNew = mapBlockIndex[hashHeads[0]];
4869 
4870  if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
4871  if (mapBlockIndex.count(hashHeads[1]) == 0) {
4872  return error("ReplayBlocks(): reorganization from unknown block requested");
4873  }
4874  pindexOld = mapBlockIndex[hashHeads[1]];
4875  pindexFork = LastCommonAncestor(pindexOld, pindexNew);
4876  assert(pindexFork != nullptr);
4877  }
4878 
4879  // Rollback along the old branch.
4880  while (pindexOld != pindexFork) {
4881  if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
4882  CBlock block;
4883  if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
4884  return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4885  }
4886  LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
4887  bool fClean=true;
4888  DisconnectResult res = DisconnectBlock(block, pindexOld, cache, &fClean);
4889  if (res == DISCONNECT_FAILED) {
4890  return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
4891  }
4892  // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
4893  // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
4894  // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
4895  // the result is still a version of the UTXO set with the effects of that block undone.
4896  }
4897  pindexOld = pindexOld->pprev;
4898  }
4899 
4900  // Roll forward from the forking point to the new tip.
4901  int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
4902  for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
4903  const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
4904  LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
4905  if (!RollforwardBlock(pindex, cache, params)) return false;
4906  }
4907 
4908  cache.SetBestBlock(pindexNew->GetBlockHash());
4909  cache.Flush();
4910  uiInterface.ShowProgress("", 100);
4911  return true;
4912 }
4913 
4914 bool RewindBlockIndex(const CChainParams& params)
4915 {
4916  LOCK(cs_main);
4917 
4918  // Note that during -reindex-chainstate we are called with an empty chainActive!
4919 
4920  int nHeight = 1;
4921  while (nHeight <= chainActive.Height()) {
4922  if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
4923  break;
4924  }
4925  nHeight++;
4926  }
4927 
4928  // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4929  CValidationState state;
4930  CBlockIndex* pindex = chainActive.Tip();
4931  while (chainActive.Height() >= nHeight) {
4932  if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4933  // If pruning, don't try rewinding past the HAVE_DATA point;
4934  // since older blocks can't be served anyway, there's
4935  // no need to walk further, and trying to DisconnectTip()
4936  // will fail (and require a needless reindex/redownload
4937  // of the blockchain).
4938  break;
4939  }
4940  if (!DisconnectTip(state, params, nullptr)) {
4941  return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4942  }
4943  // Occasionally flush state to disk.
4944  if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
4945  return false;
4946  }
4947 
4948  // Reduce validity flag and have-data flags.
4949  // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4950  // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4951  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4952  CBlockIndex* pindexIter = it->second;
4953 
4954  // Note: If we encounter an insufficiently validated block that
4955  // is on chainActive, it must be because we are a pruning node, and
4956  // this block or some successor doesn't HAVE_DATA, so we were unable to
4957  // rewind all the way. Blocks remaining on chainActive at this point
4958  // must not have their validity reduced.
4959  if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
4960  // Reduce validity
4961  pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
4962  // Remove have-data flags.
4963  pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4964  // Remove storage location.
4965  pindexIter->nFile = 0;
4966  pindexIter->nDataPos = 0;
4967  pindexIter->nUndoPos = 0;
4968  // Remove various other things
4969  pindexIter->nTx = 0;
4970  pindexIter->nChainTx = 0;
4971  pindexIter->nSequenceId = 0;
4972  // Make sure it gets written.
4973  setDirtyBlockIndex.insert(pindexIter);
4974  // Update indexes
4975  setBlockIndexCandidates.erase(pindexIter);
4976  std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4977  while (ret.first != ret.second) {
4978  if (ret.first->second == pindexIter) {
4979  mapBlocksUnlinked.erase(ret.first++);
4980  } else {
4981  ++ret.first;
4982  }
4983  }
4984  } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4985  setBlockIndexCandidates.insert(pindexIter);
4986  }
4987  }
4988 
4989  if (chainActive.Tip() != nullptr) {
4990  // We can't prune block index candidates based on our tip if we have
4991  // no tip due to chainActive being empty!
4992  PruneBlockIndexCandidates();
4993 
4994  CheckBlockIndex(params.GetConsensus());
4995 
4996  // FlushStateToDisk can possibly read chainActive. Be conservative
4997  // and skip it here, we're about to -reindex-chainstate anyway, so
4998  // it'll get called a bunch real soon.
4999  if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
5000  return false;
5001  }
5002  }
5003 
5004  return true;
5005 }
5006 
5007 // May NOT be used after any connections are up as much
5008 // of the peer-processing logic assumes a consistent
5009 // block index state
5011 {
5012  LOCK(cs_main);
5013  setBlockIndexCandidates.clear();
5014  chainActive.SetTip(nullptr);
5015  pindexBestInvalid = nullptr;
5016  pindexBestHeader = nullptr;
5017  mempool.clear();
5018  mapBlocksUnlinked.clear();
5019  vinfoBlockFile.clear();
5020  nLastBlockFile = 0;
5021  nBlockSequenceId = 1;
5022  setDirtyBlockIndex.clear();
5023  g_failed_blocks.clear();
5024  setDirtyFileInfo.clear();
5026  for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
5027  warningcache[b].clear();
5028  }
5029 
5030  for (BlockMap::value_type& entry : mapBlockIndex) {
5031  delete entry.second;
5032  }
5033  mapBlockIndex.clear();
5034  fHavePruned = false;
5035 }
5036 
5037 bool LoadBlockIndex(const CChainParams& chainparams)
5038 {
5039  // Load block index from databases
5040  bool needs_init = fReindex;
5041  if (!fReindex) {
5042  bool ret = LoadBlockIndexDB(chainparams);
5043  if (!ret) return false;
5044  needs_init = mapBlockIndex.empty();
5045  }
5046 
5047  if (needs_init) {
5048  // Everything here is for *new* reindex/DBs. Thus, though
5049  // LoadBlockIndexDB may have set fReindex if we shut down
5050  // mid-reindex previously, we don't check fReindex and
5051  // instead only check it prior to LoadBlockIndexDB to set
5052  // needs_init.
5053 
5054  LogPrintf("Initializing databases...\n");
5055  // Use the provided setting for -txindex in the new database
5056  fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
5057  pblocktree->WriteFlag("txindex", fTxIndex);
5058 
5059  // Use the provided setting for -logevents in the new database
5060  fLogEvents = gArgs.GetBoolArg("-logevents", DEFAULT_LOGEVENTS);
5061  pblocktree->WriteFlag("logevents", fLogEvents);
5062  }
5063  return true;
5064 }
5065 
5066 //------------------------
5067 bool InitBlockIndex(const CChainParams& chainparams)
5068 {
5069  LOCK(cs_main);
5070 
5071  // Check whether we're already initialized
5072  if (chainActive.Genesis() != nullptr)
5073  return true;
5074 
5075  // Use the provided setting for -txindex in the new database
5076  fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
5077  pblocktree->WriteFlag("txindex", fTxIndex);
5078 
5079  // Use the provided setting for -txindex in the new database
5080  fLogEvents = gArgs.GetBoolArg("-logevents", DEFAULT_LOGEVENTS);
5081  pblocktree->WriteFlag("logevents", fLogEvents);
5082  LogPrintf("Initializing databases...\n");
5083 
5084  // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
5085  if (!fReindex) {
5086  try {
5087  CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
5088  // Start new block file
5089  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
5090  CDiskBlockPos blockPos;
5091  CValidationState state;
5092  if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
5093  return error("LoadBlockIndex(): FindBlockPos failed");
5094  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
5095  return error("LoadBlockIndex(): writing genesis block to disk failed");
5096 
5097  CBlockIndex *pindex = AddToBlockIndex(block);
5098  pindex->hashProof = chainparams.GetConsensus().hashGenesisBlock;
5099  if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
5100  return error("LoadBlockIndex(): genesis block not accepted");
5101  // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
5102  return FlushStateToDisk();
5103  //return true;
5104  } catch (const std::runtime_error& e) {
5105  return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
5106  }
5107  }
5108 
5109  return true;
5110 }
5111 bool LoadGenesisBlock(const CChainParams& chainparams)
5112 {
5113  LOCK(cs_main);
5114 
5115  // Check whether we're already initialized by checking for genesis in
5116  // mapBlockIndex. Note that we can't use chainActive here, since it is
5117  // set based on the coins db, not the block index db, which is the only
5118  // thing loaded at this point.
5119  if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
5120  return true;
5121 
5122  try {
5123  CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
5124  // Start new block file
5125  unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
5126  CDiskBlockPos blockPos;
5127  CValidationState state;
5128  if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
5129  return error("%s: FindBlockPos failed", __func__);
5130  if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
5131  return error("%s: writing genesis block to disk failed", __func__);
5132  CBlockIndex *pindex = AddToBlockIndex(block);
5133  //pindex->hashProof = chainparams.GetConsensus().hashGenesisBlock;
5134  if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
5135  return error("%s: genesis block not accepted", __func__);
5136  } catch (const std::runtime_error& e) {
5137  return error("%s: failed to write genesis block: %s", __func__, e.what());
5138  }
5139 
5140  return true;
5141 }
5142 
5143 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
5144 {
5145  // Map of disk positions for blocks with unknown parent (only used for reindex)
5146  static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
5147  int64_t nStart = GetTimeMillis();
5148 
5149  int nLoaded = 0;
5150  try {
5151  // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
5152  CBufferedFile blkdat(fileIn, 2*dgpMaxBlockSerSize, dgpMaxBlockSerSize+8, SER_DISK, CLIENT_VERSION);
5153  uint64_t nRewind = blkdat.GetPos();
5154  while (!blkdat.eof()) {
5155  boost::this_thread::interruption_point();
5156 
5157  blkdat.SetPos(nRewind);
5158  nRewind++; // start one byte further next time, in case of failure
5159  blkdat.SetLimit(); // remove former limit
5160  unsigned int nSize = 0;
5161  try {
5162  // locate a header
5163  unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
5164  blkdat.FindByte(chainparams.MessageStart()[0]);
5165  nRewind = blkdat.GetPos()+1;
5166  blkdat >> FLATDATA(buf);
5167  if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
5168  continue;
5169  // read size
5170  blkdat >> nSize;
5171  if (nSize < 80 || nSize > dgpMaxBlockSerSize )
5172  continue;
5173  } catch (const std::exception&) {
5174  // no valid block header found; don't complain
5175  break;
5176  }
5177  try {
5178  // read block
5179  uint64_t nBlockPos = blkdat.GetPos();
5180  if (dbp)
5181  dbp->nPos = nBlockPos;
5182  blkdat.SetLimit(nBlockPos + nSize);
5183  blkdat.SetPos(nBlockPos);
5184  std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
5185  CBlock& block = *pblock;
5186  blkdat >> block;
5187  nRewind = blkdat.GetPos();
5188 
5189  // detect out of order blocks, and store them for later
5190  uint256 hash = block.GetHash();
5191  if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
5192  LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
5193  block.hashPrevBlock.ToString());
5194  if (dbp)
5195  mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
5196  continue;
5197  }
5198 
5199  // process in case the block isn't known yet
5200  if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
5201  LOCK(cs_main);
5202  CValidationState state;
5203  if (AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
5204  nLoaded++;
5205  if (state.IsError())
5206  break;
5207  } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
5208  LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
5209  }
5210 
5211  // In Bitcoin this only needed to be done for genesis and at the end of block indexing
5212  // But for Fabcoin PoS we need to sync this after every block to ensure txdb is populated for
5213  // validating PoS proofs
5214  //---- if (hash == chainparams.GetConsensus().hashGenesisBlock) {
5215  {
5216  CValidationState state;
5217  if (!ActivateBestChain(state, chainparams)) {
5218  break;
5219  }
5220  }
5221 
5222  NotifyHeaderTip();
5223 
5224  // Recursively process earlier encountered successors of this block
5225  std::deque<uint256> queue;
5226  queue.push_back(hash);
5227  while (!queue.empty()) {
5228  uint256 head = queue.front();
5229  queue.pop_front();
5230  std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
5231  while (range.first != range.second) {
5232  std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
5233  std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
5234  if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
5235  {
5236  LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
5237  head.ToString());
5238  LOCK(cs_main);
5239  CValidationState dummy;
5240  if (AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
5241  {
5242  nLoaded++;
5243  queue.push_back(pblockrecursive->GetHash());
5244  }
5245  }
5246  range.first++;
5247  mapBlocksUnknownParent.erase(it);
5248  NotifyHeaderTip();
5249  }
5250  }
5251  } catch (const std::exception& e) {
5252  LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
5253  }
5254  }
5255  } catch (const std::runtime_error& e) {
5256  AbortNode(std::string("System error: ") + e.what());
5257  }
5258  if (nLoaded > 0)
5259  LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
5260  return nLoaded > 0;
5261 }
5262 
5263 void static CheckBlockIndex(const Consensus::Params& consensusParams)
5264 {
5265  if (!fCheckBlockIndex) {
5266  return;
5267  }
5268 
5269  LOCK(cs_main);
5270 
5271  // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
5272  // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
5273  // iterating the block tree require that chainActive has been initialized.)
5274  if (chainActive.Height() < 0) {
5275  assert(mapBlockIndex.size() <= 1);
5276  return;
5277  }
5278 
5279  // Build forward-pointing map of the entire block tree.
5280  std::multimap<CBlockIndex*,CBlockIndex*> forward;
5281  for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
5282  forward.insert(std::make_pair(it->second->pprev, it->second));
5283  }
5284 
5285  assert(forward.size() == mapBlockIndex.size());
5286 
5287  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
5288  CBlockIndex *pindex = rangeGenesis.first->second;
5289  rangeGenesis.first++;
5290  assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
5291 
5292  // Iterate over the entire block tree, using depth-first search.
5293  // Along the way, remember whether there are blocks on the path from genesis
5294  // block being explored which are the first to have certain properties.
5295  size_t nNodes = 0;
5296  int nHeight = 0;
5297  CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
5298  CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
5299  CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
5300  CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
5301  CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
5302  CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
5303  CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
5304  while (pindex != nullptr) {
5305  nNodes++;
5306  if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
5307  if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
5308  if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
5309  if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
5310  if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
5311  if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
5312  if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
5313 
5314  // Begin: actual consistency checks.
5315  if (pindex->pprev == nullptr) {
5316  // Genesis block checks.
5317  assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
5318  assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
5319  }
5320  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)
5321  // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
5322  // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
5323  if (!fHavePruned) {
5324  // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
5325  assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
5326  assert(pindexFirstMissing == pindexFirstNeverProcessed);
5327  } else {
5328  // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
5329  if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
5330  }
5331  if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
5332  assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
5333  // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
5334  assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
5335  assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
5336  assert(pindex->nHeight == nHeight); // nHeight must be consistent.
5337  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.
5338  assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
5339  assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
5340  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
5341  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
5342  if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
5343  if (pindexFirstInvalid == nullptr) {
5344  // Checks for not-invalid blocks.
5345  assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
5346  }
5347  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
5348  if (pindexFirstInvalid == nullptr) {
5349  // If this block sorts at least as good as the current tip and
5350  // is valid and we have all data for its parents, it must be in
5351  // setBlockIndexCandidates. chainActive.Tip() must also be there
5352  // even if some data has been pruned.
5353  if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
5354  assert(setBlockIndexCandidates.count(pindex));
5355  }
5356  // If some parent is missing, then it could be that this block was in
5357  // setBlockIndexCandidates but had to be removed because of the missing data.
5358  // In this case it must be in mapBlocksUnlinked -- see test below.
5359  }
5360  } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
5361  assert(setBlockIndexCandidates.count(pindex) == 0);
5362  }
5363  // Check whether this block is in mapBlocksUnlinked.
5364  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
5365  bool foundInUnlinked = false;
5366  while (rangeUnlinked.first != rangeUnlinked.second) {
5367  assert(rangeUnlinked.first->first == pindex->pprev);
5368  if (rangeUnlinked.first->second == pindex) {
5369  foundInUnlinked = true;
5370  break;
5371  }
5372  rangeUnlinked.first++;
5373  }
5374  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
5375  // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
5376  assert(foundInUnlinked);
5377  }
5378  if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
5379  if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
5380  if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
5381  // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
5382  assert(fHavePruned); // We must have pruned.
5383  // This block may have entered mapBlocksUnlinked if:
5384  // - it has a descendant that at some point had more work than the
5385  // tip, and
5386  // - we tried switching to that descendant but were missing
5387  // data for some intermediate block between chainActive and the
5388  // tip.
5389  // So if this block is itself better than chainActive.Tip() and it wasn't in
5390  // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
5391  if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
5392  if (pindexFirstInvalid == nullptr) {
5393  assert(foundInUnlinked);
5394  }
5395  }
5396  }
5397  // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
5398  // End: actual consistency checks.
5399 
5400  // Try descending into the first subnode.
5401  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
5402  if (range.first != range.second) {
5403  // A subnode was found.
5404  pindex = range.first->second;
5405  nHeight++;
5406  continue;
5407  }
5408  // This is a leaf node.
5409  // Move upwards until we reach a node of which we have not yet visited the last child.
5410  while (pindex) {
5411  // We are going to either move to a parent or a sibling of pindex.
5412  // If pindex was the first with a certain property, unset the corresponding variable.
5413  if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
5414  if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
5415  if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
5416  if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
5417  if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
5418  if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
5419  if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
5420  // Find our parent.
5421  CBlockIndex* pindexPar = pindex->pprev;
5422  // Find which child we just visited.
5423  std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
5424  while (rangePar.first->second != pindex) {
5425  assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
5426  rangePar.first++;
5427  }
5428  // Proceed to the next one.
5429  rangePar.first++;
5430  if (rangePar.first != rangePar.second) {
5431  // Move to the sibling.
5432  pindex = rangePar.first->second;
5433  break;
5434  } else {
5435  // Move up further.
5436  pindex = pindexPar;
5437  nHeight--;
5438  continue;
5439  }
5440  }
5441  }
5442 
5443  // Check that we actually traversed the entire map.
5444  assert(nNodes == forward.size());
5445 }
5446 
5447 std::string CBlockFileInfo::ToString() const
5448 {
5449  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));
5450 }
5451 
5453 {
5454  return &vinfoBlockFile.at(n);
5455 }
5456 
5458 {
5459  LOCK(cs_main);
5460  return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
5461 }
5462 
5464 {
5465  LOCK(cs_main);
5466  return VersionBitsStatistics(chainActive.Tip(), params, pos);
5467 }
5468 
5470 {
5471  LOCK(cs_main);
5472  return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
5473 }
5474 
5475 static const uint64_t MEMPOOL_DUMP_VERSION = 1;
5476 
5477 bool LoadMempool(void)
5478 {
5479  const CChainParams& chainparams = Params();
5480  int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
5481  FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
5482  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
5483  if (file.IsNull()) {
5484  LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
5485  return false;
5486  }
5487 
5488  int64_t count = 0;
5489  int64_t skipped = 0;
5490  int64_t failed = 0;
5491  int64_t nNow = GetTime();
5492 
5493  try {
5494  uint64_t version;
5495  file >> version;
5496  if (version != MEMPOOL_DUMP_VERSION) {
5497  return false;
5498  }
5499  uint64_t num;
5500  file >> num;
5501  while (num--) {
5502  CTransactionRef tx;
5503  int64_t nTime;
5504  int64_t nFeeDelta;
5505  file >> tx;
5506  file >> nTime;
5507  file >> nFeeDelta;
5508 
5509  CAmount amountdelta = nFeeDelta;
5510  if (amountdelta) {
5511  mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
5512  }
5513  CValidationState state;
5514  if (nTime + nExpiryTimeout > nNow) {
5515  LOCK(cs_main);
5516  AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, true, nullptr, nTime, nullptr, false, 0);
5517  if (state.IsValid()) {
5518  ++count;
5519  } else {
5520  ++failed;
5521  }
5522  } else {
5523  ++skipped;
5524  }
5525  if (ShutdownRequested())
5526  return false;
5527  }
5528  std::map<uint256, CAmount> mapDeltas;
5529  file >> mapDeltas;
5530 
5531  for (const auto& i : mapDeltas) {
5532  mempool.PrioritiseTransaction(i.first, i.second);
5533  }
5534  } catch (const std::exception& e) {
5535  LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
5536  return false;
5537  }
5538 
5539  LogPrintf("Imported mempool transactions from disk: %i successes, %i failed, %i expired\n", count, failed, skipped);
5540  return true;
5541 }
5542 
5543 void DumpMempool(void)
5544 {
5545  int64_t start = GetTimeMicros();
5546 
5547  std::map<uint256, CAmount> mapDeltas;
5548  std::vector<TxMempoolInfo> vinfo;
5549 
5550  {
5551  LOCK(mempool.cs);
5552  for (const auto &i : mempool.mapDeltas) {
5553  mapDeltas[i.first] = i.second;
5554  }
5555  vinfo = mempool.infoAll();
5556  }
5557 
5558  int64_t mid = GetTimeMicros();
5559 
5560  try {
5561  FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
5562  if (!filestr) {
5563  return;
5564  }
5565 
5566  CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
5567 
5568  uint64_t version = MEMPOOL_DUMP_VERSION;
5569  file << version;
5570 
5571  file << (uint64_t)vinfo.size();
5572  for (const auto& i : vinfo) {
5573  file << *(i.tx);
5574  file << (int64_t)i.nTime;
5575  file << (int64_t)i.nFeeDelta;
5576  mapDeltas.erase(i.tx->GetHash());
5577  }
5578 
5579  file << mapDeltas;
5580  FileCommit(file.Get());
5581  file.fclose();
5582  RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
5583  int64_t last = GetTimeMicros();
5584  LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*0.000001, (last-mid)*0.000001);
5585  } catch (const std::exception& e) {
5586  LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
5587  }
5588 }
5589 
5592  if (pindex == nullptr)
5593  return 0.0;
5594 
5595  int64_t nNow = time(nullptr);
5596 
5597  double fTxTotal;
5598 
5599  if (pindex->nChainTx <= data.nTxCount) {
5600  fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
5601  } else {
5602  fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
5603  }
5604 
5605  return pindex->nChainTx / fTxTotal;
5606 }
5607 
5609 {
5610 public:
5613  // block headers
5614  BlockMap::iterator it1 = mapBlockIndex.begin();
5615  for (; it1 != mapBlockIndex.end(); it1++)
5616  delete (*it1).second;
5617  mapBlockIndex.clear();
5618  }
bool fLogEvents
Definition: validation.cpp:88
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:205
std::pair< std::vector< FascTransaction >, std::vector< EthTransactionParams >> ExtractFascTX
Definition: validation.h:50
CAmount nValue
Definition: transaction.h:134
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:252
CTxMemPool & pool
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:201
std::vector< ResultExecute > & getResult()
Definition: validation.h:762
CTxMemPool mempool
bool parseEthTXParams(EthTransactionParams &params)
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:996
bool IsPayToPubkeyHash() const
Definition: script.cpp:231
bool error(const char *fmt, const Args &...args)
Definition: util.h:178
int Expire(int64_t time)
Expire all transaction (and their dependencies) in the mempool older than time.
Definition: txmempool.cpp:934
dev::eth::ExecutionResult execRes
Definition: fascstate.h:33
std::vector< Coin > vprevout
Definition: undo.h:71
bool HasOpCreate() const
Definition: script.h:697
int64_t EndTime(const Consensus::Params &params) const override
bool IsPayToPubkey() const
Definition: script.cpp:218
CDiskBlockPos GetBlockPos() const
Definition: chain.h:288
void resize(size_type new_size)
Definition: prevector.h:316
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: chain.h:232
int nScriptCheckThreads
Definition: validation.cpp:84
std::function< void(uint64_t, uint64_t, dev::eth::Instruction, dev::bigint, dev::bigint, dev::bigint, dev::eth::VM *, dev::eth::ExtVMFace const *)> OnOpFunc
Definition: fascstate.h:15
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:79
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool potential_overwrite)
Add a coin.
Definition: coins.cpp:69
void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason)
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:90
CBlockIndex * pskip
pointer to the index of some further predecessor of this block
Definition: chain.h:190
uint256 GetRandHash()
Definition: random.cpp:372
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
uint256 BIP34Hash
Definition: params.h:46
unsigned int nTxOffset
Definition: txdb.h:50
boost::condition_variable CConditionVariable
Just a typedef for boost::condition_variable, can be wrapped later if desired.
Definition: sync.h:103
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:133
std::vector< CTransactionRef > conflictedTxs
Definition: validation.cpp:214
void UnloadBlockIndex()
Unload database information.
void Add(std::vector< T > &vChecks)
Definition: checkqueue.h:201
bool CheckTxInputs(const CTransaction &tx, CValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:224
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:5
int Threshold(const Consensus::Params &params) const override
bool EraseHeightIndex(const unsigned int &height)
Definition: txdb.cpp:328
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:251
double dTxRate
Definition: chainparams.h:37
CScript scriptPubKey
Definition: transaction.h:135
descends from failed block
Definition: chain.h:166
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:184
void pop_back()
Definition: prevector.h:420
ThresholdState GetStateFor(const CBlockIndex *pindexPrev, const Consensus::Params &params, ThresholdConditionCache &cache) const
Definition: versionbits.cpp:23
bool CheckTransaction(const CTransaction &tx, CValidationState &state, bool fCheckDuplicateInputs)
Transaction validation functions.
Definition: tx_verify.cpp:161
bool EvaluateSequenceLocks(const CBlockIndex &block, std::pair< int, int64_t > lockPair)
Definition: tx_verify.cpp:94
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Definition: txmempool.cpp:479
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:204
bool IsError() const
Definition: validation.h:72
void FileCommit(FILE *file)
Definition: util.cpp:744
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:30
unsigned int dgpMaxBlockSerSize
The maximum allowed size for a serialized block, in bytes (only for buffer size limits) ...
Definition: consensus.cpp:6
bool performByteCode(dev::eth::Permanence type=dev::eth::Permanence::Committed)
void swap(CScriptCheck &check)
Definition: validation.h:563
static const std::string REGTEST
A UTXO entry.
Definition: coins.h:29
bytes rlp(_T _t)
Export a single item in RLP format, returning a byte array.
Definition: RLP.h:467
Definition: block.h:155
CBlockIndex * pindexBestForkBase
int64_t BeginTime(const Consensus::Params &params) const override
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
bool ShutdownRequested()
Definition: init.cpp:126
uint8_t rootVM
#define strprintf
Definition: tinyformat.h:1054
bool ReadReindexing(bool &fReindex)
Definition: txdb.cpp:168
An in-memory indexed chain of blocks.
Definition: chain.h:501
bool VerifyDB(const CChainParams &chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
bool receiveStack(const CScript &scriptPubKey)
bool InvalidateBlock(CValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex)
Mark a block as invalid.
CAmount maxTxFee
Absolute maximum transaction fee (in liu) used by wallet and mempool (rejects high fee in sendrawtran...
Definition: validation.cpp:104
uint256 GetWitnessHash() const
Definition: transaction.cpp:71
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: txmempool.cpp:900
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:89
reverse_range< T > reverse_iterate(T &x)
CHash256 & Write(const unsigned char *data, size_t len)
Definition: hash.h:33
int Period(const Consensus::Params &params) const override
bool ReadLastBlockFile(int &nFile)
Definition: txdb.cpp:173
CWaitableCriticalSection csBestBlock
Definition: validation.cpp:82
std::vector< CTxIn > vin
Definition: transaction.h:392
bool fRecordLogOpcodes
Definition: validation.cpp:72
boost::signals2::signal< void(const uint256 &)> UpdatedTransaction
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:989
bool Condition(const CBlockIndex *pindex, const Consensus::Params &params) const override
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:890
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:78
const CBlockIndex * LastCommonAncestor(const CBlockIndex *pa, const CBlockIndex *pb)
Find the last common ancestor two blocks have.
Definition: chain.cpp:188
const char * prefix
Definition: rest.cpp:623
int height
Definition: txmempool.h:42
std::string GetHex() const
Definition: uint256.cpp:21
FascTransaction createEthTX(const EthTransactionParams &etp, const uint32_t nOut)
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
Definition: chain.h:141
size_t count
Definition: ExecStats.cpp:37
bool FlushStateToDisk()
Flush all state, indexes and buffers to disk.
static VersionVM GetEVMDefault()
static const std::string UNITTEST
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
uint32_t nHeight
Definition: block.h:46
void StartShutdown()
Definition: init.cpp:122
uint8_t format
bool CorruptionPossible() const
Definition: validation.h:82
CCriticalSection cs_main
Definition: validation.cpp:77
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view...
Definition: coins.cpp:236
CTxOut out
unspent transaction output
Definition: coins.h:33
bool fReindex
Definition: validation.cpp:86
std::string ToString() const
Definition: chain.h:370
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:237
h160 Address
An Ethereum address: 20 bytes.
Definition: Common.h:62
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
#define expect(bit)
cache implements a cache with properties similar to a cuckoo-set
Definition: cuckoocache.h:160
stage after last reached validness failed
Definition: chain.h:165
evm_mode mode
Definition: SmartVM.cpp:47
void clear()
Definition: txmempool.cpp:615
bool HasWitness() const
Definition: transaction.h:378
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:36
Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid...
Definition: chain.h:148
int64_t dgpMaxBlockSigOps
The maximum allowed number of signature check operations in a block (network rule) ...
Definition: consensus.cpp:15
int BIP66Height
Block height at which BIP66 becomes active.
Definition: params.h:50
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...
CTransactionRef get(const uint256 &hash) const
Definition: txmempool.cpp:826
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:220
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:101
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:90
bool IsSpent() const
Definition: coins.h:75
uint256 BlockWitnessMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:168
bool extractionFascTransactions(ExtractFascTX &fascTx)
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:534
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:104
void addTransaction(const CTransactionRef &tx)
Definition: txmempool.h:809
std::hash for asio::adress
Definition: Common.h:323
assert(len-trim+(2 *lenIndices)<=WIDTH)
ScriptError GetScriptError() const
Definition: validation.h:574
int64_t GetTimeMicros()
Definition: utiltime.cpp:47
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:369
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 Fabcoin system...
Definition: chainparams.h:47
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:41
size_t DynamicMemoryUsage() const
Definition: txmempool.cpp:920
undo data available in rev*.dat
Definition: chain.h:162
bool eof() const
Definition: streams.h:624
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:32
Access a block of memory.
Definition: misc.h:2233
boost::signals2::signal< void(const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction
A hasher class for Fabcoin&#39;s 256-bit hash (double SHA-256).
Definition: hash.h:21
void Thread()
Worker thread.
Definition: checkqueue.h:137
ThresholdState
Definition: versionbits.h:20
uint32_t VersionBitsMask(const Consensus::Params &params, Consensus::DeploymentPos pos)
int nFile
Which # file this block is stored in (blk?????.dat)
Definition: chain.h:196
void setGasLimit(int64_t _v)
Definition: ExtVMFace.h:249
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:457
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
Description of the result of executing a transaction.
Definition: Transaction.h:69
ExecStats::duration min
Definition: ExecStats.cpp:35
void TrimToSize(size_t sizelimit, std::vector< COutPoint > *pvNoSpendsRemaining=nullptr)
Remove transactions from the mempool until its dynamic size is <= sizelimit.
Definition: txmempool.cpp:1028
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
int64_t nTime
Definition: chainparams.h:35
bytes code
Definition: SmartVM.cpp:45
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:96
bool IsCoinBase() const
Definition: coins.h:54
unsigned char * begin()
Definition: uint256.h:65
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:437
CBlockIndex * pindexBestForkTip
void RenameThread(const char *name)
Definition: util.cpp:888
#define FLATDATA(obj)
Definition: serialize.h:388
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:165
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
void version()
Definition: main.cpp:53
const std::string strMessageMagic
Definition: validation.cpp:115
bool IsFABHardForkEnabledForCurrentBlock(const Consensus::Params &params)
Definition: validation.cpp:439
bool fIsBareMultisigStd
Definition: validation.cpp:91
uint32_t nTime
Definition: block.h:48
uint32_t FABHeight
Block height at which Fabcoin Equihash hard fork becomes active.
Definition: params.h:52
unsigned int nChainTx
(memory only) Number of transactions in the chain up to and including this block. ...
Definition: chain.h:214
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Make the best chain active, in multiple steps.
unsigned int dgpMaxBlockSize
Definition: consensus.cpp:12
indirectmap< COutPoint, const CTransaction * > mapNextTx
Definition: txmempool.h:555
unsigned char * end()
Definition: uint256.h:70
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:101
const std::vector< CTxIn > vin
Definition: transaction.h:292
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size...
Definition: policy.cpp:198
std::vector< TxMempoolInfo > infoAll() const
Definition: txmempool.cpp:812
bool CheckSync(int nHeight)
Check against automatically selected checkpoint.
Definition: checkpoints.cpp:44
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:115
arith_uint256 UintToArith256(const uint256 &a)
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &headers, CValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex, CBlockHeader *first_invalid)
Process incoming block headers.
std::string ToString() const
Definition: uint256.cpp:95
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:66
int nSubsidyHalvingInterval
Definition: params.h:43
indexed_transaction_set mapTx
Definition: txmempool.h:524
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hash.h:27
int64_t nTxCount
Definition: chainparams.h:36
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:144
bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams &params)
Check whether the Equihash solution in a block header is valid.
Definition: pow.cpp:258
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check for standard transaction types.
Definition: policy.cpp:164
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyBlockTip
New block has been accepted.
Definition: ui_interface.h:104
size_type size() const
Definition: prevector.h:282
bool ReadBlockFromDisk(Block &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
boost::signals2::signal< void(bool, const CBlockIndex *)> NotifyHeaderTip
Best header has changed.
Definition: ui_interface.h:107
bool IsFABHardForkEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Definition: validation.cpp:431
#define AssertLockHeld(cs)
Definition: sync.h:85
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:106
std::string NetworkIDString() const
Return the BIP70 network string (main, test or regtest)
Definition: chainparams.h:78
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
Removed in size limiting.
indexed_disconnected_transactions queuedTx
Definition: txmempool.h:800
bool SetLimit(uint64_t nPos=(uint64_t)(-1))
Definition: streams.h:683
bool CheckDiskSpace(uint64_t nAdditionalBytes)
Check whether enough disk space is available for an incoming block.
void fclose()
Definition: streams.h:478
uint64_t GetPos()
Definition: streams.h:651
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:15
iterator end()
Definition: prevector.h:292
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:512
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:252
#define LOCK2(cs1, cs2)
Definition: sync.h:176
void SetCorruptionPossible()
Definition: validation.h:85
void SetfLargeWorkInvalidChainFound(bool flag)
Definition: warnings.cpp:34
iterator end()
Definition: indirectmap.h:49
Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends...
Definition: chain.h:152
bool fCheckpointsEnabled
Definition: validation.cpp:94
int Height() const
Return the maximal height in the chain.
Definition: chain.h:543
bool ReplayBlocks(const CChainParams &params, CCoinsView *view)
Replay blocks that aren&#39;t fully applied to the database.
std::vector< h256 > LastHashes
Definition: ExtVMFace.h:191
opcodetype
Script opcodes.
Definition: script.h:48
unsigned int nTimeMax
(memory only) Maximum nTime in the chain upto and including this block.
Definition: chain.h:235
unsigned int nTime
Definition: chain.h:223
bool TruncateFile(FILE *file, unsigned int length)
Definition: util.cpp:761
uint64_t PruneAfterHeight() const
Definition: chainparams.h:71
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
#define LogPrintf(...)
Definition: util.h:153
dev::h256 uintToh256(const uint256 &in)
Definition: uint256.h:171
bool CheckFinalTx(const CTransaction &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: validation.cpp:271
FILE * OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
void PruneOneBlockFile(const int fileNumber)
Mark one block file as pruned.
bool CheckProofOfWork(uint256 hash, unsigned int nBits, bool postfork, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:290
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:217
double getdouble() const
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:535
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:155
Access to the block database (blocks/index/)
Definition: txdb.h:116
uint256 hashMerkleRoot
Definition: block.h:45
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:123
Abstract view on the open txout dataset.
Definition: coins.h:145
MemPoolConflictRemovalTracker(CTxMemPool &_pool)
Definition: validation.cpp:217
void updateBlockSizeParams(unsigned int newBlockSize)
Definition: consensus.cpp:21
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:103
static uint64_t vch_to_uint64(const std::vector< unsigned char > &vch)
Definition: script.h:337
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:81
unsigned int nDataPos
Byte offset within blk?????.dat where this block&#39;s data is stored.
Definition: chain.h:199
uint32_t toRaw()
int64_t GetBlockTime() const
Definition: block.h:127
DeploymentPos
Definition: params.h:15
void removeForBlock(const std::vector< CTransactionRef > &vtx)
Definition: txmempool.h:816
An input of a transaction.
Definition: transaction.h:61
bool IsNull() const
Definition: uint256.h:38
ConnectTrace(CTxMemPool &_pool)
int VersionBitsStateSinceHeight(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
#define LOCK(cs)
Definition: sync.h:175
void BlockConnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex, const std::vector< CTransactionRef > &)
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:162
std::function< void(std::string const &, char const *)> g_logPost
The current method that the logging system uses to output the log messages. Defaults to simpleDebugOu...
Definition: Log.cpp:215
ExecStats::duration max
Definition: ExecStats.cpp:36
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo * > > &fileInfo, int nLastFile, const std::vector< const CBlockIndex * > &blockinfo)
Definition: txdb.cpp:231
int BIP34Height
Block height and hash at which BIP34 becomes active.
Definition: params.h:45
size_t DynamicMemoryUsage() const
Definition: txmempool.h:805
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet, txnouttype *typeRet)
Definition: standard.cpp:268
uint64_t getBlockGasLimit(unsigned int blockHeight)
Definition: fascDGP.cpp:76
CBlockHeader GetBlockHeader() const
Definition: block.h:190
std::map< uint256, CAmount > mapDeltas
Definition: txmempool.h:556
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:456
CAmount GetValueOut() const
Definition: transaction.cpp:84
bool HasOpSpend() const
Definition: script.h:706
bool HasOpCall() const
Definition: script.h:702
uint32_t ContractHeight
Block height at which Fabcoin Smart Contract hard fork becomes active.
Definition: params.h:56
Abstract class that implements BIP9-style threshold logic, and caches results.
Definition: versionbits.h:53
void setLastHashes(LastHashes &&_lh)
Definition: ExtVMFace.h:250
uint256 hashPrevBlock
Definition: block.h:44
void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason)
Definition: validation.cpp:220
uint32_t n
Definition: transaction.h:22
void setTimestamp(u256 const &_v)
Definition: ExtVMFace.h:247
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:227
dev::eth::EVMSchedule getGasSchedule(unsigned int blockHeight)
Definition: fascDGP.cpp:35
const std::vector< CTxOut > vout
Definition: transaction.h:293
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:119
bool AcceptToMemoryPoolWithTime(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, int64_t nAcceptTime, std::list< CTransactionRef > *plTxnReplaced=NULL, bool fOverrideMempoolLimit=false, const CAmount nAbsurdFee=0, bool rawTx=false)
(try to) add transaction to memory pool with a specified acceptance time
valtype GetSenderAddress(const CTransaction &tx, const CCoinsViewCache *coinsView, const std::vector< CTransactionRef > *blockTxs)
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: ui_interface.h:98
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:796
const ChainTxData & TxData() const
Definition: chainparams.h:83
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
bool contains(const Element &e, const bool erase) const
Definition: cuckoocache.h:467
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
Definition: FixedHash.h:47
std::shared_ptr< const CBlock > pblock
static VersionVM fromRaw(uint32_t val)
CMainSignals & GetMainSignals()
dev::Address receiveAddress
Definition: validation.h:710
bytes asBytes(std::string const &_b)
Converts a string to a byte array containing the string&#39;s (byte) data.
Definition: CommonData.h:92
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:158
void setNumber(u256 const &_v)
Definition: ExtVMFace.h:245
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: chain.cpp:116
CAmount refundSender
Definition: validation.h:723
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 TestLockPointValidity(const LockPoints *lp)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:303
bool operator()()
const CMessageHeader::MessageStartChars & MessageStart() const
Definition: chainparams.h:61
std::string ToString() const
Definition: chain.h:125
An output of a transaction.
Definition: transaction.h:131
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:53
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
void SetNull()
Definition: block.h:101
bool ReadFromDisk(CBlockHeader &block, unsigned int nFile, unsigned int nBlockPos)
bool IsValid() const
Definition: validation.h:66
std::vector< uint256 > vHave
Definition: block.h:253
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data)
Returns last CBlockIndex* in mapBlockIndex that is a checkpoint.
Definition: checkpoints.cpp:19
uint32_t nMinerConfirmationWindow
Definition: params.h:71
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
bool SetPos(uint64_t nPos)
Definition: streams.h:656
class CMainCleanup instance_of_cmaincleanup
bool IsStandardTx(const CTransaction &tx, std::string &reason, const bool witnessEnabled)
Check for standard transaction types.
Definition: policy.cpp:100
Queue for verifications that have to be performed.
Definition: checkqueue.h:30
bool IsNull() const
Definition: chain.h:123
Parameters that influence chain consensus.
Definition: params.h:39
void ThreadScriptCheck()
Run an instance of the script checking thread.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
bool fEnableReplacement
Definition: validation.cpp:98
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:113
bool CheckMinGasPrice(std::vector< EthTransactionParams > &etps, const uint64_t &minGasPrice)
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
void AddTransactionsUpdated(unsigned int n)
Definition: txmempool.cpp:360
bool processingResults(ByteCodeExecResult &result)
std::vector< CTxOut > vout
Definition: transaction.h:393
bool fTxIndex
Definition: validation.cpp:87
bool RenameOver(fs::path src, fs::path dest)
Definition: util.cpp:714
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, 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:321
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:97
256-bit unsigned big integer.
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:526
block data in blk*.data was received with a witness-enforcing client
Definition: chain.h:169
CCriticalSection cs
Definition: txmempool.h:523
unsigned int nPos
Definition: chain.h:95
VersionBitsCache versionbitscache
TransactionException excepted
Definition: Transaction.h:72
void BlockConnected(CBlockIndex *pindex, std::shared_ptr< const CBlock > pblock)
bool ReadFlag(const std::string &name, bool &fValue)
Definition: txdb.cpp:258
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee, bool rawTx)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
#define b(i, j)
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:100
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo)
Definition: txdb.cpp:157
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:40
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Auxiliary functions for transaction validation (ideally should not be exposed)
Definition: tx_verify.cpp:109
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos)
Definition: txdb.cpp:243
std::map< const CBlockIndex *, ThresholdState > ThresholdConditionCache
Definition: versionbits.h:31
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:500
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:543
void insert(Element e)
insert loops at most depth_limit times trying to insert a hash at various locations in the table via ...
Definition: cuckoocache.h:392
int BIP65Height
Block height at which BIP65 becomes active.
Definition: params.h:48
bool IsInvalid() const
Definition: validation.h:69
bool LoadBlockIndex(const CChainParams &chainparams)
Load the block tree and coins database from disk, initializing state if we&#39;re running with -reindex...
bool exists(uint256 hash) const
Definition: txmempool.h:671
void setVersion(VersionVM v)
int nVersion
block header
Definition: chain.h:220
bool Error(const std::string &strRejectReasonIn)
Definition: validation.h:60
std::string GetRejectReason() const
Definition: validation.h:89
uint32_t setup_bytes(size_t bytes)
setup_bytes is a convenience function which accounts for internal memory usage when deciding how many...
Definition: cuckoocache.h:367
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:138
void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const
Definition: txmempool.cpp:874
unsigned int GetRejectCode() const
Definition: validation.h:88
unsigned int nUndoPos
Byte offset within rev?????.dat where this block&#39;s undo data is stored.
Definition: chain.h:202
bytes asBytes() const
Definition: FixedHash.h:145
CScript scriptSig
Definition: transaction.h:65
void DumpMempool(void)
Dump the mempool to disk.
std::shared_ptr< std::vector< CTransactionRef > > conflictedTxs
std::string ToString() const
Definition: feerate.cpp:40
#define LogPrint(category,...)
Definition: util.h:164
uint256 GetHash()
Definition: hash.h:149
std::string ToString() const
Definition: block.cpp:66
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:507
CAmount GetFee(size_t nBytes) const
Return the fee in liu for the given size in bytes.
Definition: feerate.cpp:23
std::vector< ResultExecute > CallContract(const dev::Address &addrContract, std::vector< unsigned char > opcode, const dev::Address &sender, uint64_t gasLimit)
bool CheckCanonicalBlockSignature(const std::shared_ptr< const CBlock > pblock)
txnouttype
Definition: standard.h:51
Capture information about block/transaction validation.
Definition: validation.h:27
int64_t nTimeout
Timeout/expiry MedianTime for the deployment attempt.
Definition: params.h:33
256-bit opaque blob.
Definition: uint256.h:132
bool fCheckBlockIndex
Definition: validation.cpp:93
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, CDiskBlockPos *dbp)
Import blocks from an external file.
ArgsManager gArgs
Definition: util.cpp:94
uint256 nMinimumChainWork
Definition: params.h:85
std::vector< CTransactionRef > vtx
Definition: block.h:159
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:407
void SetTip(CBlockIndex *pindex)
Set/initialize a chain with a given tip.
Definition: chain.cpp:13
unsigned int dgpMaxTxSigOps
The maximum number of sigops we&#39;re willing to relay/mine in a single tx.
Definition: consensus.cpp:19
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
uint256 GetHash() const
Definition: block.cpp:38
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:465
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:621
bool fRequireStandard
Definition: validation.cpp:92
Template mixin that adds -Wthread-safety locking annotations to a subset of the mutex API...
Definition: sync.h:54
uint256 hashProof
Definition: chain.h:228
static const int SYNC_TRANSACTION_NOT_IN_BLOCK
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...
PlatformStyle::TableColorType type
Definition: rpcconsole.cpp:61
CAmount GetValueIn(const CTransaction &tx) const
Amount of fabcoins coming in to a transaction Note that lightweight clients may not know anything bes...
Definition: coins.cpp:224
void FindByte(char ch)
Definition: streams.h:698
bool ResetBlockFailureFlags(CBlockIndex *pindex)
Remove invalidity status from a block and its descendants.
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:177
const CBlock & GenesisBlock() const
Definition: chainparams.h:64
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
Undo information for a CBlock.
Definition: undo.h:99
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
uint32_t nSequence
Definition: transaction.h:66
boost::signals2::signal< void()> NotifyAlertChanged
Status bar alerts changed.
Definition: ui_interface.h:92
int64_t MaxFutureBlockTime
Limit BITCOIN_MAX_FUTURE_BLOCK_TIME.
Definition: params.h:60
Undo information for a CTransaction.
Definition: undo.h:67
std::atomic_bool fImporting(false)
void * memcpy(void *a, const void *b, size_t c)
std::vector< PerBlockConnectTrace > blocksConnected
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don&#39;t call for mined blocks...
bool GetfLargeWorkForkFound()
Definition: warnings.cpp:28
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:74
int64_t GetTimeMillis()
Definition: utiltime.cpp:39
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:496
void InitScriptExecutionCache()
Initializes the script-execution cache.
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:211
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:233
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 runCommand(const std::string &strCommand)
Definition: util.cpp:881
bool LoadMempool(void)
Load the mempool from disk.
void addResult(dev::h256 hashTx, std::vector< TransactionReceiptInfo > &result)
unsigned int GetNextWorkRequired(const CBlockIndex *pindexPrev, const CBlockHeader *pblock, const Consensus::Params &params)
Definition: pow.cpp:18
bool HasCreateOrCall() const
bool sha3(bytesConstRef _input, bytesRef o_output)
Calculate SHA3-256 hash of the given input and load it into the given output.
Definition: SHA3.cpp:214
bool PreciousBlock(CValidationState &state, const CChainParams &params, CBlockIndex *pindex)
Mark a block as precious and reorganize.
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
VersionVM getVersion() const
void forceSender(Address const &_a)
Force the sender to a particular value. This will result in an invalid transaction RLP...
Definition: Transaction.h:87
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:530
void SetMiscWarning(const std::string &strWarning)
Definition: warnings.cpp:16
bool WriteTxIndex(const std::vector< std::pair< uint256, CDiskTxPos > > &list)
Definition: txdb.cpp:247
bool CheckReward(const CBlock &block, CValidationState &state, int nHeight, const Consensus::Params &consensusParams, CAmount nFees, CAmount gasRefunds, const std::vector< CTxOut > &vouts)
Fee rate in liu per kilobyte: CAmount / kB.
Definition: feerate.h:20
void setAuthor(Address const &_v)
Definition: ExtVMFace.h:246
bool RequireStandard() const
Policy: Filter transactions that do not match well-defined patterns.
Definition: chainparams.h:70
uint8_t vmVersion
std::string GetDebugMessage() const
Definition: validation.h:90
uint256 hashUTXORoot
Definition: chain.h:227
dev::eth::EnvInfo BuildEVMEnvironment()
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, int flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:140
std::string ToString() const
bool RaiseValidity(enum BlockStatus nUpTo)
Raise the validity level of this block index entry.
Definition: chain.h:389
iterator begin()
Definition: prevector.h:290
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:379
void writeVMlog(const std::vector< ResultExecute > &res, const CTransaction &tx, const CBlock &block)
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
bool LoadBlockIndexGuts(const Consensus::Params &consensusParams, std::function< CBlockIndex *(const uint256 &)> insertBlockIndex)
Definition: txdb.cpp:370
CBlockTreeDB * pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:253
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:75
#define e(i)
Definition: sha.cpp:733
bool IsCoinBase() const
Definition: transaction.h:349
bool WriteFlag(const std::string &name, bool fValue)
Definition: txdb.cpp:254
A mutable version of CTransaction.
Definition: transaction.h:390
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:130
int64_t time
Definition: txmempool.h:43
uint256 hashStateRoot
Definition: block.h:50
uint32_t nRuleChangeActivationThreshold
Minimum blocks including miner confirmation of the total of 2016 blocks in a retargeting period...
Definition: params.h:70
const uint256 & GetHash() const
Definition: transaction.h:325
std::vector< unsigned char > valtype
Definition: fascstate.h:17
All validity bits.
Definition: chain.h:158
void SetBestChain(const CBlockLocator &)
boost::signals2::signal< void(CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved
Definition: txmempool.h:691
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:623
bool addUnchecked(const uint256 &hash, const CTxMemPoolEntry &entry, bool validFeeEstimate=true)
Definition: txmempool.cpp:950
void removeForBlock(const std::vector< CTransactionRef > &vtx, unsigned int nBlockHeight)
Called when a block is connected.
Definition: txmempool.cpp:573
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:153
FlushStateMode
Definition: validation.cpp:256
std::vector< CTxOut > refundOutputs
Definition: validation.h:724
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
Permanence
Definition: State.h:82
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:19
CDiskBlockPos GetUndoPos() const
Definition: chain.h:297
void BlockDisconnected(const std::shared_ptr< const CBlock > &)
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:25
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
bool fIsVMlogFile
Definition: validation.cpp:73
WarningBitsConditionChecker(int bitIn)
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:198
bool WriteHeightIndex(const CHeightTxIndexKey &heightIndex, const std::vector< uint256 > &hash)
Definition: txdb.cpp:267
CCoinsViewDB * pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:251
BIP9Stats VersionBitsStatistics(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos)
void deleteResults(std::vector< CTransactionRef > const &txs)
uint256 hashStateRoot
Definition: chain.h:226
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
std::vector< PerBlockConnectTrace > & GetBlocksConnected()
uint16_t flagOptions
void PruneAndFlush()
Prune block files and flush state to disk.
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: chain.cpp:85
bool fChecked
Definition: block.h:162
full block available in blk*.dat
Definition: chain.h:161
void setDifficulty(u256 const &_v)
Definition: ExtVMFace.h:248
DisconnectResult
CBlockIndex * InsertBlockIndex(uint256 hash)
Create a new block index entry for a given block hash.
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
Definition: validation.h:55
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to deserialize from...
Definition: streams.h:564
UniValue vmLogToJSON(const ResultExecute &execRes, const CTransaction &tx, const CBlock &block)
int64_t GetBlockTime() const
Definition: chain.h:329
uint256 hashUTXORoot
Definition: block.h:51
A hasher class for SHA-256.
Definition: sha256.h:13
void setNVout(uint32_t vout)
bool CheckSenderScript(const CCoinsViewCache &view, const CTransaction &tx)
dev::Address EthAddrFromScript(const CScript &scriptIn)
std::vector< CTxUndo > vtxundo
Definition: undo.h:102
int nFile
Definition: chain.h:94
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
COutPoint prevout
Definition: transaction.h:64
ThresholdState VersionBitsState(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::DeploymentPos pos, VersionBitsCache &cache)
void SetfLargeWorkForkFound(bool flag)
Definition: warnings.cpp:22
Removed for conflict with in-block transaction.
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:19
CBlockIndex * maxInputBlock
Definition: txmempool.h:47
fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
Translation to a filesystem path.
Config::Pair_type Pair
int64_t GetMedianTimePast() const
Definition: chain.h:341
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:743
bool RewindBlockIndex(const CChainParams &params)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
int32_t nVersion
Definition: block.h:43
uint8_t const * data
Definition: sha3.h:19
CFeeRate incrementalRelayFee
Definition: policy.cpp:250
iterator find(const K &key)
Definition: indirectmap.h:36
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void PrioritiseTransaction(const uint256 &hash, const CAmount &nFeeDelta)
Affect CreateNewBlock prioritisation of transactions.
Definition: txmempool.cpp:844
BlockMap mapBlockIndex
Definition: validation.cpp:79
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
Definition: txmempool.cpp:511
void removeEntry(indexed_disconnected_transactions::index< insertion_order >::type::iterator entry)
Definition: txmempool.h:832
bool HasOpSpend() const
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:209
std::unique_ptr< FascState > globalState
Global state.
Definition: validation.cpp:70
StorageResults * pstorageresult
Definition: validation.cpp:254
bool ContextualCheckBlockHeader(const CBlockHeader &block, CValidationState &state, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev, int64_t nAdjustedTime)
Context-dependent validity checks.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:35
bool LoadChainTip(const CChainParams &chainparams)
Update the chain tip based on database information.
uint256 hashGenesisBlock
Definition: params.h:42
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness nonce).
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:455
size_t nCoinCacheUsage
Definition: validation.cpp:95
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:158
bool fGettingValuesDGP
Definition: validation.cpp:74
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:82
void setHashWith(const dev::h256 hash)
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:71
uint256 h256Touint(const dev::h256 &in)
Definition: uint256.h:178
uint64_t getMinGasPrice(unsigned int blockHeight)
Definition: fascDGP.cpp:66
Wrapped boost mutex: supports recursive locking, but no waiting TODO: We should move away from using ...
Definition: sync.h:91
BIP9Deployment vDeployments[MAX_VERSION_BITS_DEPLOYMENTS]
Definition: params.h:72
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
dev::eth::TransactionReceipt txRec
Definition: fascstate.h:34
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason=MemPoolRemovalReason::UNKNOWN)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:926
std::shared_ptr< dev::eth::SealEngineFace > globalSealEngine
Definition: validation.cpp:71
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:168
size_t GetTxSize() const
Definition: txmempool.cpp:60
uint256 GetBlockHash() const
Definition: chain.h:324
std::vector< LogEntry > LogEntries
Definition: ExtVMFace.h:110
uint32_t nBits
Definition: block.h:49
CConditionVariable cvBlockChange
Definition: validation.cpp:83
Definition: script.h:100
unsigned int dgpMaxBlockWeight
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.cpp:8
bool InitBlockIndex(const CChainParams &chainparams)
Initialize a new block tree database + block data on disk.
bool IsConfirmedInNPrevBlocks(const CDiskTxPos &txindex, const CBlockIndex *pindexFrom, int nMaxDepth, int &nActualDepth)
Check if the transaction is confirmed in N previous blocks.
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:39
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
std::string hex() const
Definition: FixedHash.h:130
LogEntries const & log() const
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:128
Definition: ExtVMFace.h:88
void TransactionAddedToMempool(const CTransactionRef &)
uint256 hash
Definition: transaction.h:21
const uint256 * phashBlock
pointer to the hash of the block, if any. Memory is owned by this CBlockIndex
Definition: chain.h:181
std::vector< CTransaction > valueTransfers
Definition: validation.h:725
Threshold condition checker that triggers when unknown versionbits are seen on the network...