Bitcoin ABC  0.23.2
P2P Digital Currency
validation.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Copyright (c) 2017-2020 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef BITCOIN_VALIDATION_H
8 #define BITCOIN_VALIDATION_H
9 
10 #if defined(HAVE_CONFIG_H)
11 #include <config/bitcoin-config.h>
12 #endif
13 
14 #include <amount.h>
15 #include <blockfileinfo.h>
17 #include <coins.h>
18 #include <consensus/consensus.h>
19 #include <disconnectresult.h>
20 #include <flatfile.h>
21 #include <fs.h>
22 #include <protocol.h> // For CMessageHeader::MessageMagic
23 #include <script/script_error.h>
24 #include <script/script_metrics.h>
25 #include <sync.h>
26 #include <txdb.h>
27 #include <txmempool.h> // For CTxMemPool::cs
28 #include <versionbits.h>
29 
30 #include <atomic>
31 #include <cstdint>
32 #include <map>
33 #include <memory>
34 #include <optional>
35 #include <set>
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
41 class CBlockIndex;
42 class CBlockTreeDB;
43 class CBlockUndo;
44 class CChainParams;
45 class CChain;
46 class CConnman;
47 class CInv;
48 class ChainstateManager;
49 class Config;
50 class CScriptCheck;
51 class CTxMemPool;
52 class CTxUndo;
54 class TxValidationState;
55 
56 struct ChainTxData;
57 struct FlatFilePos;
59 struct LockPoints;
60 
61 namespace Consensus {
62 struct Params;
63 }
64 
65 #define MIN_TRANSACTION_SIZE \
66  (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
67 
76 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
78 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
80 static const int MAX_SCRIPTCHECK_THREADS = 15;
82 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
83 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
84 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
85 static const bool DEFAULT_TXINDEX = false;
86 static const char *const DEFAULT_BLOCKFILTERINDEX = "0";
87 
89 static const bool DEFAULT_PERSIST_MEMPOOL = true;
91 static const bool DEFAULT_FEEFILTER = true;
92 
93 static const bool DEFAULT_PEERBLOOMFILTERS = true;
94 
96 static const int DEFAULT_STOPATHEIGHT = 0;
98 static const int DEFAULT_MAX_REORG_DEPTH = 10;
105 static const int64_t DEFAULT_MIN_FINALIZATION_DELAY = 2 * 60 * 60;
110 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
111 static const signed int DEFAULT_CHECKBLOCKS = 6;
112 static const unsigned int DEFAULT_CHECKLEVEL = 3;
126 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
127 
130 
131 extern RecursiveMutex cs_main;
132 extern CTxMemPool g_mempool;
133 typedef std::unordered_map<BlockHash, CBlockIndex *, BlockHasher> BlockMap;
135 extern std::condition_variable g_best_block_cv;
136 extern uint256 g_best_block;
137 extern std::atomic_bool fImporting;
138 extern std::atomic_bool fReindex;
139 extern bool fRequireStandard;
140 extern bool fCheckBlockIndex;
141 extern bool fCheckpointsEnabled;
142 
147 extern CFeeRate minRelayTxFee;
152 extern int64_t nMaxTipAge;
153 
159 
164 
169 
172 extern bool fHavePruned;
174 extern bool fPruneMode;
176 extern uint64_t nPruneTarget;
178 extern const std::vector<std::string> CHECKLEVEL_DOC;
179 
181 private:
183  bool checkPoW : 1;
184  bool checkMerkleRoot : 1;
185 
186 public:
187  // Do full validation by default
188  explicit BlockValidationOptions(const Config &config);
189  explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
190  bool _checkPow = true,
191  bool _checkMerkleRoot = true)
192  : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
193  checkMerkleRoot(_checkMerkleRoot) {}
194 
195  BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
196  BlockValidationOptions ret = *this;
197  ret.checkPoW = _checkPoW;
198  return ret;
199  }
200 
202  withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
203  BlockValidationOptions ret = *this;
204  ret.checkMerkleRoot = _checkMerkleRoot;
205  return ret;
206  }
207 
208  bool shouldValidatePoW() const { return checkPoW; }
209  bool shouldValidateMerkleRoot() const { return checkMerkleRoot; }
210  uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
211 };
212 
216 void LoadExternalBlockFile(const Config &config, FILE *fileIn,
217  FlatFilePos *dbp = nullptr);
218 
223 bool LoadGenesisBlock(const CChainParams &chainparams);
224 
228 void UnloadBlockIndex();
229 
233 void ThreadScriptCheck(int worker_num);
234 
238 bool GetTransaction(const TxId &txid, CTransactionRef &txOut,
239  const Consensus::Params &params, BlockHash &hashBlock,
240  const CBlockIndex *const blockIndex = nullptr);
241 
248 bool ActivateBestChain(
249  const Config &config, BlockValidationState &state,
250  std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
251 Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
252 
257 double GuessVerificationProgress(const ChainTxData &data,
258  const CBlockIndex *pindex);
259 
263 uint64_t CalculateCurrentUsage();
264 
268 void UnlinkPrunedFiles(const std::set<int> &setFilesToPrune);
269 
271 void PruneBlockFilesManual(int nManualPruneHeight);
272 
276 bool AcceptToMemoryPool(const Config &config, CTxMemPool &pool,
277  TxValidationState &state, const CTransactionRef &tx,
278  bool bypass_limits, const Amount nAbsurdFee,
279  bool test_accept = false)
280  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
281 
287 protected:
288  std::atomic<int64_t> remaining;
289 
290 public:
291  explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
292 
293  bool consume_and_check(int consumed) {
294  auto newvalue = (remaining -= consumed);
295  return newvalue >= 0;
296  }
297 
298  bool check() { return remaining >= 0; }
299 };
300 
302 public:
304 
305  // Let's make this bad boy copiable.
307  : CheckInputsLimiter(rhs.remaining.load()) {}
308 
310  remaining = rhs.remaining.load();
311  return *this;
312  }
313 
315  TxSigCheckLimiter txLimiter;
316  // Historically, there has not been a transaction with more than 20k sig
317  // checks on testnet or mainnet, so this effectively disable sigchecks.
318  txLimiter.remaining = 20000;
319  return txLimiter;
320  }
321 };
322 
323 class ConnectTrace;
324 
354 bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
355  const CCoinsViewCache &view, const uint32_t flags,
356  bool sigCacheStore, bool scriptCacheStore,
357  const PrecomputedTransactionData &txdata,
358  int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks,
359  CheckInputsLimiter *pBlockLimitSigChecks,
360  std::vector<CScriptCheck> *pvChecks)
361  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
362 
366 static inline bool
368  const CCoinsViewCache &view, const uint32_t flags,
369  bool sigCacheStore, bool scriptCacheStore,
370  const PrecomputedTransactionData &txdata, int &nSigChecksOut)
371  EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
372  TxSigCheckLimiter nSigChecksTxLimiter;
373  return CheckInputScripts(tx, state, view, flags, sigCacheStore,
374  scriptCacheStore, txdata, nSigChecksOut,
375  nSigChecksTxLimiter, nullptr, nullptr);
376 }
377 
381 
385  const CBlockIndex *pindex);
386 
393 
400 
402 void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight);
403 
407 void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
408  int nHeight);
409 
413 void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, int nHeight);
414 void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
415  int nHeight);
416 
422  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
423 
435 bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx,
436  int flags, LockPoints *lp = nullptr,
437  bool useExistingLockPoints = false)
438  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
439 
448 private:
451  unsigned int nIn;
452  uint32_t nFlags;
459 
460 public:
462  : ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false),
463  error(ScriptError::UNKNOWN), txdata(), pTxLimitSigChecks(nullptr),
464  pBlockLimitSigChecks(nullptr) {}
465 
466  CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
467  unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn,
468  const PrecomputedTransactionData &txdataIn,
469  TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
470  CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
471  : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
472  cacheStore(cacheIn), error(ScriptError::UNKNOWN), txdata(txdataIn),
473  pTxLimitSigChecks(pTxLimitSigChecksIn),
474  pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
475 
476  bool operator()();
477 
478  void swap(CScriptCheck &check) {
479  std::swap(ptxTo, check.ptxTo);
480  std::swap(m_tx_out, check.m_tx_out);
481  std::swap(nIn, check.nIn);
482  std::swap(nFlags, check.nFlags);
483  std::swap(cacheStore, check.cacheStore);
484  std::swap(error, check.error);
485  std::swap(metrics, check.metrics);
486  std::swap(txdata, check.txdata);
487  std::swap(pTxLimitSigChecks, check.pTxLimitSigChecks);
488  std::swap(pBlockLimitSigChecks, check.pBlockLimitSigChecks);
489  }
490 
491  ScriptError GetScriptError() const { return error; }
492 
494 };
495 
496 bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex);
497 
506 bool CheckBlock(const CBlock &block, BlockValidationState &state,
507  const Consensus::Params &params,
508  BlockValidationOptions validationOptions);
509 
517  const CTransaction &tx,
518  TxValidationState &state,
519  int flags = -1);
520 
525 bool TestBlockValidity(BlockValidationState &state, const CChainParams &params,
526  const CBlock &block, CBlockIndex *pindexPrev,
527  BlockValidationOptions validationOptions)
528  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
529 
534 class CVerifyDB {
535 public:
536  CVerifyDB();
537  ~CVerifyDB();
538  bool VerifyDB(const Config &config, CCoinsView *coinsview, int nCheckLevel,
539  int nCheckDepth);
540 };
541 
543  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
544 
547  const CBlockLocator &locator)
548  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
549 
551 enum class FlushStateMode { NONE, IF_NEEDED, PERIODIC, ALWAYS };
552 
555 extern std::unique_ptr<CCoinsViewCache> pcoinsTip;
556 
565 public:
566  BlockMap m_block_index GUARDED_BY(cs_main);
567 
587  std::set<CBlockIndex *> m_failed_blocks;
588 
594  std::multimap<CBlockIndex *, CBlockIndex *> m_blocks_unlinked;
595 
604  bool LoadBlockIndex(const Consensus::Params &consensus_params,
605  CBlockTreeDB &blocktree,
606  std::set<CBlockIndex *, CBlockIndexWorkComparator>
607  &block_index_candidates)
608  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
609 
611  void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
612 
613  CBlockIndex *AddToBlockIndex(const CBlockHeader &block)
614  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
616  CBlockIndex *InsertBlockIndex(const BlockHash &hash)
617  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
618 
624  bool AcceptBlockHeader(const Config &config, const CBlockHeader &block,
625  BlockValidationState &state, CBlockIndex **ppindex)
626  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
627 };
628 
638 class CoinsViews {
639 public:
642  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
643 
646  CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
647 
650  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
651 
660  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory,
661  bool should_wipe);
662 
664  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
665 };
666 
669  CRITICAL = 2,
671  LARGE = 1,
672  OK = 0
673 };
674 
689 class CChainState {
690 private:
697 
703  std::atomic<int32_t> nBlockSequenceId{1};
705  int32_t nBlockReverseSequenceId = -1;
707  arith_uint256 nLastPreciousChainwork = 0;
708 
715  mutable std::atomic<bool> m_cached_finished_ibd{false};
716 
721 
724  std::unique_ptr<CoinsViews> m_coins_views;
725 
730  const CBlockIndex *m_finalizedBlockIndex GUARDED_BY(cs_main) = nullptr;
731 
732 public:
733  explicit CChainState(BlockManager &blockman,
734  BlockHash from_snapshot_blockhash = BlockHash());
735 
742  void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
743  std::string leveldb_name = "chainstate");
744 
747  void InitCoinsCache(size_t cache_size_bytes)
748  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
749 
753  bool CanFlushToDisk() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
754  return m_coins_views && m_coins_views->m_cacheview;
755  }
756 
760 
767  const BlockHash m_from_snapshot_blockhash{};
768 
775  std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
776 
778  CCoinsViewCache &CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
779  assert(m_coins_views->m_cacheview);
780  return *m_coins_views->m_cacheview.get();
781  }
782 
784  CCoinsViewDB &CoinsDB() { return m_coins_views->m_dbview; }
785 
789  EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
790  return m_coins_views->m_catcherview;
791  }
792 
794  void ResetCoinsViews() { m_coins_views.reset(); }
795 
797  size_t m_coinsdb_cache_size_bytes{0};
798 
800  size_t m_coinstip_cache_size_bytes{0};
801 
804  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
805  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
806 
818  bool FlushStateToDisk(const CChainParams &chainparams,
820  int nManualPruneHeight = 0);
821 
823  void ForceFlushStateToDisk();
824 
827  void PruneAndFlush();
828 
843  bool ActivateBestChain(
844  const Config &config, BlockValidationState &state,
845  std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>())
846  LOCKS_EXCLUDED(cs_main);
847 
848  bool AcceptBlock(const Config &config,
849  const std::shared_ptr<const CBlock> &pblock,
850  BlockValidationState &state, bool fRequested,
851  const FlatFilePos *dbp, bool *fNewBlock)
852  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
853 
854  // Block (dis)connection on a given view:
855  DisconnectResult DisconnectBlock(const CBlock &block,
856  const CBlockIndex *pindex,
857  CCoinsViewCache &view);
858  bool ConnectBlock(const CBlock &block, BlockValidationState &state,
859  CBlockIndex *pindex, CCoinsViewCache &view,
860  const CChainParams &params,
861  BlockValidationOptions options, bool fJustCheck = false)
862  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
863 
864  // Block disconnection on our pcoinsTip:
865  bool DisconnectTip(const CChainParams &params, BlockValidationState &state,
866  DisconnectedBlockTransactions *disconnectpool)
867  EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.cs);
868 
869  // Manual block validity manipulation:
870  bool PreciousBlock(const Config &config, BlockValidationState &state,
871  CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
873  bool InvalidateBlock(const Config &config, BlockValidationState &state,
874  CBlockIndex *pindex)
875  LOCKS_EXCLUDED(cs_main, m_cs_chainstate);
877  bool ParkBlock(const Config &config, BlockValidationState &state,
878  CBlockIndex *pindex)
879  LOCKS_EXCLUDED(cs_main, m_cs_chainstate);
880 
885  bool FinalizeBlock(const Config &config, BlockValidationState &state,
886  CBlockIndex *pindex)
887  LOCKS_EXCLUDED(cs_main, m_cs_chainstate);
889  const CBlockIndex *GetFinalizedBlock() const
890  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
894  bool IsBlockFinalized(const CBlockIndex *pindex) const
895  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
896 
897  void ResetBlockFailureFlags(CBlockIndex *pindex)
898  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
899  template <typename F>
900  bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
901  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
902  template <typename F, typename C, typename AC>
903  void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
904  C fChild, AC fAncestorWasChanged)
905  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
907  void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
908  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
909 
911  bool ReplayBlocks(const Consensus::Params &params);
912  bool LoadGenesisBlock(const CChainParams &chainparams);
913 
914  void PruneBlockIndexCandidates();
915 
916  void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
917 
922  bool IsInitialBlockDownload() const;
923 
930  void CheckBlockIndex(const Consensus::Params &consensusParams);
931 
934  bool LoadChainTip(const CChainParams &chainparams)
935  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
936 
940  CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool &tx_pool)
941  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
942 
943  CoinsCacheSizeState GetCoinsCacheSizeState(
944  const CTxMemPool &tx_pool, size_t max_coins_cache_size_bytes,
945  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
946 
947  std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
948 
949 private:
950  bool ActivateBestChainStep(const Config &config,
951  BlockValidationState &state,
952  CBlockIndex *pindexMostWork,
953  const std::shared_ptr<const CBlock> &pblock,
954  bool &fInvalidFound, ConnectTrace &connectTrace)
955  EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.cs);
956  bool ConnectTip(const Config &config, BlockValidationState &state,
957  CBlockIndex *pindexNew,
958  const std::shared_ptr<const CBlock> &pblock,
959  ConnectTrace &connectTrace,
960  DisconnectedBlockTransactions &disconnectpool)
961  EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::g_mempool.cs);
962  void InvalidBlockFound(CBlockIndex *pindex,
963  const BlockValidationState &state)
964  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
965  void InvalidChainFound(CBlockIndex *pindexNew)
966  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
967  CBlockIndex *FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
968  bool MarkBlockAsFinal(BlockValidationState &state,
969  const CBlockIndex *pindex)
970  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
971  void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
972  const FlatFilePos &pos)
973  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
974 
975  bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs,
976  const Consensus::Params &params)
977  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
978  bool UnwindBlock(const Config &config, BlockValidationState &state,
979  CBlockIndex *pindex, bool invalidate)
980  EXCLUSIVE_LOCKS_REQUIRED(m_cs_chainstate);
981 
983 };
984 
990 bool PreciousBlock(const Config &config, BlockValidationState &state,
991  CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
992 
995  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
996 
999  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1000 
1002 void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1003 
1037 class ChainstateManager {
1038 private:
1056  std::unique_ptr<CChainState> m_ibd_chainstate;
1057 
1069  std::unique_ptr<CChainState> m_snapshot_chainstate;
1070 
1082  CChainState *m_active_chainstate{nullptr};
1083 
1086  bool m_snapshot_validated{false};
1087 
1088  // For access to m_active_chainstate.
1089  friend CChainState &ChainstateActive();
1090  friend CChain &ChainActive();
1091 
1092 public:
1095  BlockManager m_blockman GUARDED_BY(::cs_main);
1096 
1099  int64_t m_total_coinstip_cache{0};
1100  //
1103  int64_t m_total_coinsdb_cache{0};
1104 
1110  CChainState &
1111  InitializeChainstate(const BlockHash &snapshot_blockhash = BlockHash())
1112  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1113 
1115  std::vector<CChainState *> GetAll();
1116 
1118  CChainState &ActiveChainstate() const;
1119  CChain &ActiveChain() const { return ActiveChainstate().m_chain; }
1120  int ActiveHeight() const { return ActiveChain().Height(); }
1121  CBlockIndex *ActiveTip() const { return ActiveChain().Tip(); }
1122 
1123  BlockMap &BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
1124  return m_blockman.m_block_index;
1125  }
1126 
1127  bool IsSnapshotActive() const;
1128 
1129  std::optional<BlockHash> SnapshotBlockhash() const;
1130 
1132  bool IsSnapshotValidated() const { return m_snapshot_validated; }
1133 
1136  bool IsBackgroundIBD(CChainState *chainstate) const;
1137 
1142  CChainState &ValidatedChainstate() const;
1143 
1144  CChain &ValidatedChain() const { return ValidatedChainstate().m_chain; }
1145  CBlockIndex *ValidatedTip() const { return ValidatedChain().Tip(); }
1146 
1170  bool ProcessNewBlock(const Config &config,
1171  const std::shared_ptr<const CBlock> pblock,
1172  bool fForceProcessing, bool *fNewBlock)
1173  LOCKS_EXCLUDED(cs_main);
1174 
1189  bool ProcessNewBlockHeaders(const Config &config,
1190  const std::vector<CBlockHeader> &block,
1191  BlockValidationState &state,
1192  const CBlockIndex **ppindex = nullptr)
1193  LOCKS_EXCLUDED(cs_main);
1194 
1196  void PruneOneBlockFile(const int fileNumber)
1197  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1198 
1201  bool LoadBlockIndex(const Consensus::Params &params)
1202  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1203 
1205  void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1206 
1208  void Reset();
1209 
1212  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1213 };
1214 
1219 extern ChainstateManager g_chainman GUARDED_BY(::cs_main);
1220 
1223 
1225 CChain &ChainActive();
1226 
1228 BlockMap &BlockIndex();
1229 
1233 extern std::unique_ptr<CBlockTreeDB> pblocktree;
1234 
1241 int GetSpendHeight(const CCoinsViewCache &inputs);
1242 
1246 int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev,
1247  const Consensus::Params &params);
1248 
1250 CBlockFileInfo *GetBlockFileInfo(size_t n);
1251 
1253 bool DumpMempool(const CTxMemPool &pool);
1254 
1256 bool LoadMempool(const Config &config, CTxMemPool &pool);
1257 
1259 bool IsBlockPruned(const CBlockIndex *pblockindex);
1260 
1261 #endif // BITCOIN_VALIDATION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:319
bool shouldValidatePoW() const
Definition: validation.h:208
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:82
static const Amount DEFAULT_UTXO_FEE
Default for -excessutxocharge for transactions transactions.
Definition: validation.h:71
Display status of an in-progress BIP9 softfork.
Definition: versionbits.h:44
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:78
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition: validation.h:306
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:116
static constexpr Amount zero()
Definition: amount.h:35
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:129
bool shouldValidateMerkleRoot() const
Definition: validation.h:209
std::unordered_map< BlockHash, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:133
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:759
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:100
uint64_t getExcessiveBlockSize() const
Definition: validation.h:210
void swap(CScriptCheck &check)
Definition: validation.h:478
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:564
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
Definition: block.h:55
The cache is at >= 90% capacity.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:638
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1037
An in-memory indexed chain of blocks.
Definition: chain.h:152
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block.
static void pool cs
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:83
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
Inv(ventory) message data.
Definition: protocol.h:512
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:104
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ChainActive().Tip() will not be pr...
Definition: validation.h:110
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:329
unsigned int nHeight
CChain & ValidatedChain() const
Definition: validation.h:1144
uint64_t excessiveBlockSize
Definition: validation.h:182
Definition: amount.h:17
bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp=nullptr, bool useExistingLockPoints=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.cpp:208
The coins cache is in immediate need of a flush.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:794
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:689
static constexpr Amount SATOSHI
Definition: amount.h:146
bool AcceptToMemoryPool(const Config &config, CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, bool bypass_limits, const Amount nAbsurdFee, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool
Definition: validation.cpp:787
static const uint64_t MAX_TX_SIGCHECKS
Allowed number of signature check operations per transaction.
Definition: consensus.h:22
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
ScriptError error
Definition: validation.h:454
CCoinsViewDB & CoinsDB()
Definition: validation.h:784
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:26
ScriptError
Definition: script_error.h:11
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument &#39;checklevel&#39;.
Definition: validation.cpp:68
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool cacheStore
Definition: validation.h:453
void LoadExternalBlockFile(const Config &config, FILE *fileIn, FlatFilePos *dbp=nullptr)
Import blocks from an external file.
bool LoadMempool(const Config &config, CTxMemPool &pool)
Load the mempool from disk.
CTxOut m_tx_out
Definition: validation.h:449
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...
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:202
Called by RandAddPeriodic()
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition: validation.h:309
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:151
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:458
std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Definition: validation.h:594
static const int64_t DEFAULT_MIN_FINALIZATION_DELAY
Default for -finalizationdelay This is the minimum time between a block header reception and the bloc...
Definition: validation.h:105
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and a...
Definition: validation.h:775
static const Amount DEFAULT_MIN_RELAY_TX_FEE_PER_KB(1000 *SATOSHI)
Default for -minrelaytxfee, minimum relay fee for transactions.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:69
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:89
Struct for holding cumulative results from executing a script or a sequence of scripts.
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:93
static TxSigCheckLimiter getDisabled()
Definition: validation.h:314
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck), atomic so as to be compatible with parallel validation.
Definition: validation.h:286
bool ContextualCheckTransactionForCurrentBlock(const Consensus::Params &params, const CTransaction &tx, TxValidationState &state, int flags=-1)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: config.h:19
Access to the block database (blocks/index/)
Definition: txdb.h:105
Abstract view on the open txout dataset.
Definition: coins.h:175
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:696
DeploymentPos
Definition: params.h:16
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
bool consume_and_check(int consumed)
Definition: validation.h:293
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:110
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1132
FlushStateMode
Definition: validation.h:551
bool ActivateBestChain(const Config &config, BlockValidationState &state, std::shared_ptr< const CBlock > pblock=std::shared_ptr< const CBlock >())
Find the best known block, and make it the tip of the block chain.
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:534
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:85
int ActiveHeight() const
Definition: validation.h:1120
bool TestLockPointValidity(const LockPoints *lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain. ...
Definition: validation.cpp:189
ThresholdState VersionBitsBlockState(const Consensus::Params &params, Consensus::DeploymentPos pos, const CBlockIndex *pindex)
Get the BIP9 state for a given deployment at a given block.
Holds various statistics on transactions within a chain.
Definition: chainparams.h:34
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:76
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:96
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:119
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Definition: validation.h:91
Definition: net.h:167
ChainstateManager g_chainman
Definition: validation.cpp:77
bool PreciousBlock(const Config &config, BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
An output of a transaction.
Definition: transaction.h:130
ThresholdState VersionBitsTipState(const Consensus::Params &params, Consensus::DeploymentPos pos)
Get the BIP9 state for a given deployment at the current tip.
std::atomic_bool fImporting
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:724
Parameters that influence chain consensus.
Definition: params.h:59
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:86
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
256-bit unsigned big integer.
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:115
uint256 g_best_block
Definition: validation.cpp:107
PrecomputedTransactionData txdata
Definition: validation.h:456
Closure representing one script verification.
Definition: validation.h:447
DisconnectResult
int flags
Definition: bitcoin-tx.cpp:529
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:121
std::condition_variable g_best_block_cv
Definition: validation.cpp:106
std::atomic_bool fReindex
256-bit opaque blob.
Definition: uint256.h:123
CoinsCacheSizeState
Definition: validation.h:667
const CTransaction * ptxTo
Definition: validation.h:450
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:84
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks, CheckInputsLimiter *pBlockLimitSigChecks, std::vector< CScriptCheck > *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction&#39;s input scripts succeed.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:468
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:102
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:195
CTxMemPool g_mempool
Definition: validation.cpp:123
bool fRequireStandard
Definition: validation.cpp:112
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
const CChainParams & Params()
Return the currently selected parameters.
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
Undo information for a CBlock.
Definition: undo.h:73
std::unique_ptr< CChainState > m_snapshot_chainstate
A chainstate initialized on the basis of a UTXO snapshot.
Definition: validation.h:1069
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:111
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
A TxId is the identifier of a transaction.
Definition: txid.h:14
ChainstateManager g_chainman GUARDED_BY(::cs_main)
DEPRECATED! Please use node.chainman instead.
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:53
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
Definition: validation.h:1056
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
std::atomic< int64_t > remaining
Definition: validation.h:288
CChainState &InitializeChainstate(const BlockHash &snapshot_blockhash=BlockHash()) EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * > GetAll()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:1115
bool DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
Definition: validation.h:720
static const int DEFAULT_MAX_REORG_DEPTH
Default for -maxreorgdepth.
Definition: validation.h:98
CBlockIndex * ValidatedTip() const
Definition: validation.h:1145
bool GetTransaction(const TxId &txid, CTransactionRef &txOut, const Consensus::Params &params, BlockHash &hashBlock, const CBlockIndex *const blockIndex=nullptr)
Retrieve a transaction (from memory pool, or from disk, if possible).
Definition: validation.cpp:800
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:778
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:157
unsigned int nIn
Definition: validation.h:451
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:79
bool TestBlockValidity(BlockValidationState &state, const CChainParams &params, const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:194
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:493
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
Definition: validation.h:466
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:111
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:231
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev...
Definition: validation.h:126
int GetSpendHeight(const CCoinsViewCache &inputs)
Return the spend height, which is one more than the inputs.GetBestBlock().
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 fCheckpointsEnabled
Definition: validation.cpp:114
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
ScriptExecutionMetrics metrics
Definition: validation.h:455
std::set< CBlockIndex * > m_failed_blocks
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to conn...
Definition: validation.h:587
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:358
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
ScriptError GetScriptError() const
Definition: validation.h:491
BlockHash hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:118
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:457
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:177
static const bool DEFAULT_TXINDEX
Definition: validation.h:85
void UnloadBlockIndex()
Unload database information.
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition: validation.h:189
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
CChain & ActiveChain() const
Definition: validation.h:1119
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:788
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:112
uint32_t nFlags
Definition: validation.h:452
bool fCheckBlockIndex
Definition: validation.cpp:113
BlockMap & BlockIndex()
Please prefer the identical ChainstateManager::BlockIndex.
Definition: validation.cpp:938
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:80
void UnparkBlockAndChildren(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove parked status from a block and its descendants.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
Definition: validation.cpp:860
CBlockIndex * ActiveTip() const
Definition: validation.h:1121
LockPoints lp
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
Mutex g_best_block_mutex
Definition: validation.cpp:105
CheckInputsLimiter(int64_t limit)
Definition: validation.h:291
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1123