Bitcoin Core  0.21.1
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules
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 
27 #include <atomic>
28 #include <map>
29 #include <memory>
30 #include <set>
31 #include <stdint.h>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 class CChainState;
38 class CBlockIndex;
39 class CBlockTreeDB;
40 class CBlockUndo;
41 class CChainParams;
42 class CInv;
43 class CConnman;
44 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 
98 {
99  // this used to call `GetCheapHash()` in uint256, which was later moved; the
100  // cheap hash function simply calls ReadLE64() however, so the end result is
101  // identical
102  size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); }
103 };
104 
107  INIT_REINDEX,
109  POST_INIT
110 };
111 
112 extern RecursiveMutex cs_main;
114 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
116 extern std::condition_variable g_best_block_cv;
117 extern uint256 g_best_block;
118 extern std::atomic_bool fImporting;
119 extern std::atomic_bool fReindex;
123 extern bool g_parallel_script_checks;
124 extern bool fRequireStandard;
125 extern bool fCheckBlockIndex;
126 extern bool fCheckpointsEnabled;
128 extern CFeeRate minRelayTxFee;
130 extern int64_t nMaxTipAge;
131 
133 extern uint256 hashAssumeValid;
134 
137 
140 
143 extern bool fHavePruned;
145 extern bool fPruneMode;
147 extern uint64_t nPruneTarget;
149 extern const std::vector<std::string> CHECKLEVEL_DOC;
150 
152 FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false);
154 fs::path GetBlockPosFilename(const FlatFilePos &pos);
156 void LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos* dbp = nullptr);
158 bool LoadGenesisBlock(const CChainParams& chainparams);
160 void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman);
162 void ThreadScriptCheck(int worker_num);
175 CTransactionRef GetTransaction(const CBlockIndex* const block_index, const CTxMemPool* const mempool, const uint256& hash, const Consensus::Params& consensusParams, uint256& hashBlock);
182 bool ActivateBestChain(BlockValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
183 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
184 
186 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
187 
189 uint64_t CalculateCurrentUsage();
190 
194 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune);
195 
197 void PruneBlockFilesManual(int nManualPruneHeight);
198 
202 bool AcceptToMemoryPool(CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
203  std::list<CTransactionRef>* plTxnReplaced,
204  bool bypass_limits, bool test_accept=false, CAmount* fee_out=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
205 
208 
211 
214 
215 
217 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
218 
228 bool CheckFinalTx(const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
229 
234 
246 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false) EXCLUSIVE_LOCKS_REQUIRED(::cs_main, pool.cs);
247 
253 {
254 private:
257  unsigned int nIn;
258  unsigned int nFlags;
262 
263 public:
264  CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
265  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
266  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
267 
268  bool operator()();
269 
270  void swap(CScriptCheck &check) {
271  std::swap(ptxTo, check.ptxTo);
272  std::swap(m_tx_out, check.m_tx_out);
273  std::swap(nIn, check.nIn);
274  std::swap(nFlags, check.nFlags);
275  std::swap(cacheStore, check.cacheStore);
276  std::swap(error, check.error);
277  std::swap(txdata, check.txdata);
278  }
279 
280  ScriptError GetScriptError() const { return error; }
281 };
282 
285 
286 
288 bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams);
289 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
290 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start);
291 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start);
292 
293 bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex);
294 
298 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
299 
301 bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
302 
305 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
306 
308 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
309 
311 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
312 
314 class CVerifyDB {
315 public:
316  CVerifyDB();
317  ~CVerifyDB();
318  bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
319 };
320 
322 
324 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
325 
327 {
328  DISCONNECT_OK, // All good.
329  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
330  DISCONNECT_FAILED // Something else went wrong.
331 };
332 
333 class ConnectTrace;
334 
336 enum class FlushStateMode {
337  NONE,
338  IF_NEEDED,
339  PERIODIC,
340  ALWAYS
341 };
342 
344 {
345  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
346 };
347 
356 {
357  friend CChainState;
358 
359 private:
360  /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
361  void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height);
362 
378  void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, bool is_ibd);
379 
380 public:
381  BlockMap m_block_index GUARDED_BY(cs_main);
382 
401  std::set<CBlockIndex*> m_failed_blocks;
402 
407  std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
408 
417  bool LoadBlockIndex(
418  const Consensus::Params& consensus_params,
419  CBlockTreeDB& blocktree,
420  std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
421  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
422 
424  void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
425 
429 
431  void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
432 
437  bool AcceptBlockHeader(
438  const CBlockHeader& block,
439  BlockValidationState& state,
440  const CChainParams& chainparams,
441  CBlockIndex** ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
442 
444  Unload();
445  }
446 };
447 
457 class CoinsViews {
458 
459 public:
462  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
463 
465  CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
466 
469  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
470 
477  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
478 
480  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
481 };
482 
484 {
486  CRITICAL = 2,
488  LARGE = 1,
489  OK = 0
490 };
491 
507 {
508 protected:
515  int32_t nBlockSequenceId = 1;
520 
526 
533  mutable std::atomic<bool> m_cached_finished_ibd{false};
534 
539 
542 
544  std::unique_ptr<CoinsViews> m_coins_views;
545 
546 public:
547  explicit CChainState(CTxMemPool& mempool, BlockManager& blockman, uint256 from_snapshot_blockhash = uint256());
548 
555  void InitCoinsDB(
556  size_t cache_size_bytes,
557  bool in_memory,
558  bool should_wipe,
559  std::string leveldb_name = "chainstate");
560 
563  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
564 
567  bool CanFlushToDisk() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
568  return m_coins_views && m_coins_views->m_cacheview;
569  }
570 
574 
581 
587  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
588 
591  {
592  assert(m_coins_views->m_cacheview);
593  return *m_coins_views->m_cacheview.get();
594  }
595 
598  {
599  return m_coins_views->m_dbview;
600  }
601 
605  {
606  return m_coins_views->m_catcherview;
607  }
608 
610  void ResetCoinsViews() { m_coins_views.reset(); }
611 
614 
617 
620  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
621  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
622 
634  bool FlushStateToDisk(
635  const CChainParams& chainparams,
636  BlockValidationState &state,
637  FlushStateMode mode,
638  int nManualPruneHeight = 0);
639 
641  void ForceFlushStateToDisk();
642 
645  void PruneAndFlush();
646 
661  bool ActivateBestChain(
662  BlockValidationState& state,
663  const CChainParams& chainparams,
664  std::shared_ptr<const CBlock> pblock) LOCKS_EXCLUDED(cs_main);
665 
666  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);
667 
668  // Block (dis)connection on a given view:
669  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
670  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
671  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
672 
673  // Apply the effects of a block disconnection on the UTXO set.
674  bool DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool.cs);
675 
676  // Manual block validity manipulation:
677  bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
678  bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
680 
682  bool ReplayBlocks(const CChainParams& params);
683  bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
684  bool LoadGenesisBlock(const CChainParams& chainparams);
685 
687 
688  void UnloadBlockIndex();
689 
691  bool IsInitialBlockDownload() const;
692 
698  void CheckBlockIndex(const Consensus::Params& consensusParams);
699 
701  void LoadMempool(const ArgsManager& args);
702 
704  bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
705 
709  CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool* tx_pool)
710  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
711 
712  CoinsCacheSizeState GetCoinsCacheSizeState(
713  const CTxMemPool* tx_pool,
714  size_t max_coins_cache_size_bytes,
715  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
716 
717  std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
718 
719 private:
720  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);
721  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);
722 
723  void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
725  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
726 
727  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
728 
731 
733 };
734 
740 bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
741 
743 bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
744 
747 
781 class ChainstateManager
782 {
783 private:
801  std::unique_ptr<CChainState> m_ibd_chainstate;
802 
814  std::unique_ptr<CChainState> m_snapshot_chainstate;
815 
827  CChainState* m_active_chainstate{nullptr};
828 
831  bool m_snapshot_validated{false};
832 
833  // For access to m_active_chainstate.
834  friend CChainState& ChainstateActive();
835  friend CChain& ChainActive();
836 
837 public:
840  BlockManager m_blockman GUARDED_BY(::cs_main);
841 
844  int64_t m_total_coinstip_cache{0};
845  //
848  int64_t m_total_coinsdb_cache{0};
849 
854  // constructor
857  CChainState& InitializeChainstate(CTxMemPool& mempool, const uint256& snapshot_blockhash = uint256())
858  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
859 
861  std::vector<CChainState*> GetAll();
862 
864  CChainState& ActiveChainstate() const;
865  CChain& ActiveChain() const { return ActiveChainstate().m_chain; }
866  int ActiveHeight() const { return ActiveChain().Height(); }
867  CBlockIndex* ActiveTip() const { return ActiveChain().Tip(); }
868 
870  {
871  return m_blockman.m_block_index;
872  }
873 
874  bool IsSnapshotActive() const;
875 
876  Optional<uint256> SnapshotBlockhash() const;
877 
879  bool IsSnapshotValidated() const { return m_snapshot_validated; }
880 
883  bool IsBackgroundIBD(CChainState* chainstate) const;
884 
889  CChainState& ValidatedChainstate() const;
890 
891  CChain& ValidatedChain() const { return ValidatedChainstate().m_chain; }
892  CBlockIndex* ValidatedTip() const { return ValidatedChain().Tip(); }
893 
914  bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
915 
927  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
928 
930  bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
931 
933  void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
934 
936  void Reset();
937 
940  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
941 };
942 
944 extern ChainstateManager g_chainman GUARDED_BY(::cs_main);
945 
948 
951 
953 extern std::unique_ptr<CBlockTreeDB> pblocktree;
954 
960 int GetSpendHeight(const CCoinsViewCache& inputs);
961 
963 
967 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
968 
971 
973 bool DumpMempool(const CTxMemPool& pool);
974 
976 bool LoadMempool(CTxMemPool& pool);
977 
979 inline bool IsBlockPruned(const CBlockIndex* pblockindex)
980 {
981  return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
982 }
983 
984 #endif // BITCOIN_VALIDATION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:395
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:60
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:616
int ActiveHeight() const
Definition: validation.h:866
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:206
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:68
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:62
bool PreciousBlock(BlockValidationState &state, const CChainParams &params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
bool LoadBlockIndex(const Consensus::Params &consensus_params, CBlockTreeDB &blocktree, std::set< CBlockIndex *, CBlockIndexWorkComparator > &block_index_candidates) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
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:144
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:106
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:573
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
enum ScriptError_t ScriptError
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:114
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 CheckBlockIndex(const Consensus::Params &consensusParams)
Make various assertions about the state of the block index.
void swap(CScriptCheck &check)
Definition: validation.h:270
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:355
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:457
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:781
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.
static void pool cs
unsigned int nFlags
Definition: validation.h:258
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:427
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:131
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:326
unsigned int nHeight
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:135
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:151
bool DisconnectTip(BlockValidationState &state, const CChainParams &chainparams, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
The coins cache is in immediate need of a flush.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:610
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:506
bool IsInitialBlockDownload() const
Check whether we are doing an initial block download (synchronizing from disk or network) ...
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
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
Dictates whether we need to flush the cache to disk or not.
ScriptError GetScriptError() const
Definition: validation.h:280
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:52
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
Connect a new block to m_chain.
ScriptError error
Definition: validation.h:260
ThresholdState
BIP 9 defines a finite-state-machine to deploy a softfork in multiple stages.
Definition: versionbits.h:25
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
Definition: validation.h:533
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:77
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
CChainState(CTxMemPool &mempool, BlockManager &blockman, uint256 from_snapshot_blockhash=uint256())
bool cacheStore
Definition: validation.h:259
bool CheckSequenceLocks(const CTxMemPool &pool, const CTransaction &tx, int flags, LockPoints *lp, bool useExistingLockPoints)
Definition: validation.cpp:256
bool ConnectBlock(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, const CChainParams &chainparams, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins...
unsigned char * begin()
Definition: uint256.h:58
CTxOut m_tx_out
Definition: validation.h:255
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:265
friend CChainState
Definition: validation.h:357
Transaction validation functions.
Definition: params.h:12
bool ActivateBestChain(BlockValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock) LOCKS_EXCLUDED(cs_main)
Make the best chain active, in multiple steps.
void LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp=nullptr)
Import blocks from an external file.
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
bool RewindBlockIndex(const CChainParams &params) LOCKS_EXCLUDED(cs_main)
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned...
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:525
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:71
CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:78
bool error(const char *fmt, const Args &...args)
Definition: system.h:52
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:879
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:76
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:597
Access to the block database (blocks/index/)
Definition: txdb.h:96
Abstract view on the open txout dataset.
Definition: coins.h:180
DeploymentPos
Definition: params.h:14
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
BlockMap m_block_index GUARDED_BY(cs_main)
bool ReadRawBlockFromDisk(std::vector< uint8_t > &block, const FlatFilePos &pos, const CMessageHeader::MessageStartChars &message_start)
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool LoadGenesisBlock(const CChainParams &chainparams)
bool fHavePruned
Pruning-related variables and constants.
Definition: validation.cpp:138
void InitScriptExecutionCache()
Initializes the script-execution cache.
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:124
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
FlushStateMode
Definition: validation.h:336
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:314
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:113
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:238
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
size_t operator()(const uint256 &hash) const
Definition: validation.h:102
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
CBlockIndex * AddToBlockIndex(const CBlockHeader &block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
const uint256 m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from. ...
Definition: validation.h:580
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:147
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Definition: validation.h:80
Definition: net.h:187
ChainstateManager g_chainman
Definition: validation.cpp:104
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:544
Parameters that influence chain consensus.
Definition: params.h:56
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:76
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:519
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.
bool m_mempool cs
Definition: validation.h:674
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're trying to stay below.
Definition: validation.cpp:143
uint256 g_best_block
Definition: validation.cpp:134
Check if transaction will be BIP 68 final in the next block to be created.
Definition: validation.h:252
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:401
void UnloadBlockIndex()
int32_t nBlockSequenceId
Blocks loaded from disk are assigned id 0, so start the counter at 1.
Definition: validation.h:515
int flags
Definition: bitcoin-tx.cpp:506
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:149
std::condition_variable g_best_block_cv
Definition: validation.cpp:133
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:483
const CTransaction * ptxTo
Definition: validation.h:256
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h: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:488
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:517
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:613
#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:129
bool fRequireStandard
Definition: validation.cpp:140
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...
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
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:979
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:814
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
CBlockIndex * ValidatedTip() const
Definition: validation.h:892
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
Definition: validation.h:801
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:146
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
void EraseBlockData(CBlockIndex *index) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as not having block data.
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
Definition: validation.cpp:86
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:587
CChain & ValidatedChain() const
Definition: validation.h:891
static uint64_t ReadLE64(const unsigned char *ptr)
Definition: common.h:31
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'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:538
bool InvalidateBlock(BlockValidationState &state, const CChainParams &chainparams, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:173
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:590
CTxMemPool & m_mempool
mempool that is kept in sync with the chain
Definition: validation.h:541
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:180
unsigned int nIn
Definition: validation.h:257
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:407
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:106
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:259
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:114
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're running in -prune mode.
Definition: validation.cpp:139
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:236
full block available in blk*.dat
Definition: chain.h:121
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:95
bool ReplayBlocks(const CChainParams &params)
Replay blocks that aren't fully applied to the database.
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:142
bool LoadChainTip(const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos, const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
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:357
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
CBlockIndex * ActiveTip() const
Definition: validation.h:867
VersionBitsCache versionbitscache
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:199
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) ...
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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:513
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)
Store block on disk.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:604
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:86
bool fCheckBlockIndex
Definition: validation.cpp:141
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:70
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs, const CChainParams &params) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied...
LockPoints lp
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
Mutex g_best_block_mutex
Definition: validation.cpp:132
PrecomputedTransactionData * txdata
Definition: validation.h:261
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:869