Bitcoin Core  24.1.0
P2P Digital Currency
validation.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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 <arith_uint256.h>
14 #include <attributes.h>
15 #include <chain.h>
16 #include <chainparams.h>
18 #include <consensus/amount.h>
19 #include <deploymentstatus.h>
20 #include <fs.h>
21 #include <node/blockstorage.h>
22 #include <policy/feerate.h>
23 #include <policy/packages.h>
24 #include <policy/policy.h>
25 #include <script/script_error.h>
26 #include <sync.h>
27 #include <txdb.h>
28 #include <txmempool.h> // For CTxMemPool::cs
29 #include <uint256.h>
30 #include <util/check.h>
31 #include <util/hasher.h>
32 #include <util/translation.h>
33 #include <versionbits.h>
34 
35 #include <atomic>
36 #include <map>
37 #include <memory>
38 #include <optional>
39 #include <set>
40 #include <stdint.h>
41 #include <string>
42 #include <thread>
43 #include <utility>
44 #include <vector>
45 
46 class Chainstate;
47 class CBlockTreeDB;
48 class CTxMemPool;
49 class ChainstateManager;
50 struct ChainTxData;
53 struct LockPoints;
54 struct AssumeutxoData;
55 namespace node {
56 class SnapshotMetadata;
57 } // namespace node
58 namespace Consensus {
59 struct Params;
60 } // namespace Consensus
61 
63 static const int MAX_SCRIPTCHECK_THREADS = 15;
65 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
66 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
67 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
68 static const bool DEFAULT_TXINDEX = false;
69 static constexpr bool DEFAULT_COINSTATSINDEX{false};
70 static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
72 static const int DEFAULT_STOPATHEIGHT = 0;
74 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
75 static const signed int DEFAULT_CHECKBLOCKS = 6;
76 static constexpr int DEFAULT_CHECKLEVEL{3};
77 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
78 // At 1MB per block, 288 blocks = 288MB.
79 // Add 15% for Undo data = 331MB
80 // Add 20% for Orphan block rate = 397MB
81 // We want the low water mark after pruning to be at least 397 MB and since we prune in
82 // full block file chunks, we need the high water mark which triggers the prune to be
83 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
84 // Setting the target to >= 550 MiB will make it likely we can respect the target.
85 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
86 
91  POST_INIT
92 };
93 
94 extern RecursiveMutex cs_main;
96 extern std::condition_variable g_best_block_cv;
98 extern uint256 g_best_block;
102 extern bool g_parallel_script_checks;
103 extern bool fCheckBlockIndex;
104 extern bool fCheckpointsEnabled;
106 extern int64_t nMaxTipAge;
107 
109 extern uint256 hashAssumeValid;
110 
113 
115 extern const std::vector<std::string> CHECKLEVEL_DOC;
116 
118 void StartScriptCheckWorkerThreads(int threads_num);
121 
122 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
123 
124 bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str{});
125 
127 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
128 
130 void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
131 
137  enum class ResultType {
138  VALID,
139  INVALID,
140  MEMPOOL_ENTRY,
142  };
145 
148 
149  // The following fields are only present when m_result_type = ResultType::VALID or MEMPOOL_ENTRY
151  const std::optional<std::list<CTransactionRef>> m_replaced_transactions;
153  const std::optional<int64_t> m_vsize;
155  const std::optional<CAmount> m_base_fees;
156 
157  // The following field is only present when m_result_type = ResultType::DIFFERENT_WITNESS
159  const std::optional<uint256> m_other_wtxid;
160 
162  return MempoolAcceptResult(state);
163  }
164 
165  static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns, int64_t vsize, CAmount fees) {
166  return MempoolAcceptResult(std::move(replaced_txns), vsize, fees);
167  }
168 
169  static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
170  return MempoolAcceptResult(vsize, fees);
171  }
172 
174  return MempoolAcceptResult(other_wtxid);
175  }
176 
177 // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
178 private:
181  : m_result_type(ResultType::INVALID), m_state(state) {
182  Assume(!state.IsValid()); // Can be invalid or error
183  }
184 
186  explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns, int64_t vsize, CAmount fees)
187  : m_result_type(ResultType::VALID),
188  m_replaced_transactions(std::move(replaced_txns)), m_vsize{vsize}, m_base_fees(fees) {}
189 
191  explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
192  : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
193 
195  explicit MempoolAcceptResult(const uint256& other_wtxid)
196  : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
197 };
198 
203 {
211  std::map<const uint256, const MempoolAcceptResult> m_tx_results;
215  std::optional<CFeeRate> m_package_feerate;
216 
218  std::map<const uint256, const MempoolAcceptResult>&& results)
219  : m_state{state}, m_tx_results(std::move(results)) {}
220 
222  std::map<const uint256, const MempoolAcceptResult>&& results)
223  : m_state{state}, m_tx_results(std::move(results)), m_package_feerate{feerate} {}
224 
226  explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
227  : m_tx_results{ {wtxid, result} } {}
228 };
229 
244  int64_t accept_time, bool bypass_limits, bool test_accept)
246 
256  const Package& txns, bool test_accept)
258 
259 /* Mempool validation helper functions */
260 
264 bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
265 
284  const CCoinsView& coins_view,
285  const CTransaction& tx,
286  LockPoints* lp = nullptr,
287  bool useExistingLockPoints = false);
288 
294 {
295 private:
298  unsigned int nIn;
299  unsigned int nFlags;
303 
304 public:
306  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
307  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
308 
309  bool operator()();
310 
311  void swap(CScriptCheck& check) noexcept
312  {
313  std::swap(ptxTo, check.ptxTo);
314  std::swap(m_tx_out, check.m_tx_out);
315  std::swap(nIn, check.nIn);
316  std::swap(nFlags, check.nFlags);
317  std::swap(cacheStore, check.cacheStore);
318  std::swap(error, check.error);
319  std::swap(txdata, check.txdata);
320  }
321 
322  ScriptError GetScriptError() const { return error; }
323 };
324 
326 [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
327 
331 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
332 
335  const CChainParams& chainparams,
336  Chainstate& chainstate,
337  const CBlock& block,
338  CBlockIndex* pindexPrev,
339  const std::function<NodeClock::time_point()>& adjusted_time_callback,
340  bool fCheckPOW = true,
341  bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
342 
344 bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
345 
347 arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader>& headers);
348 
350 class CVerifyDB {
351 public:
352  CVerifyDB();
353  ~CVerifyDB();
354  bool VerifyDB(
355  Chainstate& chainstate,
356  const Consensus::Params& consensus_params,
357  CCoinsView& coinsview,
358  int nCheckLevel,
359  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
360 };
361 
363 {
364  DISCONNECT_OK, // All good.
365  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
366  DISCONNECT_FAILED // Something else went wrong.
367 };
368 
369 class ConnectTrace;
370 
372 enum class FlushStateMode {
373  NONE,
374  IF_NEEDED,
375  PERIODIC,
376  ALWAYS
377 };
378 
388 class CoinsViews {
389 
390 public:
393  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
394 
397 
400  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
401 
408  CoinsViews(fs::path ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
409 
411  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
412 };
413 
415 {
417  CRITICAL = 2,
419  LARGE = 1,
420  OK = 0
421 };
422 
438 {
439 protected:
445  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
450 
457 
464  mutable std::atomic<bool> m_cached_finished_ibd{false};
465 
469 
471  std::unique_ptr<CoinsViews> m_coins_views;
472 
473 public:
477 
479  /* TODO: replace with m_chainman.GetParams() */
481 
486 
487  explicit Chainstate(
488  CTxMemPool* mempool,
489  node::BlockManager& blockman,
490  ChainstateManager& chainman,
491  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
492 
499  void InitCoinsDB(
500  size_t cache_size_bytes,
501  bool in_memory,
502  bool should_wipe,
503  fs::path leveldb_name = "chainstate");
504 
507  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
508 
511  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
512  {
514  return m_coins_views && m_coins_views->m_cacheview;
515  }
516 
520 
526  const std::optional<uint256> m_from_snapshot_blockhash;
527 
530  bool reliesOnAssumedValid() { return m_from_snapshot_blockhash.has_value(); }
531 
538  std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
539 
542  {
544  assert(m_coins_views->m_cacheview);
545  return *m_coins_views->m_cacheview.get();
546  }
547 
550  {
552  return m_coins_views->m_dbview;
553  }
554 
557  {
558  return m_mempool;
559  }
560 
564  {
566  return m_coins_views->m_catcherview;
567  }
568 
570  void ResetCoinsViews() { m_coins_views.reset(); }
571 
574 
577 
580  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
582 
609  void LoadExternalBlockFile(
610  FILE* fileIn,
611  FlatFilePos* dbp = nullptr,
612  std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr)
614 
626  bool FlushStateToDisk(
627  BlockValidationState& state,
628  FlushStateMode mode,
629  int nManualPruneHeight = 0);
630 
632  void ForceFlushStateToDisk();
633 
636  void PruneAndFlush();
637 
653  bool ActivateBestChain(
654  BlockValidationState& state,
655  std::shared_ptr<const CBlock> pblock = nullptr)
658 
659  bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
660 
661  // Block (dis)connection on a given view:
662  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
664  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
665  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
666 
667  // Apply the effects of a block disconnection on the UTXO set.
669 
670  // Manual block validity manipulation:
675  bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
678 
680  bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
683 
686 
688  bool ReplayBlocks();
689 
691  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
693  bool LoadGenesisBlock();
694 
696 
697  void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
698 
700  bool IsInitialBlockDownload() const;
701 
704 
710  void CheckBlockIndex();
711 
713  void LoadMempool(const fs::path& load_path, fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
714 
717 
721  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
722 
723  CoinsCacheSizeState GetCoinsCacheSizeState(
724  size_t max_coins_cache_size_bytes,
725  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
726 
728 
729 private:
730  bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
731  bool ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
732 
735  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
736 
738 
741 
744  {
745  return m_mempool ? &m_mempool->cs : nullptr;
746  }
747 
762  DisconnectedBlockTransactions& disconnectpool,
764 
766  void UpdateTip(const CBlockIndex* pindexNew)
768 
769  friend ChainstateManager;
770 };
771 
800 {
801 private:
817  std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
818 
828  std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
829 
839  Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
840 
843  bool m_snapshot_validated GUARDED_BY(::cs_main){false};
844 
845  CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
846 
848  [[nodiscard]] bool PopulateAndValidateSnapshot(
849  Chainstate& snapshot_chainstate,
850  AutoFile& coins_file,
851  const node::SnapshotMetadata& metadata);
852 
860  bool AcceptBlockHeader(
861  const CBlockHeader& block,
862  BlockValidationState& state,
863  CBlockIndex** ppindex,
864  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
865  friend Chainstate;
866 
868  std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
869 
870 public:
872 
873  explicit ChainstateManager(Options options) : m_options{std::move(options)}
874  {
876  }
877 
878  const CChainParams& GetParams() const { return m_options.chainparams; }
880 
893 
895  std::thread m_load_block;
899 
919  std::set<CBlockIndex*> m_failed_blocks;
920 
923 
927  //
931 
936  // constructor
939  Chainstate& InitializeChainstate(
940  CTxMemPool* mempool,
941  const std::optional<uint256>& snapshot_blockhash = std::nullopt)
943 
945  std::vector<Chainstate*> GetAll();
946 
960  [[nodiscard]] bool ActivateSnapshot(
961  AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
962 
964  Chainstate& ActiveChainstate() const;
968 
970  {
972  return m_blockman.m_block_index;
973  }
974 
979 
982  bool IsSnapshotActive() const;
983 
984  std::optional<uint256> SnapshotBlockhash() const;
985 
987  bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return m_snapshot_validated; }
988 
1013  bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1014 
1026  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1027 
1034  [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1036 
1039 
1042  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1043 
1045  void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1046 
1048  std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1049 
1054  void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
1055 
1056  ~ChainstateManager();
1057 };
1058 
1060 template<typename DEP>
1061 bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1062 {
1063  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1064 }
1065 
1066 template<typename DEP>
1067 bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1068 {
1069  return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1070 }
1071 
1072 template<typename DEP>
1073 bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1074 {
1075  return DeploymentEnabled(chainman.GetConsensus(), dep);
1076 }
1077 
1085 const AssumeutxoData* ExpectedAssumeutxo(const int height, const CChainParams& params);
1086 
1087 #endif // BITCOIN_VALIDATION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:414
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:541
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:65
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:898
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from. ...
Definition: validation.h:526
bool m_snapshot_validated GUARDED_BY(::cs_main)
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
Definition: validation.h:843
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:468
bool ReplayBlocks()
Replay blocks that aren&#39;t fully applied to the database.
bool PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
Definition: validation.h:1061
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1067
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:129
AssertLockHeld(pool.cs)
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
Definition: validation.h:743
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, 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) ...
const Options m_options
Definition: validation.h:894
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:88
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:538
CBlockIndex * m_best_header
Best header we&#39;ve seen so far (used for getheaders queries&#39; starting points).
Definition: validation.h:922
assert(!tx.IsCoinBase())
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
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:120
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:845
GlobalMutex g_best_block_mutex
Definition: validation.cpp:123
Valid, transaction was already in the mempool.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances...
Definition: validation.h:476
Bilingual messages:
Definition: translation.h:18
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
Definition: block.h:68
The cache is at >= 90% capacity.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:388
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:799
An in-memory indexed chain of blocks.
Definition: chain.h:422
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees)
Constructor for success case.
Definition: validation.h:186
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:151
unsigned int nFlags
Definition: validation.h:299
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:766
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:66
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:573
PackageMempoolAcceptResult(PackageValidationState state, std::map< const uint256, const MempoolAcceptResult > &&results)
Definition: validation.h:217
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:44
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:74
DisconnectResult
Definition: validation.h:362
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:471
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:965
unsigned int nHeight
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:126
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:76
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:137
int Height() const
Return the maximal height in the chain.
Definition: chain.h:468
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:59
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:211
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees)
Definition: validation.h:165
std::chrono::time_point< std::chrono::steady_clock > m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
Definition: validation.h:868
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn&#39;t already been seen, call CheckBlockHeader on it, ensure that it doesn&#39;t desce...
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, fs::path leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:160
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:839
The coins cache is in immediate need of a flush.
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
bool HasValidProofOfWork(const std::vector< CBlockHeader > &headers, const Consensus::Params &consensusParams)
Check with the proof of work on each blockheader matches the value in nBits.
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:449
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:226
std::optional< CFeeRate > m_package_feerate
Package feerate, defined as the aggregated modified fees divided by the total virtual size of all tra...
Definition: validation.h:215
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops. ...
Definition: validation.h:153
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:147
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:919
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:155
CoinsViews(fs::path 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...
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:69
bool ConnectTip(BlockValidationState &state, 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:301
void MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
Definition: validation.cpp:289
const ResultType m_result_type
Result type.
Definition: validation.h:144
void CheckBlockIndex()
Make various assertions about the state of the block index.
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
ChainstateManager(Options options)
Definition: validation.h:873
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1073
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument &#39;checklevel&#39;.
Definition: validation.cpp:96
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:519
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:300
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be final in the next block to be created.
Definition: validation.h:283
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:474
Bridge operations to C stdio.
Definition: fs.cpp:23
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
CTxOut m_tx_out
Definition: validation.h:296
Filesystem operations and types.
Definition: fs.h:20
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:570
Called by RandAddPeriodic()
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:306
bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
Transaction validation functions.
Definition: params.h:15
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:978
bool ProcessNewBlock(const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned...
bool IsValid() const
Definition: validation.h:121
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(bool AcceptBlock(const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, CBlockIndex **ppindex, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the best known block, and make it the tip of the block chain.
Definition: validation.h:659
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: fs.h:207
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:485
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain&#39;s tip.
int32_t nBlockSequenceId GUARDED_BY(::cs_main)
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
bool IsSnapshotActive() const
#define LIFETIMEBOUND
Definition: attributes.h:16
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:437
const CChainParams & m_params
Chain parameters for this chainstate.
Definition: validation.h:480
void swap(CScriptCheck &check) noexcept
Definition: validation.h:311
Access to the block database (blocks/index/)
Definition: txdb.h:78
const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block of this chain and a locator.
Definition: validation.cpp:134
Abstract view on the open txout dataset.
Definition: coins.h:156
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
Definition: validation.h:530
Validation result for package mempool acceptance.
Definition: validation.h:202
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins...
Definition: validation.h:664
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev) const
Produce the necessary coinbase commitment for a block (modifies the hash, don&#39;t call for mined blocks...
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied...
const std::function< NodeClock::time_point()> adjusted_time_callback
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:447
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we&#39;re running with -reindex...
FlushStateMode
Definition: validation.h:372
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:350
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
Holds various statistics on transactions within a chain.
Definition: chainparams.h:59
const PackageValidationState m_state
Definition: validation.h:204
static constexpr bool DEFAULT_COINSTATSINDEX
Definition: validation.h:69
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:72
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< const uint256, const MempoolAcceptResult > &&results)
Definition: validation.h:221
const Consensus::Params & GetConsensus() const
Definition: validation.h:879
void LoadMempool(const fs::path &load_path, fsbridge::FopenFn mockable_fopen_function=fsbridge::fopen)
Load the persisted mempool from disk.
bool ActivateBestChainStep(BlockValidationState &state, 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.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:967
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:81
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:549
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:132
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:563
bool operator()()
An output of a transaction.
Definition: transaction.h:156
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:892
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the tip of the chain with the most work in it, that isn&#39;t known to be invalid (it&#39;s however fa...
Parameters that influence chain consensus.
Definition: params.h:73
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:70
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
Chainstate &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:945
Validation result for a single transaction mempool acceptance.
Definition: validation.h:135
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:180
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
Definition: validation.h:169
#define Assume(val)
Assume is the identity function.
Definition: check.h:86
256-bit unsigned big integer.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
std::thread m_load_block
Definition: validation.h:895
const std::optional< uint256 > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness...
Definition: validation.h:159
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:926
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:80
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:969
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:125
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:293
Definition: init.h:25
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
std::condition_variable g_best_block_cv
Definition: validation.cpp:124
const CChainParams & GetParams() const
Definition: validation.h:878
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
256-bit opaque blob.
Definition: uint256.h:119
CoinsCacheSizeState
Definition: validation.h:414
const CTransaction * ptxTo
Definition: validation.h:297
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
Definition: validation.h:464
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:67
#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:431
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
Definition: validation.h:195
#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:121
bool ActivateSnapshot(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
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:151
const CChainParams & Params()
Return the currently selected parameters.
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:75
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:50
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:131
bool m_mempool cs
Definition: validation.h:668
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:439
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:966
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &params)
Return the expected assumeutxo value for a given height, if one exists.
unsigned int nIn
Definition: validation.h:298
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:576
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.
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:456
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:161
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:287
Different type to mark Mutex at global scope.
Definition: sync.h:141
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::optional< uint256 > SnapshotBlockhash() const
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:82
Chainstate & ActiveChainstate() const
The most-work chain.
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:930
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:212
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:85
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
Definition: validation.h:191
bool fCheckpointsEnabled
Definition: validation.cpp:128
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:342
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
Definition: validation.h:685
ScriptError GetScriptError() const
Definition: validation.h:322
void ReportHeadersPresync(const arith_uint256 &work, int64_t height, int64_t timestamp)
This is used by net_processing to report pre-synchronization progress of headers, as headers are not ...
static const bool DEFAULT_TXINDEX
Definition: validation.h:68
std::unique_ptr< Chainstate > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
Definition: validation.h:173
CTxMemPool * GetMempool()
Definition: validation.h:556
bool fCheckBlockIndex
Definition: validation.cpp:127
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:987
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:521
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:63
#define Assert(val)
Identity function.
Definition: check.h:74
LockPoints lp
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:15
MempoolAcceptResult ProcessTransaction(const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the memory pool.
PrecomputedTransactionData * txdata
Definition: validation.h:302