Bitcoin Core  24.99.0
P2P Digital Currency
validation.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 <kernel/cs_main.h> // IWYU pragma: export
22 #include <node/blockstorage.h>
23 #include <policy/feerate.h>
24 #include <policy/packages.h>
25 #include <policy/policy.h>
26 #include <script/script_error.h>
27 #include <sync.h>
28 #include <txdb.h>
29 #include <txmempool.h> // For CTxMemPool::cs
30 #include <uint256.h>
31 #include <util/check.h>
32 #include <util/hasher.h>
33 #include <util/translation.h>
34 #include <versionbits.h>
35 
36 #include <atomic>
37 #include <map>
38 #include <memory>
39 #include <optional>
40 #include <set>
41 #include <stdint.h>
42 #include <string>
43 #include <thread>
44 #include <utility>
45 #include <vector>
46 
47 class Chainstate;
48 class CBlockTreeDB;
49 class CTxMemPool;
50 class ChainstateManager;
51 struct ChainTxData;
54 struct LockPoints;
55 struct AssumeutxoData;
56 namespace node {
57 class SnapshotMetadata;
58 } // namespace node
59 namespace Consensus {
60 struct Params;
61 } // namespace Consensus
62 
64 static const int MAX_SCRIPTCHECK_THREADS = 15;
66 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
68 static const int DEFAULT_STOPATHEIGHT = 0;
70 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
71 static const signed int DEFAULT_CHECKBLOCKS = 6;
72 static constexpr int DEFAULT_CHECKLEVEL{3};
73 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
74 // At 1MB per block, 288 blocks = 288MB.
75 // Add 15% for Undo data = 331MB
76 // Add 20% for Orphan block rate = 397MB
77 // We want the low water mark after pruning to be at least 397 MB and since we prune in
78 // full block file chunks, we need the high water mark which triggers the prune to be
79 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
80 // Setting the target to >= 550 MiB will make it likely we can respect the target.
81 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
82 
87  POST_INIT
88 };
89 
91 extern std::condition_variable g_best_block_cv;
93 extern uint256 g_best_block;
94 
96 extern const std::vector<std::string> CHECKLEVEL_DOC;
97 
99 void StartScriptCheckWorkerThreads(int threads_num);
102 
103 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
104 
105 bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str{});
106 
108 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
109 
111 void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
112 
118  enum class ResultType {
119  VALID,
120  INVALID,
121  MEMPOOL_ENTRY,
123  };
126 
129 
130  // The following fields are only present when m_result_type = ResultType::VALID or MEMPOOL_ENTRY
132  const std::optional<std::list<CTransactionRef>> m_replaced_transactions;
134  const std::optional<int64_t> m_vsize;
136  const std::optional<CAmount> m_base_fees;
143  const std::optional<CFeeRate> m_effective_feerate;
149  const std::optional<std::vector<uint256>> m_wtxids_fee_calculations;
150 
151  // The following field is only present when m_result_type = ResultType::DIFFERENT_WITNESS
153  const std::optional<uint256> m_other_wtxid;
154 
156  return MempoolAcceptResult(state);
157  }
158 
159  static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
160  int64_t vsize,
161  CAmount fees,
162  CFeeRate effective_feerate,
163  const std::vector<uint256>& wtxids_fee_calculations) {
164  return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
165  effective_feerate, wtxids_fee_calculations);
166  }
167 
168  static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
169  return MempoolAcceptResult(vsize, fees);
170  }
171 
173  return MempoolAcceptResult(other_wtxid);
174  }
175 
176 // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
177 private:
180  : m_result_type(ResultType::INVALID), m_state(state) {
181  Assume(!state.IsValid()); // Can be invalid or error
182  }
183 
185  explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
186  int64_t vsize,
187  CAmount fees,
188  CFeeRate effective_feerate,
189  const std::vector<uint256>& wtxids_fee_calculations)
190  : m_result_type(ResultType::VALID),
191  m_replaced_transactions(std::move(replaced_txns)),
192  m_vsize{vsize},
193  m_base_fees(fees),
194  m_effective_feerate(effective_feerate),
195  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
196 
198  explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
199  : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
200 
202  explicit MempoolAcceptResult(const uint256& other_wtxid)
203  : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
204 };
205 
210 {
218  std::map<const uint256, const MempoolAcceptResult> m_tx_results;
219 
221  std::map<const uint256, const MempoolAcceptResult>&& results)
222  : m_state{state}, m_tx_results(std::move(results)) {}
223 
225  std::map<const uint256, const MempoolAcceptResult>&& results)
226  : m_state{state}, m_tx_results(std::move(results)) {}
227 
229  explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
230  : m_tx_results{ {wtxid, result} } {}
231 };
232 
247  int64_t accept_time, bool bypass_limits, bool test_accept)
249 
259  const Package& txns, bool test_accept)
261 
262 /* Mempool validation helper functions */
263 
267 bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
268 
287  const CCoinsView& coins_view,
288  const CTransaction& tx,
289  LockPoints* lp = nullptr,
290  bool useExistingLockPoints = false);
291 
297 {
298 private:
301  unsigned int nIn;
302  unsigned int nFlags;
306 
307 public:
309  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
310  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
311 
312  bool operator()();
313 
314  void swap(CScriptCheck& check) noexcept
315  {
316  std::swap(ptxTo, check.ptxTo);
317  std::swap(m_tx_out, check.m_tx_out);
318  std::swap(nIn, check.nIn);
319  std::swap(nFlags, check.nFlags);
320  std::swap(cacheStore, check.cacheStore);
321  std::swap(error, check.error);
322  std::swap(txdata, check.txdata);
323  }
324 
325  ScriptError GetScriptError() const { return error; }
326 };
327 
329 [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
330 
334 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
335 
338  const CChainParams& chainparams,
339  Chainstate& chainstate,
340  const CBlock& block,
341  CBlockIndex* pindexPrev,
342  const std::function<NodeClock::time_point()>& adjusted_time_callback,
343  bool fCheckPOW = true,
344  bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
345 
347 bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
348 
350 arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader>& headers);
351 
353 class CVerifyDB {
354 public:
355  CVerifyDB();
356  ~CVerifyDB();
357  bool VerifyDB(
358  Chainstate& chainstate,
359  const Consensus::Params& consensus_params,
360  CCoinsView& coinsview,
361  int nCheckLevel,
362  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
363 };
364 
366 {
367  DISCONNECT_OK, // All good.
368  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
369  DISCONNECT_FAILED // Something else went wrong.
370 };
371 
372 class ConnectTrace;
373 
375 enum class FlushStateMode {
376  NONE,
377  IF_NEEDED,
378  PERIODIC,
379  ALWAYS
380 };
381 
391 class CoinsViews {
392 
393 public:
397 
400 
403  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
404 
411  CoinsViews(fs::path ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
412 
414  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
415 };
416 
418 {
420  CRITICAL = 2,
422  LARGE = 1,
423  OK = 0
424 };
425 
441 {
442 protected:
448  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
450  int32_t nBlockReverseSequenceId = -1;
452  arith_uint256 nLastPreciousChainwork = 0;
453 
460 
467  mutable std::atomic<bool> m_cached_finished_ibd{false};
468 
472 
474  std::unique_ptr<CoinsViews> m_coins_views;
475 
476 public:
480 
485 
486  explicit Chainstate(
487  CTxMemPool* mempool,
488  node::BlockManager& blockman,
489  ChainstateManager& chainman,
490  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
491 
498  void InitCoinsDB(
499  size_t cache_size_bytes,
500  bool in_memory,
501  bool should_wipe,
502  fs::path leveldb_name = "chainstate");
503 
506  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
507 
510  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
511  {
513  return m_coins_views && m_coins_views->m_cacheview;
514  }
515 
519 
525  const std::optional<uint256> m_from_snapshot_blockhash;
526 
529  bool reliesOnAssumedValid() { return m_from_snapshot_blockhash.has_value(); }
530 
537  std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
538 
541  {
543  assert(m_coins_views->m_cacheview);
544  return *m_coins_views->m_cacheview.get();
545  }
546 
549  {
551  return m_coins_views->m_dbview;
552  }
553 
556  {
557  return m_mempool;
558  }
559 
563  {
565  return m_coins_views->m_catcherview;
566  }
567 
569  void ResetCoinsViews() { m_coins_views.reset(); }
570 
572  size_t m_coinsdb_cache_size_bytes{0};
573 
575  size_t m_coinstip_cache_size_bytes{0};
576 
579  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
581 
609  FILE* fileIn,
610  FlatFilePos* dbp = nullptr,
611  std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr)
612  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex);
613 
625  bool FlushStateToDisk(
626  BlockValidationState& state,
627  FlushStateMode mode,
628  int nManualPruneHeight = 0);
629 
631  void ForceFlushStateToDisk();
632 
635  void PruneAndFlush();
636 
652  bool ActivateBestChain(
653  BlockValidationState& state,
654  std::shared_ptr<const CBlock> pblock = nullptr)
655  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
657 
658  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);
659 
660  // Block (dis)connection on a given view:
661  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
663  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
664  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
665 
666  // Apply the effects of a block disconnection on the UTXO set.
667  bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
668 
669  // Manual block validity manipulation:
674  bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
675  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
677 
679  bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
680  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
682 
684  void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
685 
687  bool ReplayBlocks();
688 
690  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
692  bool LoadGenesisBlock();
693 
694  void PruneBlockIndexCandidates();
695 
696  void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
697 
699  bool IsInitialBlockDownload() const;
700 
702  const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
703 
709  void CheckBlockIndex();
710 
712  void LoadMempool(const fs::path& load_path, fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
713 
715  bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
716 
720  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
721 
722  CoinsCacheSizeState GetCoinsCacheSizeState(
723  size_t max_coins_cache_size_bytes,
724  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
725 
727 
728 private:
729  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);
730  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);
731 
732  void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
733  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
734  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
735 
736  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
737 
738  void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
739  void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
740 
742  RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
743  {
744  return m_mempool ? &m_mempool->cs : nullptr;
745  }
746 
760  void MaybeUpdateMempoolForReorg(
761  DisconnectedBlockTransactions& disconnectpool,
762  bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
763 
765  void UpdateTip(const CBlockIndex* pindexNew)
767 
768  std::chrono::microseconds m_last_write{0};
769  std::chrono::microseconds m_last_flush{0};
770 
772 };
773 
802 {
803 private:
819  std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
820 
830  std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
831 
841  Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
842 
845  bool m_snapshot_validated GUARDED_BY(::cs_main){false};
846 
847  CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
848 
850  [[nodiscard]] bool PopulateAndValidateSnapshot(
851  Chainstate& snapshot_chainstate,
852  AutoFile& coins_file,
853  const node::SnapshotMetadata& metadata);
854 
862  bool AcceptBlockHeader(
863  const CBlockHeader& block,
864  BlockValidationState& state,
865  CBlockIndex** ppindex,
866  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
867  friend Chainstate;
868 
870  std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
871 
872 public:
874 
875  explicit ChainstateManager(Options options);
876 
877  const CChainParams& GetParams() const { return m_options.chainparams; }
878  const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
879  bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); }
880  const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
881  const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
882 
895 
897  std::thread m_load_block;
901 
921  std::set<CBlockIndex*> m_failed_blocks;
922 
924  CBlockIndex* m_best_header = nullptr;
925 
928  int64_t m_total_coinstip_cache{0};
929  //
932  int64_t m_total_coinsdb_cache{0};
933 
937  // constructor
938  Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
939 
941  std::vector<Chainstate*> GetAll();
942 
956  [[nodiscard]] bool ActivateSnapshot(
957  AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
958 
960  Chainstate& ActiveChainstate() const;
961  CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
962  int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
963  CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
964 
966  {
968  return m_blockman.m_block_index;
969  }
970 
975 
978  bool IsSnapshotActive() const;
979 
980  std::optional<uint256> SnapshotBlockhash() const;
981 
983  bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return m_snapshot_validated; }
984 
1009  bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1010 
1022  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1023 
1030  [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1032 
1034  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1035 
1038  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1039 
1041  void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1042 
1044  std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1045 
1050  void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
1051 
1054  bool DetectSnapshotChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1055 
1056  void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1057 
1060  Chainstate& ActivateExistingSnapshot(CTxMemPool* mempool, uint256 base_blockhash)
1062 
1064 };
1065 
1067 template<typename DEP>
1068 bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1069 {
1070  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1071 }
1072 
1073 template<typename DEP>
1074 bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1075 {
1076  return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1077 }
1078 
1079 template<typename DEP>
1080 bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1081 {
1082  return DeploymentEnabled(chainman.GetConsensus(), dep);
1083 }
1084 
1092 const AssumeutxoData* ExpectedAssumeutxo(const int height, const CChainParams& params);
1093 
1095 bool IsBIP30Repeat(const CBlockIndex& block_index);
1096 
1098 bool IsBIP30Unspendable(const CBlockIndex& block_index);
1099 
1100 #endif // BITCOIN_VALIDATION_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:73
#define Assume(val)
Assume is the identity function.
Definition: check.h:85
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:496
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
Definition: block.h:69
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
Access to the block database (blocks/index/)
Definition: txdb.h:81
An in-memory indexed chain of blocks.
Definition: chain.h:436
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:50
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:343
Abstract view on the open txout dataset.
Definition: coins.h:157
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:297
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:325
PrecomputedTransactionData * txdata
Definition: validation.h:305
CTxOut m_tx_out
Definition: validation.h:299
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:309
void swap(CScriptCheck &check) noexcept
Definition: validation.h:314
bool cacheStore
Definition: validation.h:303
ScriptError error
Definition: validation.h:304
unsigned int nFlags
Definition: validation.h:302
const CTransaction * ptxTo
Definition: validation.h:300
unsigned int nIn
Definition: validation.h:301
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:316
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:405
An output of a transaction.
Definition: transaction.h:158
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:353
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:441
CTxMemPool * GetMempool()
Definition: validation.h:555
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:459
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:518
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:548
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:525
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:471
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
Definition: validation.h:529
friend ChainstateManager
Definition: validation.h:771
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:537
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:484
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:474
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:569
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:540
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:562
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:479
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...
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:802
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:961
std::unique_ptr< Chainstate > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:841
const CChainParams & GetParams() const
Definition: validation.h:877
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:880
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:845
bool ShouldCheckBlockIndex() const
Definition: validation.h:879
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:965
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:983
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:894
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:962
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:974
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:963
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:870
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:847
const Options m_options
Definition: validation.h:896
const uint256 & AssumedValidBlock() const
Definition: validation.h:881
std::thread m_load_block
Definition: validation.h:897
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:941
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:921
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
const Consensus::Params & GetConsensus() const
Definition: validation.h:878
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:900
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:391
std::unique_ptr< CCoinsViewCache > m_cacheview GUARDED_BY(cs_main)
This is the top layer of the cache hierarchy - it keeps as many coins in memory as can fit per the db...
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...
CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main)
This view wraps access to the leveldb instance and handles read errors gracefully.
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
Different type to mark Mutex at global scope.
Definition: sync.h:141
bool IsValid() const
Definition: validation.h:121
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:81
256-bit unsigned big integer.
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:81
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:22
256-bit opaque blob.
Definition: uint256.h:119
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
unsigned int nHeight
LockPoints lp
static void pool cs
Transaction validation functions.
Filesystem operations and types.
Definition: fs.h:20
Bridge operations to C stdio.
Definition: fs.cpp:23
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: fs.h:207
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, FopenFn mockable_fopen_function)
Definition: init.h:25
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:58
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:44
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
@ PERIODIC
Called by RandAddPeriodic()
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
Definition: script_error.h:14
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:121
Holds various statistics on transactions within a chain.
Definition: chainparams.h:59
Parameters that influence chain consensus.
Definition: params.h:73
Validation result for a single transaction mempool acceptance.
Definition: validation.h:116
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
Definition: validation.h:134
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< uint256 > &wtxids_fee_calculations)
Definition: validation.h:159
const ResultType m_result_type
Result type.
Definition: validation.h:125
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
Definition: validation.h:198
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:136
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:132
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:179
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:128
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
Definition: validation.h:172
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:118
@ DIFFERENT_WITNESS
Valid, transaction was already in the mempool.
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:155
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:143
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:153
const std::optional< std::vector< uint256 > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
Definition: validation.h:149
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< uint256 > &wtxids_fee_calculations)
Constructor for success case.
Definition: validation.h:185
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
Definition: validation.h:168
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
Definition: validation.h:202
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:210
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:218
PackageMempoolAcceptResult(PackageValidationState state, std::map< const uint256, const MempoolAcceptResult > &&results)
Definition: validation.h:220
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< const uint256, const MempoolAcceptResult > &&results)
Definition: validation.h:224
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:229
const PackageValidationState m_state
Definition: validation.h:211
Bilingual messages:
Definition: translation.h:18
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:138
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
GlobalMutex g_best_block_mutex
Definition: validation.cpp:108
std::condition_variable g_best_block_cv
Definition: validation.cpp:109
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:72
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.
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:81
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
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:286
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
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: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.
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.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
Definition: validation.h:1068
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:64
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &params)
Return the expected assumeutxo value for a given height, if one exists.
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1080
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:84
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:66
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
bool IsBIP30Unspendable(const CBlockIndex &block_index)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
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.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:93
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CoinsCacheSizeState
Definition: validation.h:418
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1074
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
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)
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:71
FlushStateMode
Definition: validation.h:375
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:110
DisconnectResult
Definition: validation.h:366
@ DISCONNECT_FAILED
Definition: validation.h:369
@ DISCONNECT_UNCLEAN
Definition: validation.h:368
@ DISCONNECT_OK
Definition: validation.h:367
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:68