Bitcoin Core  21.99.0
P2P Digital Currency
validation.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 #ifndef BITCOIN_VALIDATION_H
7 #define BITCOIN_VALIDATION_H
8 
9 #if defined(HAVE_CONFIG_H)
10 #include <config/bitcoin-config.h>
11 #endif
12 
13 #include <amount.h>
14 #include <coins.h>
15 #include <crypto/common.h> // for ReadLE64
16 #include <fs.h>
17 #include <optional.h>
18 #include <policy/feerate.h>
19 #include <protocol.h> // For CMessageHeader::MessageStartChars
20 #include <script/script_error.h>
21 #include <sync.h>
22 #include <txmempool.h> // For CTxMemPool::cs
23 #include <txdb.h>
24 #include <versionbits.h>
25 #include <serialize.h>
26 #include <util/hasher.h>
27 
28 #include <atomic>
29 #include <map>
30 #include <memory>
31 #include <set>
32 #include <stdint.h>
33 #include <string>
34 #include <utility>
35 #include <vector>
36 
37 class CChainState;
39 class CBlockIndex;
40 class CBlockTreeDB;
41 class CBlockUndo;
42 class CChainParams;
43 class CInv;
44 class CConnman;
45 class CScriptCheck;
46 class CTxMemPool;
47 class ChainstateManager;
48 class TxValidationState;
49 struct ChainTxData;
50 
53 struct LockPoints;
54 
56 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
58 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
60 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
62 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
64 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
66 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
68 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
70 static const int MAX_SCRIPTCHECK_THREADS = 15;
72 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
73 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
74 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
75 static const bool DEFAULT_TXINDEX = false;
76 static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
78 static const bool DEFAULT_PERSIST_MEMPOOL = true;
80 static const bool DEFAULT_FEEFILTER = true;
82 static const int DEFAULT_STOPATHEIGHT = 0;
84 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
85 static const signed int DEFAULT_CHECKBLOCKS = 6;
86 static const unsigned int DEFAULT_CHECKLEVEL = 3;
87 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
88 // At 1MB per block, 288 blocks = 288MB.
89 // Add 15% for Undo data = 331MB
90 // Add 20% for Orphan block rate = 397MB
91 // We want the low water mark after pruning to be at least 397 MB and since we prune in
92 // full block file chunks, we need the high water mark which triggers the prune to be
93 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
94 // Setting the target to >= 550 MiB will make it likely we can respect the target.
95 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
96 
101  POST_INIT
102 };
103 
104 extern RecursiveMutex cs_main;
105 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
107 extern std::condition_variable g_best_block_cv;
108 extern uint256 g_best_block;
109 extern std::atomic_bool fImporting;
110 extern std::atomic_bool fReindex;
114 extern bool g_parallel_script_checks;
115 extern bool fRequireStandard;
116 extern bool fCheckBlockIndex;
117 extern bool fCheckpointsEnabled;
119 extern CFeeRate minRelayTxFee;
121 extern int64_t nMaxTipAge;
122 
124 extern uint256 hashAssumeValid;
125 
128 
131 
134 extern bool fHavePruned;
136 extern bool fPruneMode;
138 extern uint64_t nPruneTarget;
140 extern const std::vector<std::string> CHECKLEVEL_DOC;
141 
143 FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false);
145 fs::path GetBlockPosFilename(const FlatFilePos &pos);
147 void LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos* dbp = nullptr);
149 bool LoadGenesisBlock(const CChainParams& chainparams);
151 void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman);
153 void ThreadScriptCheck(int worker_num);
166 CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock);
173 bool ActivateBestChain(BlockValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
174 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
175 
177 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
178 
180 uint64_t CalculateCurrentUsage();
181 
185 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune);
186 
188 void PruneBlockFilesManual(int nManualPruneHeight);
189 
193 bool AcceptToMemoryPool(CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
194  std::list<CTransactionRef>* plTxnReplaced,
195  bool bypass_limits, bool test_accept=false, CAmount* fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
196 
199 
202 
205 
206 
208 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
209 
219 bool CheckFinalTx(const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
220 
225 
237 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, pool.cs);
238 
244 {
245 private:
248  unsigned int nIn;
249  unsigned int nFlags;
253 
254 public:
255  CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
256  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
257  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
258 
259  bool operator()();
260 
261  void swap(CScriptCheck &check) {
262  std::swap(ptxTo, check.ptxTo);
263  std::swap(m_tx_out, check.m_tx_out);
264  std::swap(nIn, check.nIn);
265  std::swap(nFlags, check.nFlags);
266  std::swap(cacheStore, check.cacheStore);
267  std::swap(error, check.error);
268  std::swap(txdata, check.txdata);
269  }
270 
271  ScriptError GetScriptError() const { return error; }
272 };
273 
276 
277 
279 bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams);
280 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
281 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start);
282 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start);
283 
284 bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex);
285 
289 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
290 
292 bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
293 
296 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
297 
299 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
300 
302 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
303 
305 class CVerifyDB {
306 public:
307  CVerifyDB();
308  ~CVerifyDB();
309  bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
310 };
311 
313 
315 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
316 
318 {
319  DISCONNECT_OK, // All good.
320  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
321  DISCONNECT_FAILED // Something else went wrong.
322 };
323 
324 class ConnectTrace;
325 
327 enum class FlushStateMode {
328  NONE,
329  IF_NEEDED,
330  PERIODIC,
331  ALWAYS
332 };
333 
335 {
336  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
337 };
338 
347 {
348  friend CChainState;
349 
350 private:
351  /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
352  void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height);
353 
369  void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, bool is_ibd);
370 
371 public:
372  BlockMap m_block_index GUARDED_BY(cs_main);
373 
392  std::set<CBlockIndex*> m_failed_blocks;
393 
398  std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
399 
408  bool LoadBlockIndex(
409  const Consensus::Params& consensus_params,
410  CBlockTreeDB& blocktree,
411  std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
412  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
413 
415  void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
416 
417  CBlockIndex* AddToBlockIndex(const CBlockHeader& block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
419  CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
420 
422  void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
423 
428  bool AcceptBlockHeader(
429  const CBlockHeader& block,
430  BlockValidationState& state,
431  const CChainParams& chainparams,
432  CBlockIndex** ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
433 
435  Unload();
436  }
437 };
438 
448 class CoinsViews {
449 
450 public:
453  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
454 
456  CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
457 
460  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
461 
468  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
469 
471  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
472 };
473 
475 {
477  CRITICAL = 2,
479  LARGE = 1,
480  OK = 0
481 };
482 
498 {
499 protected:
506  int32_t nBlockSequenceId = 1;
508  int32_t nBlockReverseSequenceId = -1;
510  arith_uint256 nLastPreciousChainwork = 0;
511 
517 
524  mutable std::atomic<bool> m_cached_finished_ibd{false};
525 
530 
533 
535  std::unique_ptr<CoinsViews> m_coins_views;
536 
537 public:
538  explicit CChainState(CTxMemPool& mempool, BlockManager& blockman, uint256 from_snapshot_blockhash = uint256());
539 
546  void InitCoinsDB(
547  size_t cache_size_bytes,
548  bool in_memory,
549  bool should_wipe,
550  std::string leveldb_name = "chainstate");
551 
554  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
555 
558  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
559  return m_coins_views && m_coins_views->m_cacheview;
560  }
561 
565 
571  const uint256 m_from_snapshot_blockhash{};
572 
578  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
579 
581  CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
582  {
583  assert(m_coins_views->m_cacheview);
584  return *m_coins_views->m_cacheview.get();
585  }
586 
588  CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
589  {
590  return m_coins_views->m_dbview;
591  }
592 
595  CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
596  {
597  return m_coins_views->m_catcherview;
598  }
599 
601  void ResetCoinsViews() { m_coins_views.reset(); }
602 
604  size_t m_coinsdb_cache_size_bytes{0};
605 
607  size_t m_coinstip_cache_size_bytes{0};
608 
611  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
612  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
613 
625  bool FlushStateToDisk(
626  const CChainParams& chainparams,
627  BlockValidationState &state,
628  FlushStateMode mode,
629  int nManualPruneHeight = 0);
630 
632  void ForceFlushStateToDisk();
633 
636  void PruneAndFlush();
637 
652  bool ActivateBestChain(
653  BlockValidationState& state,
654  const CChainParams& chainparams,
655  std::shared_ptr<const CBlock> pblock) LOCKS_EXCLUDED(cs_main);
656 
657  bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
658 
659  // Block (dis)connection on a given view:
660  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
661  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
662  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
663 
664  // Apply the effects of a block disconnection on the UTXO set.
665  bool DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool.cs);
666 
667  // Manual block validity manipulation:
668  bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
669  bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
671 
673  bool ReplayBlocks(const CChainParams& params);
674  bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
675  bool LoadGenesisBlock(const CChainParams& chainparams);
676 
677  void PruneBlockIndexCandidates();
678 
679  void UnloadBlockIndex();
680 
682  bool IsInitialBlockDownload() const;
683 
689  void CheckBlockIndex(const Consensus::Params& consensusParams);
690 
692  void LoadMempool(const ArgsManager& args);
693 
695  bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
696 
700  CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool* tx_pool)
701  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
702 
703  CoinsCacheSizeState GetCoinsCacheSizeState(
704  const CTxMemPool* tx_pool,
705  size_t max_coins_cache_size_bytes,
706  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
707 
708  std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
709 
710 private:
711  bool ActivateBestChainStep(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool.cs);
712  bool ConnectTip(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool.cs);
713 
714  void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
715  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
716  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
717 
718  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
719 
721  void EraseBlockData(CBlockIndex* index) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
722 
724 };
725 
731 bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
732 
734 bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
735 
737 void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
738 
772 class ChainstateManager
773 {
774 private:
792  std::unique_ptr<CChainState> m_ibd_chainstate;
793 
805  std::unique_ptr<CChainState> m_snapshot_chainstate;
806 
818  CChainState* m_active_chainstate{nullptr};
819 
822  bool m_snapshot_validated{false};
823 
824  // For access to m_active_chainstate.
825  friend CChainState& ChainstateActive();
826  friend CChain& ChainActive();
827 
828 public:
831  BlockManager m_blockman GUARDED_BY(::cs_main);
832 
835  int64_t m_total_coinstip_cache{0};
836  //
839  int64_t m_total_coinsdb_cache{0};
840 
845  // constructor
848  CChainState& InitializeChainstate(CTxMemPool& mempool, const uint256& snapshot_blockhash = uint256())
849  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
850 
852  std::vector<CChainState*> GetAll();
853 
855  CChainState& ActiveChainstate() const;
856  CChain& ActiveChain() const { return ActiveChainstate().m_chain; }
857  int ActiveHeight() const { return ActiveChain().Height(); }
858  CBlockIndex* ActiveTip() const { return ActiveChain().Tip(); }
859 
860  BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
861  {
862  return m_blockman.m_block_index;
863  }
864 
865  bool IsSnapshotActive() const;
866 
867  Optional<uint256> SnapshotBlockhash() const;
868 
870  bool IsSnapshotValidated() const { return m_snapshot_validated; }
871 
874  bool IsBackgroundIBD(CChainState* chainstate) const;
875 
880  CChainState& ValidatedChainstate() const;
881 
882  CChain& ValidatedChain() const { return ValidatedChainstate().m_chain; }
883  CBlockIndex* ValidatedTip() const { return ValidatedChain().Tip(); }
884 
905  bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
906 
918  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
919 
921  bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
922 
924  void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
925 
927  void Reset();
928 
931  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
932 };
933 
935 extern ChainstateManager g_chainman GUARDED_BY(::cs_main);
936 
939 
942 
944 extern std::unique_ptr<CBlockTreeDB> pblocktree;
945 
951 int GetSpendHeight(const CCoinsViewCache& inputs);
952 
954 
958 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
959 
962 
964 bool DumpMempool(const CTxMemPool& pool);
965 
967 bool LoadMempool(CTxMemPool& pool);
968 
970 inline bool IsBlockPruned(const CBlockIndex* pblockindex)
971 {
972  return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
973 }
974 
975 #endif // BITCOIN_VALIDATION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:60
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:72
Display status of an in-progress BIP9 softfork.
Definition: versionbits.h:39
bool CheckFinalTx(const CTransaction &tx, int flags=-1) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Transaction validation functions.
Definition: validation.cpp:203
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:68
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:62
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:143
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:98
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:564
assert(!tx.IsCoinBase())
enum ScriptError_t ScriptError
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:114
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:174
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const uint256 &hash, const Consensus::Params &consensusParams, uint256 &hashBlock)
Return transaction from the block at block_index.
void swap(CScriptCheck &check)
Definition: validation.h:261
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:346
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
Definition: block.h:62
The cache is at >= 90% capacity.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:448
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:772
An in-memory indexed chain of blocks.
Definition: chain.h:379
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
unsigned int nFlags
Definition: validation.h:249
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:73
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
inv message data
Definition: protocol.h:423
bool PreciousBlock(BlockValidationState &state, const CChainParams &params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:130
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:84
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:58
DisconnectResult
Definition: validation.h:317
unsigned int nHeight
CChain & ValidatedChain() const
Definition: validation.h:882
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:134
The coins cache is in immediate need of a flush.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:601
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:497
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
ScriptError error
Definition: validation.h:251
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:25
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:76
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:250
bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Definition: validation.cpp:253
CTxOut m_tx_out
Definition: validation.h:246
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...
Called by RandAddPeriodic()
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:256
friend CChainState
Definition: validation.h:348
Transaction validation functions.
Definition: params.h:12
void LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp=nullptr)
Import blocks from an external file.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static void pool cs
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:516
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:78
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:75
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value). ...
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:588
Access to the block database (blocks/index/)
Definition: txdb.h:96
Abstract view on the open txout dataset.
Definition: coins.h:153
DeploymentPos
Definition: params.h:14
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:137
void InitScriptExecutionCache()
Initializes the script-execution cache.
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
bool LoadMempool(CTxMemPool &pool)
Load the mempool from disk.
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:870
FlushStateMode
Definition: validation.h:327
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:305
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:56
CChain & ChainActive()
Please prefer the identical ChainstateManager::ActiveChain.
Definition: validation.cpp:112
int ActiveHeight() const
Definition: validation.h:857
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:235
Holds various statistics on transactions within a chain.
Definition: chainparams.h:39
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:64
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:66
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:82
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:146
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Definition: validation.h:80
Definition: net.h:795
ChainstateManager g_chainman
Definition: validation.cpp:103
An output of a transaction.
Definition: transaction.h:128
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:535
Parameters that influence chain consensus.
Definition: params.h:46
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:76
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
int32_t ComputeBlockVersion(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Determine what nVersion a new block should use.
256-bit unsigned big integer.
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:38
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:142
uint256 g_best_block
Definition: validation.cpp:133
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.h:243
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:392
int flags
Definition: bitcoin-tx.cpp:512
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:148
std::condition_variable g_best_block_cv
Definition: validation.cpp:132
std::atomic_bool fReindex
bool ActivateBestChain(BlockValidationState &state, const CChainParams &chainparams, 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.
256-bit opaque blob.
Definition: uint256.h:124
CoinsCacheSizeState
Definition: validation.h:474
const CTransaction * ptxTo
Definition: validation.h:247
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:74
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:474
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:128
bool fRequireStandard
Definition: validation.cpp:139
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for a block, and whether to enforce NULLDUMMY (BIP 147...
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:137
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.
Definition: validation.h:970
Undo information for a CBlock.
Definition: undo.h:63
std::unique_ptr< CChainState > m_snapshot_chainstate
A chainstate initialized on the basis of a UTXO snapshot.
Definition: validation.h:805
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:85
ChainstateManager g_chainman GUARDED_BY(::cs_main)
DEPRECATED! Please use node.chainman instead.
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:46
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
Definition: validation.h:792
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
bool InvalidateBlock(BlockValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as invalid.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:145
CChainState &InitializeChainstate(CTxMemPool &mempool, const uint256 &snapshot_blockhash=uint256()) 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:852
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:578
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 DumpMempool(const CTxMemPool &pool)
Dump the mempool to disk.
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
Definition: validation.h:529
CBlockIndex * ValidatedTip() const
Definition: validation.h:883
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:170
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:581
CTxMemPool & m_mempool
mempool that is kept in sync with the chain
Definition: validation.h:532
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:177
unsigned int nIn
Definition: validation.h:248
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:398
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
Functions for validating blocks and updating the block tree.
CChainState & ChainstateActive()
Please prefer the identical ChainstateManager::ActiveChainstate.
Definition: validation.cpp:105
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:105
bool AcceptToMemoryPool(CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, bool test_accept=false, CAmount *fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:138
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:209
full block available in blk*.dat
Definition: chain.h:121
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:95
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:141
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:330
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
VersionBitsCache versionbitscache
ScriptError GetScriptError() const
Definition: validation.h:271
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:196
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW=true, bool fCheckMerkleRoot=true) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check a block is completely valid from start to finish (only works on top of our current best block) ...
static const bool DEFAULT_TXINDEX
Definition: validation.h:75
RecursiveMutex cs_nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Definition: validation.h:504
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:166
std::optional< T > Optional
Substitute for C++17 std::optional DEPRECATED use std::optional in new code.
Definition: optional.h:14
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
CChain & ActiveChain() const
Definition: validation.h:856
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:595
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:86
bool fCheckBlockIndex
Definition: validation.cpp:140
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:562
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:70
CBlockIndex * ActiveTip() const
Definition: validation.h:858
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:131
PrecomputedTransactionData * txdata
Definition: validation.h:252
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:860