Bitcoin Core  0.20.99
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 
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";
77 static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100;
79 static const bool DEFAULT_PERSIST_MEMPOOL = true;
81 static const bool DEFAULT_FEEFILTER = true;
83 static const int DEFAULT_STOPATHEIGHT = 0;
85 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
86 static const signed int DEFAULT_CHECKBLOCKS = 6;
87 static const unsigned int DEFAULT_CHECKLEVEL = 3;
88 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
89 // At 1MB per block, 288 blocks = 288MB.
90 // Add 15% for Undo data = 331MB
91 // Add 20% for Orphan block rate = 397MB
92 // We want the low water mark after pruning to be at least 397 MB and since we prune in
93 // full block file chunks, we need the high water mark which triggers the prune to be
94 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
95 // Setting the target to >= 550 MiB will make it likely we can respect the target.
96 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
98 static constexpr size_t MINIMUM_WITNESS_COMMITMENT{38};
99 
101 {
102  // this used to call `GetCheapHash()` in uint256, which was later moved; the
103  // cheap hash function simply calls ReadLE64() however, so the end result is
104  // identical
105  size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); }
106 };
107 
110  INIT_REINDEX,
112  POST_INIT
113 };
114 
115 extern RecursiveMutex cs_main;
117 extern CTxMemPool mempool;
118 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
120 extern std::condition_variable g_best_block_cv;
121 extern uint256 g_best_block;
122 extern std::atomic_bool fImporting;
123 extern std::atomic_bool fReindex;
127 extern bool g_parallel_script_checks;
128 extern bool fRequireStandard;
129 extern bool fCheckBlockIndex;
130 extern bool fCheckpointsEnabled;
131 extern size_t nCoinCacheUsage;
133 extern CFeeRate minRelayTxFee;
135 extern int64_t nMaxTipAge;
136 
138 extern uint256 hashAssumeValid;
139 
142 
145 
148 extern bool fHavePruned;
150 extern bool fPruneMode;
152 extern uint64_t nPruneTarget;
154 extern const std::vector<std::string> CHECKLEVEL_DOC;
155 
157 FILE* OpenBlockFile(const FlatFilePos &pos, bool fReadOnly = false);
159 fs::path GetBlockPosFilename(const FlatFilePos &pos);
161 void LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, FlatFilePos* dbp = nullptr);
163 bool LoadGenesisBlock(const CChainParams& chainparams);
165 void UnloadBlockIndex();
167 void ThreadScriptCheck(int worker_num);
169 bool GetTransaction(const uint256& hash, CTransactionRef& tx, const Consensus::Params& params, uint256& hashBlock, const CBlockIndex* const blockIndex = nullptr);
176 bool ActivateBestChain(BlockValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>());
177 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
178 
180 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
181 
183 uint64_t CalculateCurrentUsage();
184 
188 void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune);
189 
191 void PruneBlockFilesManual(int nManualPruneHeight);
192 
195 bool AcceptToMemoryPool(CTxMemPool& pool, TxValidationState &state, const CTransactionRef &tx,
196  std::list<CTransactionRef>* plTxnReplaced,
197  bool bypass_limits, const CAmount nAbsurdFee, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
198 
201 
204 
207 
208 
210 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
211 
221 bool CheckFinalTx(const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
222 
227 
239 bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
240 
246 {
247 private:
250  unsigned int nIn;
251  unsigned int nFlags;
255 
256 public:
257  CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
258  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
259  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
260 
261  bool operator()();
262 
263  void swap(CScriptCheck &check) {
264  std::swap(ptxTo, check.ptxTo);
265  std::swap(m_tx_out, check.m_tx_out);
266  std::swap(nIn, check.nIn);
267  std::swap(nFlags, check.nFlags);
268  std::swap(cacheStore, check.cacheStore);
269  std::swap(error, check.error);
270  std::swap(txdata, check.txdata);
271  }
272 
273  ScriptError GetScriptError() const { return error; }
274 };
275 
278 
279 
281 bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams);
282 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams);
283 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start);
284 bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start);
285 
286 bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex* pindex);
287 
291 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
292 
294 bool TestBlockValidity(BlockValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
295 
298 bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params);
299 
301 int GetWitnessCommitmentIndex(const CBlock& block);
302 
304 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
305 
307 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
308 
310 class CVerifyDB {
311 public:
312  CVerifyDB();
313  ~CVerifyDB();
314  bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth);
315 };
316 
318 
320 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
321 
323 {
324  DISCONNECT_OK, // All good.
325  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
326  DISCONNECT_FAILED // Something else went wrong.
327 };
328 
329 class ConnectTrace;
330 
332 enum class FlushStateMode {
333  NONE,
334  IF_NEEDED,
335  PERIODIC,
336  ALWAYS
337 };
338 
340 {
341  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
342 };
343 
352 public:
353  BlockMap m_block_index GUARDED_BY(cs_main);
354 
373  std::set<CBlockIndex*> m_failed_blocks;
374 
379  std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
380 
389  bool LoadBlockIndex(
390  const Consensus::Params& consensus_params,
391  CBlockTreeDB& blocktree,
392  std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
393  EXCLUSIVE_LOCKS_REQUIRED(cs_main);
394 
396  void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
397 
398  CBlockIndex* AddToBlockIndex(const CBlockHeader& block) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
400  CBlockIndex* InsertBlockIndex(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
401 
406  bool AcceptBlockHeader(
407  const CBlockHeader& block,
408  BlockValidationState& state,
409  const CChainParams& chainparams,
410  CBlockIndex** ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
411 };
412 
422 class CoinsViews {
423 
424 public:
427  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
428 
430  CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main);
431 
434  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
435 
442  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
443 
445  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
446 };
447 
449 {
451  CRITICAL = 2,
453  LARGE = 1,
454  OK = 0
455 };
456 
471 class CChainState {
472 private:
473 
480  int32_t nBlockSequenceId = 1;
482  int32_t nBlockReverseSequenceId = -1;
484  arith_uint256 nLastPreciousChainwork = 0;
485 
491 
498  mutable std::atomic<bool> m_cached_finished_ibd{false};
499 
504 
506  std::unique_ptr<CoinsViews> m_coins_views;
507 
508 public:
509  explicit CChainState(BlockManager& blockman, uint256 from_snapshot_blockhash = uint256());
510 
517  void InitCoinsDB(
518  size_t cache_size_bytes,
519  bool in_memory,
520  bool should_wipe,
521  std::string leveldb_name = "chainstate");
522 
525  void InitCoinsCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
526 
529  bool CanFlushToDisk() EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
530  return m_coins_views && m_coins_views->m_cacheview;
531  }
532 
536 
542  const uint256 m_from_snapshot_blockhash{};
543 
549  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
550 
552  CCoinsViewCache& CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
553  {
554  assert(m_coins_views->m_cacheview);
555  return *m_coins_views->m_cacheview.get();
556  }
557 
559  CCoinsViewDB& CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
560  {
561  return m_coins_views->m_dbview;
562  }
563 
566  CCoinsViewErrorCatcher& CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
567  {
568  return m_coins_views->m_catcherview;
569  }
570 
572  void ResetCoinsViews() { m_coins_views.reset(); }
573 
585  bool FlushStateToDisk(
586  const CChainParams& chainparams,
587  BlockValidationState &state,
588  FlushStateMode mode,
589  int nManualPruneHeight = 0);
590 
592  void ForceFlushStateToDisk();
593 
596  void PruneAndFlush();
597 
612  bool ActivateBestChain(
613  BlockValidationState& state,
614  const CChainParams& chainparams,
615  std::shared_ptr<const CBlock> pblock) LOCKS_EXCLUDED(cs_main);
616 
617  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);
618 
619  // Block (dis)connection on a given view:
620  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
621  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
622  CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
623 
624  // Apply the effects of a block disconnection on the UTXO set.
625  bool DisconnectTip(BlockValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, ::mempool.cs);
626 
627  // Manual block validity manipulation:
628  bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
629  bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
631 
633  bool ReplayBlocks(const CChainParams& params);
634  bool RewindBlockIndex(const CChainParams& params) LOCKS_EXCLUDED(cs_main);
635  bool LoadGenesisBlock(const CChainParams& chainparams);
636 
637  void PruneBlockIndexCandidates();
638 
639  void UnloadBlockIndex();
640 
642  bool IsInitialBlockDownload() const;
643 
649  void CheckBlockIndex(const Consensus::Params& consensusParams);
650 
652  bool LoadChainTip(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
653 
657  CoinsCacheSizeState GetCoinsCacheSizeState(const CTxMemPool& tx_pool)
658  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
659 
660  CoinsCacheSizeState GetCoinsCacheSizeState(
661  const CTxMemPool& tx_pool,
662  size_t max_coins_cache_size_bytes,
663  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
664 
665  std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
666 
667 private:
668  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);
669  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);
670 
671  void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
672  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
673  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
674 
675  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
676 
678  void EraseBlockData(CBlockIndex* index) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
679 
681 };
682 
688 bool PreciousBlock(BlockValidationState& state, const CChainParams& params, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main);
689 
691 bool InvalidateBlock(BlockValidationState& state, const CChainParams& chainparams, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
692 
694 void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
695 
729 class ChainstateManager
730 {
731 private:
749  std::unique_ptr<CChainState> m_ibd_chainstate;
750 
762  std::unique_ptr<CChainState> m_snapshot_chainstate;
763 
775  CChainState* m_active_chainstate{nullptr};
776 
779  bool m_snapshot_validated{false};
780 
781  // For access to m_active_chainstate.
782  friend CChainState& ChainstateActive();
783  friend CChain& ChainActive();
784 
785 public:
788  BlockManager m_blockman GUARDED_BY(::cs_main);
789 
795  CChainState& InitializeChainstate(const uint256& snapshot_blockhash = uint256())
796  EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
797 
799  std::vector<CChainState*> GetAll();
800 
802  CChainState& ActiveChainstate() const;
803  CChain& ActiveChain() const { return ActiveChainstate().m_chain; }
804  int ActiveHeight() const { return ActiveChain().Height(); }
805  CBlockIndex* ActiveTip() const { return ActiveChain().Tip(); }
806 
807  BlockMap& BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
808  {
809  return m_blockman.m_block_index;
810  }
811 
812  bool IsSnapshotActive() const;
813 
814  Optional<uint256> SnapshotBlockhash() const;
815 
817  bool IsSnapshotValidated() const { return m_snapshot_validated; }
818 
821  bool IsBackgroundIBD(CChainState* chainstate) const;
822 
827  CChainState& ValidatedChainstate() const;
828 
829  CChain& ValidatedChain() const { return ValidatedChainstate().m_chain; }
830  CBlockIndex* ValidatedTip() const { return ValidatedChain().Tip(); }
831 
852  bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock) LOCKS_EXCLUDED(cs_main);
853 
865  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
866 
868  void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
869 
871  bool LoadBlockIndex(const CChainParams& chainparams) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
872 
874  void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
875 
877  void Reset();
878 };
879 
881 extern ChainstateManager g_chainman GUARDED_BY(::cs_main);
882 
885 
888 
890 extern std::unique_ptr<CBlockTreeDB> pblocktree;
891 
897 int GetSpendHeight(const CCoinsViewCache& inputs);
898 
900 
904 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params);
905 
908 
910 bool DumpMempool(const CTxMemPool& pool);
911 
913 bool LoadMempool(CTxMemPool& pool);
914 
916 inline bool IsBlockPruned(const CBlockIndex* pblockindex)
917 {
918  return (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0);
919 }
920 
921 #endif // BITCOIN_VALIDATION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:387
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:60
CTxMemPool mempool
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:210
size_t nCoinCacheUsage
Definition: validation.cpp:142
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:144
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:109
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:535
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
void swap(CScriptCheck &check)
Definition: validation.h:263
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:351
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:422
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:729
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:251
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:407
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:85
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:58
DisconnectResult
Definition: validation.h:322
unsigned int nHeight
CChain & ValidatedChain() const
Definition: validation.h:829
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:134
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:151
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:260
The coins cache is in immediate need of a flush.
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:572
CChainState stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:471
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:253
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:252
unsigned char * begin()
Definition: uint256.h:54
CTxOut m_tx_out
Definition: validation.h:248
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:258
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
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:490
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:69
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:79
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:559
Access to the block database (blocks/index/)
Definition: txdb.h:88
Abstract view on the open txout dataset.
Definition: coins.h:180
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.
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.
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)
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:817
FlushStateMode
Definition: validation.h:332
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:310
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:804
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:242
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: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:83
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:81
Definition: net.h:118
ChainstateManager g_chainman
Definition: validation.cpp:103
An output of a transaction.
Definition: transaction.h:120
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:506
Parameters that influence chain consensus.
Definition: params.h:45
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.
size_t operator()(const uint256 &hash) const
Definition: validation.h:105
static constexpr size_t MINIMUM_WITNESS_COMMITMENT
Minimum size of a witness commitment structure.
Definition: validation.h:98
256-bit unsigned big integer.
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:143
uint256 g_best_block
Definition: validation.cpp:133
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:245
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:373
int flags
Definition: bitcoin-tx.cpp:509
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: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:120
CoinsCacheSizeState
Definition: validation.h:448
const CTransaction * ptxTo
Definition: validation.h:249
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:74
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:53
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:443
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly=false)
Open a block file (blk?????.dat)
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:52
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:916
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:762
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:86
ChainstateManager g_chainman GUARDED_BY(::cs_main)
DEPRECATED! Please use node.chainman instead.
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:43
std::unique_ptr< CChainState > m_ibd_chainstate
The chainstate used under normal operation (i.e.
Definition: validation.h:749
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:146
CChainState &InitializeChainstate(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:799
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:549
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 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:29
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances...
Definition: validation.h:503
CBlockIndex * ValidatedTip() const
Definition: validation.h:830
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:174
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:552
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:181
unsigned int nIn
Definition: validation.h:250
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:379
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:77
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:251
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:118
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:236
full block available in blk*.dat
Definition: chain.h:121
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:96
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:350
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
VersionBitsCache versionbitscache
ScriptError GetScriptError() const
Definition: validation.h:273
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:200
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
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:478
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:166
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:803
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune)
Actually unlink the specified files.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:566
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:87
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:520
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:70
CBlockIndex * ActiveTip() const
Definition: validation.h:805
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:254
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:807