Bitcoin Core  0.19.99
P2P Digital Currency
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
9 #if defined(HAVE_CONFIG_H)
10 #include <config/bitcoin-config.h>
11 #endif
13 #include <amount.h>
14 #include <coins.h>
15 #include <crypto/common.h> // for ReadLE64
16 #include <fs.h>
17 #include <policy/feerate.h>
18 #include <protocol.h> // For CMessageHeader::MessageStartChars
19 #include <script/script_error.h>
20 #include <sync.h>
21 #include <txmempool.h> // For CTxMemPool::cs
22 #include <txdb.h>
23 #include <versionbits.h>
24 #include <serialize.h>
26 #include <atomic>
27 #include <map>
28 #include <memory>
29 #include <set>
30 #include <stdint.h>
31 #include <utility>
32 #include <vector>
34 class CChainState;
36 class CBlockIndex;
37 class CBlockTreeDB;
38 class CBlockUndo;
39 class CChainParams;
40 class CInv;
41 class CConnman;
42 class CScriptCheck;
44 class CTxMemPool;
45 class TxValidationState;
46 struct ChainTxData;
50 struct LockPoints;
53 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
55 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
57 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
59 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
61 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
67 static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000;
69 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
71 static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000;
73 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
75 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
77 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
80 static const int MAX_SCRIPTCHECK_THREADS = 15;
82 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
84 static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
86 static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
89 static const unsigned int MAX_HEADERS_RESULTS = 2000;
92 static const int MAX_CMPCTBLOCK_DEPTH = 5;
94 static const int MAX_BLOCKTXN_DEPTH = 10;
99 static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
101 static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60;
103 static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
105 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000;
107 static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000;
109 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
111 static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60;
113 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
114 static const bool DEFAULT_TXINDEX = false;
115 static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
116 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
118 static const bool DEFAULT_PERSIST_MEMPOOL = true;
120 static const bool DEFAULT_FEEFILTER = true;
123 static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8;
126 static const int MAX_UNCONNECTING_HEADERS = 10;
129 static const int DEFAULT_STOPATHEIGHT = 0;
132 {
133  // this used to call `GetCheapHash()` in uint256, which was later moved; the
134  // cheap hash function simply calls ReadLE64() however, so the end result is
135  // identical
136  size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); }
137 };
139 extern RecursiveMutex cs_main;
141 extern CTxMemPool mempool;
142 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
144 extern std::condition_variable g_best_block_cv;
145 extern uint256 g_best_block;
146 extern std::atomic_bool fImporting;
147 extern std::atomic_bool fReindex;
151 extern bool g_parallel_script_checks;
152 extern bool fRequireStandard;
153 extern bool fCheckBlockIndex;
154 extern bool fCheckpointsEnabled;
155 extern size_t nCoinCacheUsage;
157 extern CFeeRate minRelayTxFee;
159 extern int64_t nMaxTipAge;
162 extern uint256 hashAssumeValid;
172 extern bool fHavePruned;
174 extern bool fPruneMode;
176 extern uint64_t nPruneTarget;
178 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
180 static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS = 288;
182 static const signed int DEFAULT_CHECKBLOCKS = 6;
183 static const unsigned int DEFAULT_CHECKLEVEL = 3;
185 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
186 // At 1MB per block, 288 blocks = 288MB.
187 // Add 15% for Undo data = 331MB
188 // Add 20% for Orphan block rate = 397MB
189 // We want the low water mark after pruning to be at least 397 MB and since we prune in
190 // full block file chunks, we need the high water mark which triggers the prune to be
191 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
192 // Setting the target to >= 550 MiB will make it likely we can respect the target.
193 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
215 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
228 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
231 FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false);
233 fs::path GetBlockPosFilename(const FlatFilePos &pos);
235 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos *dbp = nullptr);
237 bool LoadGenesisBlock(const CChainParams& chainparams);
240 bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
242 void UnloadBlockIndex();
244 void ThreadScriptCheck(int worker_num);
246 bool GetTransaction(const uint256& hash, CTransactionRef& tx, const Consensus::Params& params, uint256& hashBlock, const CBlockIndex* const blockIndex = nullptr);
253 bool ActivateBestChain(BlockValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
254 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
257 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
260 uint64_t CalculateCurrentUsage();
265 void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
270 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune);
273 void PruneBlockFilesManual(int nManualPruneHeight);
277 bool AcceptToMemoryPool(CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
278  std::list<CTransactionRef>* plTxnReplaced,
279  bool bypass_limits, const CAmount nAbsurdFee, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
292 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
303 bool CheckFinalTx(const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
321 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
328 {
329 private:
332  unsigned int nIn;
333  unsigned int nFlags;
338 public:
339  CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
340  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
341  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
343  bool operator()();
345  void swap(CScriptCheck &check) {
346  std::swap(ptxTo, check.ptxTo);
347  std::swap(m_tx_out, check.m_tx_out);
348  std::swap(nIn, check.nIn);
349  std::swap(nFlags, check.nFlags);
350  std::swap(cacheStore, check.cacheStore);
351  std::swap(error, check.error);
352  std::swap(txdata, check.txdata);
353  }
355  ScriptError GetScriptError() const { return error; }
356 };
363 bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams);
364 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
365 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start);
366 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start);
368 bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex);
373 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
376 bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
380 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
383 bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
386 int GetWitnessCommitmentIndex(const CBlock& block);
389 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
392 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
395 class CVerifyDB {
396 public:
397  CVerifyDB();
398  ~CVerifyDB();
399  bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
400 };
405 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
408 {
409  DISCONNECT_OK, // All good.
410  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
411  DISCONNECT_FAILED // Something else went wrong.
412 };
414 class ConnectTrace;
417 enum class FlushStateMode {
418  NONE,
422 };
425 {
426  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
427 };
437 public:
438  BlockMap m_block_index GUARDED_BY(cs_main);
458  std::set<CBlockIndex*> m_failed_blocks;
464  std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
474  bool LoadBlockIndex(
475  const Consensus::Params& consensus_params,
476  CBlockTreeDB& blocktree,
477  std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
481  void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
483  CBlockIndex* AddToBlockIndex(const CBlockHeader& block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
485  CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
491  bool AcceptBlockHeader(
492  const CBlockHeader& block,
493  BlockValidationState& state,
494  const CChainParams& chainparams,
495  CBlockIndex** ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
496 };
507 class CoinsViews {
509 public:
512  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
515  CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
519  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
527  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
530  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
531 };
534 {
536  CRITICAL = 2,
538  LARGE = 1,
539  OK = 0
540 };
556 class CChainState {
557 private:
565  int32_t nBlockSequenceId = 1;
567  int32_t nBlockReverseSequenceId = -1;
569  arith_uint256 nLastPreciousChainwork = 0;
583  mutable std::atomic<bool> m_cached_finished_ibd{false};
591  std::unique_ptr<CoinsViews> m_coins_views;
593 public:
594  CChainState(BlockManager& blockman) : m_blockman(blockman) {}
595  CChainState();
603  void InitCoinsDB(
604  size_t cache_size_bytes,
605  bool in_memory,
606  bool should_wipe,
607  std::string leveldb_name = "chainstate");
611  void InitCoinsCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
615  bool CanFlushToDisk() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
616  return m_coins_views && m_coins_views->m_cacheview;
617  }
628  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
631  CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
632  {
633  assert(m_coins_views->m_cacheview);
634  return *m_coins_views->m_cacheview.get();
635  }
638  CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
639  {
640  return m_coins_views->m_dbview;
641  }
645  CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
646  {
647  return m_coins_views->m_catcherview;
648  }
651  void ResetCoinsViews() { m_coins_views.reset(); }
664  bool FlushStateToDisk(
665  const CChainParams& chainparams,
666  BlockValidationState &state,
667  FlushStateMode mode,
668  int nManualPruneHeight = 0);
671  void ForceFlushStateToDisk();
675  void PruneAndFlush();
691  bool ActivateBestChain(
692  BlockValidationState& state,
693  const CChainParams& chainparams,
694  std::shared_ptr<const CBlock> pblock) LOCKS_EXCLUDED(cs_main);
696  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);
698  // Block (dis)connection on a given view:
699  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
700  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
701  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
703  // Apply the effects of a block disconnection on the UTXO set.
704  bool DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::mempool.cs);
706  // Manual block validity manipulation:
707  bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
708  bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
712  bool ReplayBlocks(const CChainParams& params);
713  bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
714  bool LoadGenesisBlock(const CChainParams& chainparams);
716  void PruneBlockIndexCandidates();
718  void UnloadBlockIndex();
721  bool IsInitialBlockDownload() const;
728  void CheckBlockIndex(const Consensus::Params& consensusParams);
731  bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
736  CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool& tx_pool)
739  CoinsCacheSizeState GetCoinsCacheSizeState(
740  const CTxMemPool& tx_pool,
741  size_t max_coins_cache_size_bytes,
742  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
744 private:
745  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, ::mempool.cs);
746  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, ::mempool.cs);
748  void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
749  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
750  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
752  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
755  void EraseBlockData(CBlockIndex* index) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
756 };
763 bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
766 bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
769 void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
780 // Most often ::ChainstateActive() should be used instead of this, but some code
781 // may not be able to assume that this has been initialized yet and so must use it
782 // directly, e.g. init.cpp.
783 extern std::unique_ptr<CChainState> g_chainstate;
786 extern std::unique_ptr<CBlockTreeDB> pblocktree;
793 int GetSpendHeight(const CCoinsViewCache& inputs);
800 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
806 bool DumpMempool(const CTxMemPool& pool);
809 bool LoadMempool(CTxMemPool& pool);
812 inline bool IsBlockPruned(const CBlockIndex* pblockindex)
813 {
814  return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
815 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:57
CTxMemPool mempool
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:82
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:188
size_t nCoinCacheUsage
Definition: validation.cpp:120
static const int MAX_BLOCKTXN_DEPTH
Maximum depth of blocks we&#39;re willing to respond to GETBLOCKTXN requests for.
Definition: validation.h:94
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: validation.h:73
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:59
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:122
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:621
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:126
void swap(CScriptCheck &check)
Definition: validation.h:345
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:436
void ThreadScriptCheck(int worker_num)
Run an instance of the script checking thread.
Definition: block.h:72
CChainState(BlockManager &blockman)
Definition: validation.h:594
The cache is at >= 90% capacity.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:507
An in-memory indexed chain of blocks.
Definition: chain.h:379
static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE
Maximum kilobytes for transactions to store for processing during reorg.
Definition: validation.h:71
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
unsigned int nFlags
Definition: validation.h:333
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:109
void PruneBlockFilesManual(int nManualPruneHeight)
Prune block files up to a given height.
inv message data
Definition: protocol.h:375
bool PreciousBlock(BlockValidationState &state, const CChainParams &params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE
Block download timeout base, expressed in millionths of the block interval (i.e.
Definition: validation.h:105
CBlockIndex * pindexBestHeader
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.cpp:108
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:178
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:55
Definition: validation.h:407
unsigned int nHeight
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:112
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:129
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:238
The coins cache is in immediate need of a flush.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:651
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned.
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:556
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block&#39;s coinbase transaction the witness commitment occurs, or -1 if not found.
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:47
ScriptError error
Definition: validation.h:335
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.
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:334
unsigned char * begin()
Definition: uint256.h:54
bool RewindBlockIndex(const CChainParams &params) LOCKS_EXCLUDED(cs_main)
When there are blocks in the active chain with missing data, rewind the chainstate and remove them fr...
CTxOut m_tx_out
Definition: validation.h:330
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:340
Transaction validation functions.
Definition: params.h:12
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
bool LoadBlockIndex(const CChainParams &chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we&#39;re running with -reindex...
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:575
Default for -persistmempool.
Definition: validation.h:118
Additional block download timeout per parallel downloading peer (i.e.
Definition: validation.h:107
static const unsigned int NODE_NETWORK_LIMITED_MIN_BLOCKS
Minimum blocks required to signal NODE_NETWORK_LIMITED.
Definition: validation.h:180
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). ...
Definition: validation.h:638
Access to the block database (blocks/index/)
Definition: txdb.h:88
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: validation.h:75
Abstract view on the open txout dataset.
Definition: coins.h:154
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:115
void InitScriptExecutionCache()
Initializes the script-execution cache.
static const int64_t MAX_FEE_ESTIMATION_TIP_AGE
Maximum age of our tip in seconds for us to be considered current for fee estimation.
Definition: validation.h:111
The BlockPolicyEstimator is used for estimating the feerate needed for a transaction to be included i...
Definition: fees.h:131
Number of blocks that can be requested at any given time from a single peer.
Definition: validation.h:84
fs::path GetBlockPosFilename(const FlatFilePos &pos)
Translation to a filesystem path.
bool LoadMempool(CTxMemPool &pool)
Load the mempool from disk.
bool GetTransaction(const uint256 &hash, CTransactionRef &tx, const Consensus::Params &params, uint256 &hashBlock, const CBlockIndex *const blockIndex=nullptr)
Retrieve a transaction (from memory pool, or from disk, if possible)
Definition: validation.h:417
static const unsigned int MAX_HEADERS_RESULTS
Number of headers sent in one getheaders result.
Definition: validation.h:89
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:395
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:53
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: validation.h:77
CChain & ChainActive()
Definition: validation.cpp:91
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:220
Holds various statistics on transactions within a chain.
Definition: chainparams.h:34
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:61
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:69
Default for -stopatheight.
Definition: validation.h:129
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:125
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
static const bool DEFAULT_FEEFILTER
Default for using fee filter.
Definition: validation.h:120
Definition: net.h:121
An output of a transaction.
Definition: transaction.h:133
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:591
Parameters that influence chain consensus.
Definition: params.h:45
static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT
An extra transaction can be added to a package, as long as it only has one ancestor and is no larger ...
Definition: validation.h:67
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:115
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.
size_t operator()(const uint256 &hash) const
Definition: validation.h:136
256-bit unsigned big integer.
static const unsigned int DATABASE_WRITE_INTERVAL
Time to wait (in seconds) between writing blocks/block index to disk.
Definition: validation.h:101
unsigned char MessageStartChars[MESSAGE_START_SIZE]
Definition: protocol.h:37
uint64_t nPruneTarget
Number of MiB of block files that we&#39;re trying to stay below.
Definition: validation.cpp:121
uint256 g_best_block
Definition: validation.cpp:111
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:327
Maximum number of unconnecting headers announcements before DoS score.
Definition: validation.h:126
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:458
int flags
Definition: bitcoin-tx.cpp:508
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:127
std::condition_variable g_best_block_cv
Definition: validation.cpp:110
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:120
Definition: validation.h:533
const CTransaction * ptxTo
Definition: validation.h:331
Definition: validation.h:113
Definition: threadsafety.h:51
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:444
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:106
bool fRequireStandard
Definition: validation.cpp:117
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:812
Undo information for a CBlock.
Definition: undo.h:63
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:182
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:43
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:124
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:628
bool AcceptToMemoryPool(CTxMemPool &pool, TxValidationState &state, const CTransactionRef &tx, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
static const unsigned int MAX_BLOCKS_TO_ANNOUNCE
Maximum number of headers to announce when relaying blocks with headers message.
Definition: validation.h:123
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&#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:19
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
Definition: validation.h:588
#define GUARDED_BY(x)
Definition: threadsafety.h:38
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:152
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:631
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:159
unsigned int nIn
Definition: validation.h:332
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:464
std::unique_ptr< CChainState > g_chainstate
Definition: validation.cpp:84
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.
static const unsigned int DEFAULT_BANSCORE_THRESHOLD
Definition: validation.h:116
CChainState & ChainstateActive()
Definition: validation.cpp:86
static const unsigned int BLOCK_STALLING_TIMEOUT
Timeout in seconds during which a peer must stall block download progress before being disconnected...
Definition: validation.h:86
static const int MAX_CMPCTBLOCK_DEPTH
Maximum depth of blocks we&#39;re willing to serve as compact blocks to peers when requested.
Definition: validation.h:92
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:142
bool LoadExternalBlockFile(const CChainParams &chainparams, FILE *fileIn, FlatFilePos *dbp=nullptr)
Import blocks from an external file.
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:116
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:210
full block available in blk*.dat
Definition: chain.h:121
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:193
static const unsigned int DATABASE_FLUSH_INTERVAL
Time to wait (in seconds) between flushing chainstate to disk.
Definition: validation.h:103
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:119
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:334
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
VersionBitsCache versionbitscache
ScriptError GetScriptError() const
Definition: validation.h:355
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:178
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:114
void UnloadBlockIndex()
Unload database information.
RecursiveMutex cs_nBlockSequenceId
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Definition: validation.h:563
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
static const unsigned int BLOCK_DOWNLOAD_WINDOW
Size of the "block download window": how far ahead of our current height do we fetch? Larger windows tolerate larger download speed differences between peer, but increase the potential degree of disordering of blocks on disk (which make reindexing and pruning harder).
Definition: validation.h:99
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:645
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:183
bool fCheckBlockIndex
Definition: validation.cpp:118
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:521
BlockMap & BlockIndex()
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:80
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:109
PrecomputedTransactionData * txdata
Definition: validation.h:336