Bitcoin Core  31.0.0
P2P Digital Currency
validation.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-present 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 #include <arith_uint256.h>
10 #include <attributes.h>
11 #include <chain.h>
12 #include <checkqueue.h>
13 #include <coins.h>
14 #include <consensus/amount.h>
15 #include <cuckoocache.h>
16 #include <deploymentstatus.h>
17 #include <kernel/chain.h>
18 #include <kernel/chainparams.h>
20 #include <kernel/cs_main.h> // IWYU pragma: export
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 <script/sigcache.h>
27 #include <script/verify_flags.h>
28 #include <sync.h>
29 #include <txdb.h>
30 #include <txmempool.h>
31 #include <uint256.h>
32 #include <util/byte_units.h>
33 #include <util/check.h>
34 #include <util/fs.h>
35 #include <util/hasher.h>
36 #include <util/result.h>
37 #include <util/time.h>
38 #include <util/translation.h>
39 #include <versionbits.h>
40 
41 #include <algorithm>
42 #include <atomic>
43 #include <cstdint>
44 #include <map>
45 #include <memory>
46 #include <optional>
47 #include <set>
48 #include <span>
49 #include <string>
50 #include <type_traits>
51 #include <utility>
52 #include <vector>
53 
54 class Chainstate;
55 class CTxMemPool;
56 class ChainstateManager;
57 struct ChainTxData;
60 struct LockPoints;
61 struct AssumeutxoData;
62 namespace kernel {
63 struct ChainstateRole;
64 } // namespace kernel
65 namespace node {
66 class SnapshotMetadata;
67 } // namespace node
68 namespace Consensus {
69 struct Params;
70 } // namespace Consensus
71 namespace util {
72 class SignalInterrupt;
73 } // namespace util
74 
76 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
77 static const signed int DEFAULT_CHECKBLOCKS = 6;
78 static constexpr int DEFAULT_CHECKLEVEL{3};
79 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
80 // At 1MB per block, 288 blocks = 288MB.
81 // Add 15% for Undo data = 331MB
82 // Add 20% for Orphan block rate = 397MB
83 // We want the low water mark after pruning to be at least 397 MB and since we prune in
84 // full block file chunks, we need the high water mark which triggers the prune to be
85 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
86 // Setting the target to >= 550 MiB will make it likely we can respect the target.
87 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
88 
90 static constexpr int MAX_SCRIPTCHECK_THREADS{15};
91 
96  POST_INIT
97 };
98 
100 extern const std::vector<std::string> CHECKLEVEL_DOC;
101 
102 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
103 
104 bool FatalError(kernel::Notifications& notifications, BlockValidationState& state, const bilingual_str& message);
105 
107 void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
108 
133  enum class ResultType {
134  VALID,
135  INVALID,
136  MEMPOOL_ENTRY,
138  };
141 
144 
146  const std::list<CTransactionRef> m_replaced_transactions;
148  const std::optional<int64_t> m_vsize;
150  const std::optional<CAmount> m_base_fees;
156  const std::optional<CFeeRate> m_effective_feerate;
162  const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations;
163 
165  const std::optional<Wtxid> m_other_wtxid;
166 
168  return MempoolAcceptResult(state);
169  }
170 
172  CFeeRate effective_feerate,
173  const std::vector<Wtxid>& wtxids_fee_calculations) {
174  return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations);
175  }
176 
177  static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
178  int64_t vsize,
179  CAmount fees,
180  CFeeRate effective_feerate,
181  const std::vector<Wtxid>& wtxids_fee_calculations) {
182  return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
183  effective_feerate, wtxids_fee_calculations);
184  }
185 
186  static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
187  return MempoolAcceptResult(vsize, fees);
188  }
189 
191  return MempoolAcceptResult(other_wtxid);
192  }
193 
194 // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
195 private:
198  : m_result_type(ResultType::INVALID), m_state(state) {
199  Assume(!state.IsValid()); // Can be invalid or error
200  }
201 
203  explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
204  int64_t vsize,
205  CAmount fees,
206  CFeeRate effective_feerate,
207  const std::vector<Wtxid>& wtxids_fee_calculations)
208  : m_result_type(ResultType::VALID),
209  m_replaced_transactions(std::move(replaced_txns)),
210  m_vsize{vsize},
211  m_base_fees(fees),
212  m_effective_feerate(effective_feerate),
213  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
214 
217  CFeeRate effective_feerate,
218  const std::vector<Wtxid>& wtxids_fee_calculations)
219  : m_result_type(ResultType::INVALID),
220  m_state(state),
221  m_effective_feerate(effective_feerate),
222  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
223 
225  explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
226  : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
227 
229  explicit MempoolAcceptResult(const Wtxid& other_wtxid)
230  : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
231 };
232 
237 {
245  std::map<Wtxid, MempoolAcceptResult> m_tx_results;
246 
248  std::map<Wtxid, MempoolAcceptResult>&& results)
249  : m_state{state}, m_tx_results(std::move(results)) {}
250 
252  std::map<Wtxid, MempoolAcceptResult>&& results)
253  : m_state{state}, m_tx_results(std::move(results)) {}
254 
257  : m_tx_results{ {wtxid, result} } {}
258 };
259 
275  int64_t accept_time, bool bypass_limits, bool test_accept)
277 
289  const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
291 
292 /* Mempool validation helper functions */
293 
297 bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
298 
317 std::optional<LockPoints> CalculateLockPointsAtTip(
318  CBlockIndex* tip,
319  const CCoinsView& coins_view,
320  const CTransaction& tx);
321 
332  const LockPoints& lock_points);
333 
339 {
340 private:
343  unsigned int nIn;
348 
349 public:
350  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, SignatureCache& signature_cache, unsigned int nInIn, script_verify_flags flags, bool cacheIn, PrecomputedTransactionData* txdataIn) :
351  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), m_flags(flags), cacheStore(cacheIn), txdata(txdataIn), m_signature_cache(&signature_cache) { }
352 
353  CScriptCheck(const CScriptCheck&) = delete;
354  CScriptCheck& operator=(const CScriptCheck&) = delete;
355  CScriptCheck(CScriptCheck&&) = default;
356  CScriptCheck& operator=(CScriptCheck&&) = default;
357 
358  std::optional<std::pair<ScriptError, std::string>> operator()();
359 };
360 
361 // CScriptCheck is used a lot in std::vector, make sure that's efficient
362 static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
363 static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
364 static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
365 
371 {
372 private:
375 
376 public:
379 
380  ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes);
381 
382  ValidationCache(const ValidationCache&) = delete;
383  ValidationCache& operator=(const ValidationCache&) = delete;
384 
387 };
388 
392 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
393 
412  Chainstate& chainstate,
413  const CBlock& block,
414  bool check_pow,
415  bool check_merkle_root) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
416 
418 bool HasValidProofOfWork(std::span<const CBlockHeader> headers, const Consensus::Params& consensusParams);
419 
421 bool IsBlockMutated(const CBlock& block, bool check_witness_root);
422 
424 arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers);
425 
426 enum class VerifyDBResult {
427  SUCCESS,
429  INTERRUPTED,
432 };
433 
436 {
437 private:
439 
440 public:
441  explicit CVerifyDB(kernel::Notifications& notifications);
442  ~CVerifyDB();
443  [[nodiscard]] VerifyDBResult VerifyDB(
444  Chainstate& chainstate,
445  const Consensus::Params& consensus_params,
446  CCoinsView& coinsview,
447  int nCheckLevel,
448  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
449 };
450 
452 {
453  DISCONNECT_OK, // All good.
454  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
455  DISCONNECT_FAILED // Something else went wrong.
456 };
457 
458 class ConnectTrace;
459 
461 inline constexpr std::array FlushStateModeNames{"NONE", "IF_NEEDED", "PERIODIC", "FORCE_FLUSH", "FORCE_SYNC"};
462 enum class FlushStateMode: uint8_t {
463  NONE,
464  IF_NEEDED,
465  PERIODIC,
466  FORCE_FLUSH,
467  FORCE_SYNC,
468 };
469 
479 class CoinsViews {
480 
481 public:
484  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
485 
488 
491  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
492 
495  std::unique_ptr<CoinsViewOverlay> m_connect_block_view GUARDED_BY(cs_main);
496 
503  CoinsViews(DBParams db_params, CoinsViewOptions options);
504 
506  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
507 };
508 
510 {
512  CRITICAL = 2,
514  LARGE = 1,
515  OK = 0
516 };
517 
518 constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept
519 {
520  // No periodic flush needed if at least this much space is free
521  constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES{int64_t(10_MiB)};
522  return std::max((total_space * 9) / 10,
523  total_space - MAX_BLOCK_COINSDB_USAGE_BYTES);
524 }
525 
527 enum class Assumeutxo {
529  VALIDATED,
531  UNVALIDATED,
533  INVALID,
534 };
535 
551 {
552 protected:
559 
563 
565  std::unique_ptr<CoinsViews> m_coins_views;
566 
568  mutable const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};
569 
571  mutable const CBlockIndex* m_cached_target_block GUARDED_BY(::cs_main){nullptr};
572 
573  std::optional<const char*> m_last_script_check_reason_logged GUARDED_BY(::cs_main){};
574 
575 public:
579 
584 
585  explicit Chainstate(
586  CTxMemPool* mempool,
587  node::BlockManager& blockman,
588  ChainstateManager& chainman,
589  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
590 
592  fs::path StoragePath() const;
593 
599 
606  void InitCoinsDB(
607  size_t cache_size_bytes,
608  bool in_memory,
609  bool should_wipe);
610 
613  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
614 
617  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
618  {
620  return m_coins_views && m_coins_views->m_cacheview;
621  }
622 
626 
630  Assumeutxo m_assumeutxo GUARDED_BY(::cs_main);
631 
637  const std::optional<uint256> m_from_snapshot_blockhash;
638 
643  std::optional<uint256> m_target_blockhash GUARDED_BY(::cs_main);
644 
647  std::optional<AssumeutxoHash> m_target_utxohash GUARDED_BY(::cs_main);
648 
654  const CBlockIndex* SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
655 
659  const CBlockIndex* TargetBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
663  void SetTargetBlock(CBlockIndex* block) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
666  void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
667 
670  {
671  const CBlockIndex* target_block{TargetBlock()};
672  assert(!target_block || target_block->GetAncestor(m_chain.Height()) == m_chain.Tip());
673  return target_block && target_block == m_chain.Tip();
674  }
675 
683  std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
684 
687  {
690  return *Assert(m_coins_views->m_cacheview);
691  }
692 
695  {
697  return Assert(m_coins_views)->m_dbview;
698  }
699 
702  {
703  return m_mempool;
704  }
705 
709  {
711  return Assert(m_coins_views)->m_catcherview;
712  }
713 
715  void ResetCoinsViews() { m_coins_views.reset(); }
716 
719 
722 
725  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
727 
739  bool FlushStateToDisk(
740  BlockValidationState& state,
741  FlushStateMode mode,
742  int nManualPruneHeight = 0);
743 
745  void ForceFlushStateToDisk(bool wipe_cache = true);
746 
749  void PruneAndFlush();
750 
772  bool ActivateBestChain(
773  BlockValidationState& state,
774  std::shared_ptr<const CBlock> pblock = nullptr)
777 
778  // Block (dis)connection on a given view:
779  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
781  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
782  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
783 
784  // Apply the effects of a block disconnection on the UTXO set.
786 
787  // Manual block validity manipulation:
792  bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
795 
797  bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
800 
802  void SetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
803 
806 
808  bool ReplayBlocks();
809 
811  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
813  bool LoadGenesisBlock();
814 
817 
819 
820  void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
821 
823  void PopulateBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
824 
826  const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
827 
830 
834  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
835 
836  CoinsCacheSizeState GetCoinsCacheSizeState(
837  size_t max_coins_cache_size_bytes,
838  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
839 
841 
843  RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
844  {
845  return m_mempool ? &m_mempool->cs : nullptr;
846  }
847 
851  std::pair<int, int> GetPruneRange(int last_height_can_prune) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
852 
853 protected:
854  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);
855  bool ConnectTip(
856  BlockValidationState& state,
857  CBlockIndex* pindexNew,
858  std::shared_ptr<const CBlock> block_to_connect,
859  ConnectTrace& connectTrace,
861 
864 
866 
869 
884  DisconnectedBlockTransactions& disconnectpool,
886 
888  void UpdateTip(const CBlockIndex* pindexNew)
890 
891  NodeClock::time_point m_next_write{NodeClock::time_point::max()};
892 
897  [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
898 
899  friend ChainstateManager;
900 };
901 
903  SUCCESS,
904  SKIPPED,
905 
906  // Expected assumeutxo configuration data is not found for the height of the
907  // base block.
909 
910  // Failed to generate UTXO statistics (to check UTXO set hash) for the
911  // validated chainstate.
912  STATS_FAILED,
913 
914  // The UTXO set hash of the validated chainstate does not match the one
915  // expected by assumeutxo chainparams.
917 };
918 
940 {
941 private:
942 
944  CBlockIndex* m_last_notified_header GUARDED_BY(GetMutex()){nullptr};
945 
946  bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex());
947 
955  [[nodiscard]] util::Result<void> PopulateAndValidateSnapshot(
956  Chainstate& snapshot_chainstate,
957  AutoFile& coins_file,
958  const node::SnapshotMetadata& metadata);
959 
967  bool AcceptBlockHeader(
968  const CBlockHeader& block,
969  BlockValidationState& state,
970  CBlockIndex** ppindex,
971  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
972  friend Chainstate;
973 
975  MockableSteadyClock::time_point m_last_presync_update GUARDED_BY(GetMutex()){};
976 
978  CCheckQueue<CScriptCheck> m_script_check_queue;
979 
982  SteadyClock::duration GUARDED_BY(::cs_main) time_check{};
983  SteadyClock::duration GUARDED_BY(::cs_main) time_forks{};
984  SteadyClock::duration GUARDED_BY(::cs_main) time_connect{};
985  SteadyClock::duration GUARDED_BY(::cs_main) time_verify{};
986  SteadyClock::duration GUARDED_BY(::cs_main) time_undo{};
987  SteadyClock::duration GUARDED_BY(::cs_main) time_index{};
988  SteadyClock::duration GUARDED_BY(::cs_main) time_total{};
989  int64_t GUARDED_BY(::cs_main) num_blocks_total{0};
990  SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total{};
991  SteadyClock::duration GUARDED_BY(::cs_main) time_flush{};
992  SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate{};
993  SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect{};
994 
995 protected:
996  CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
997 
998 public:
1000 
1001  explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);
1002 
1005  std::function<void()> snapshot_download_completed = std::function<void()>();
1006 
1007  const CChainParams& GetParams() const { return m_options.chainparams; }
1008  const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
1009  bool ShouldCheckBlockIndex() const;
1010  const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
1011  const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
1012  kernel::Notifications& GetNotifications() const { return m_options.notifications; };
1013 
1019  void CheckBlockIndex() const;
1020 
1033 
1039 
1041 
1049  std::atomic_bool m_cached_is_ibd{true};
1050 
1058  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = SEQ_ID_INIT_FROM_DISK + 1;
1060  int32_t nBlockReverseSequenceId = -1;
1062  arith_uint256 nLastPreciousChainwork = 0;
1063 
1064  // Reset the memory-only sequence counters we use to track block arrival
1065  // (used by tests to reset state)
1067  {
1069  nBlockSequenceId = SEQ_ID_INIT_FROM_DISK + 1;
1070  nBlockReverseSequenceId = -1;
1071  }
1072 
1073 
1078  CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};
1079 
1082  size_t m_total_coinstip_cache{0};
1083  //
1086  size_t m_total_coinsdb_cache{0};
1087 
1091  // constructor
1092  Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1093 
1106  AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
1107 
1116  SnapshotCompletionResult MaybeValidateSnapshot(Chainstate& validated_cs, Chainstate& unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1117 
1120  {
1121  for (auto& cs : m_chainstates) {
1122  if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && !cs->m_target_blockhash) return *cs;
1123  }
1124  abort();
1125  }
1126 
1129  {
1130  for (auto& cs : m_chainstates) {
1131  if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && cs->m_target_blockhash && !cs->m_target_utxohash) return cs.get();
1132  }
1133  return nullptr;
1134  }
1135 
1140  {
1141  for (auto* cs : {&CurrentChainstate(), HistoricalChainstate()}) {
1142  if (cs && cs->m_assumeutxo == Assumeutxo::VALIDATED) return *cs;
1143  }
1144  abort();
1145  }
1146 
1148  std::unique_ptr<Chainstate> RemoveChainstate(Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
1149  {
1150  auto it{std::find_if(m_chainstates.begin(), m_chainstates.end(), [&](auto& cs) { return cs.get() == &chainstate; })};
1151  if (it != m_chainstates.end()) {
1152  auto ret{std::move(*it)};
1153  m_chainstates.erase(it);
1154  return ret;
1155  }
1156  return nullptr;
1157  }
1158 
1164  Chainstate& ActiveChainstate() const;
1165  CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
1166  int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
1167  CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
1169 
1181  void UpdateIBDStatus() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1182 
1184  {
1186  return m_blockman.m_block_index;
1187  }
1188 
1193 
1195  bool IsInitialBlockDownload() const noexcept;
1196 
1198  double GuessVerificationProgress(const CBlockIndex* pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1199 
1226  void LoadExternalBlockFile(
1227  AutoFile& file_in,
1228  FlatFilePos* dbp = nullptr,
1229  std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);
1230 
1255  bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1256 
1269  bool ProcessNewBlockHeaders(std::span<const CBlockHeader> headers, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1270 
1290  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);
1291 
1292  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1293 
1300  [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1302 
1304  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1305 
1308  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1309 
1315  void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1316 
1318  void GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1319 
1324  void ReportHeadersPresync(int64_t height, int64_t timestamp);
1325 
1329  Chainstate* LoadAssumeutxoChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1330 
1332  Chainstate& AddChainstate(std::unique_ptr<Chainstate> chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1333 
1334  void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1335 
1338  [[nodiscard]] bool DeleteChainstate(Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1339 
1349  bool ValidatedSnapshotCleanup(Chainstate& validated_cs, Chainstate& unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1350 
1352  std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> GetHistoricalBlockRange() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1353 
1355  util::Result<void> ActivateBestChains() LOCKS_EXCLUDED(::cs_main);
1356 
1360  void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1361 
1364  std::optional<int> BlocksAheadOfTip() const LOCKS_EXCLUDED(::cs_main);
1365 
1366  CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }
1367 
1368  ~ChainstateManager();
1369 
1377  std::vector<std::unique_ptr<Chainstate>> m_chainstates GUARDED_BY(::cs_main);
1378 };
1379 
1381 template<typename DEP>
1382 bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1383 {
1384  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1385 }
1386 
1387 template<typename DEP>
1388 bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1389 {
1390  return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1391 }
1392 
1393 template<typename DEP>
1394 bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1395 {
1396  return DeploymentEnabled(chainman.GetConsensus(), dep);
1397 }
1398 
1400 bool IsBIP30Repeat(const CBlockIndex& block_index);
1401 
1403 bool IsBIP30Unspendable(const uint256& block_hash, int block_height);
1404 
1405 // Returns the script flags which should be checked for a given block
1406 script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman);
1407 
1408 #endif // BITCOIN_VALIDATION_H
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:686
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:156
Mockable clock in the context of tests, otherwise the system clock.
Definition: time.h:18
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, std::shared_ptr< const CBlock > block_to_connect, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
const CBlockIndex *m_cached_target_block GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_target_blockhash)
Definition: validation.h:571
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1038
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:637
const uint256 & AssumedValidBlock() const
Definition: validation.h:1011
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
int ret
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:562
script_verify_flags m_flags
Definition: validation.h:344
Valid signature cache, to avoid doing expensive ECDSA signature checking twice for every transaction ...
Definition: sigcache.h:38
bool ReplayBlocks()
Replay blocks that aren&#39;t fully applied to the database.
The assumeutxo snapshot failed validation.
CScriptCheck & operator=(const CScriptCheck &)=delete
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
Definition: validation.h:1382
SignatureCache m_signature_cache
Definition: validation.h:378
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1388
AssertLockHeld(pool.cs)
const Options m_options
Definition: validation.h:1035
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Definition: validation.h:171
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:93
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries that have as much work as our current tip or more, and transaction data needed to be validated (with BLOCK_VALID_TRANSACTIONS for each block and its parents back to the genesis block or an assumeutxo snapshot block).
Definition: validation.h:683
Convenience class for initializing and passing the script execution cache and signature cache...
Definition: validation.h:370
assert(!tx.IsCoinBase())
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
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:116
int64_t GUARDED_BY(::cs_main) num_blocks_total
Definition: validation.h:989
const std::optional< std::vector< Wtxid > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
Definition: validation.h:162
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:996
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:573
Bilingual messages:
Definition: translation.h:24
Definition: block.h:73
The cache is at >= 90% capacity.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:479
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:939
An in-memory indexed chain of blocks.
Definition: chain.h:379
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, bool check_pow, bool check_merkle_root) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Verify a block, including transactions.
SteadyClock::duration GUARDED_BY(::cs_main) time_connect
Definition: validation.h:984
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:718
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:45
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:76
Information about chainstate that notifications are sent from.
Definition: types.h:18
DisconnectResult
Definition: validation.h:451
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:565
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1165
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(util::Result< CBlockIndex * ActivateSnapshot)(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Instantiate a new chainstate.
Definition: validation.h:1105
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation. ...
Definition: validation.h:374
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:78
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:133
int Height() const
Return the maximal height in the chain.
Definition: chain.h:425
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:135
#define LOCK_RETURNED(x)
Definition: threadsafety.h:49
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:147
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:90
The coins cache is in immediate need of a flush.
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops. ...
Definition: validation.h:148
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:143
Definition: common.h:29
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:150
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:76
User-controlled performance and debug options.
Definition: txdb.h:26
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:294
const ResultType m_result_type
Result type.
Definition: validation.h:140
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< Wtxid, MempoolAcceptResult > &&results)
Definition: validation.h:251
std::map< Wtxid, MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:245
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1394
bool IsBIP30Unspendable(const uint256 &block_hash, int block_height)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30) ...
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument &#39;checklevel&#39;.
Definition: validation.cpp:100
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:625
bool cacheStore
Definition: validation.h:345
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:372
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we&#39;ve seen so far for which the block is not known to be invalid (used, among others, for getheaders queries&#39; starting points).
Definition: validation.h:1078
void ForceFlushStateToDisk(bool wipe_cache=true)
Flush all changes to disk.
CTxOut m_tx_out
Definition: validation.h:341
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:715
PackageMempoolAcceptResult(PackageValidationState state, std::map< Wtxid, MempoolAcceptResult > &&results)
Definition: validation.h:247
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1034
CVerifyDB(kernel::Notifications &notifications)
Transaction validation functions.
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1192
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
FlushStateMode
Definition: validation.h:462
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:105
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept, const std::optional< CFeeRate > &client_maxfeerate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, SignatureCache &signature_cache, unsigned int nInIn, script_verify_flags flags, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:350
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:583
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain&#39;s tip.
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
constexpr std::array FlushStateModeNames
Definition: validation.h:461
util::Result< void > InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(friend ChainstateManager
In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for iss...
Definition: validation.h:897
Blocks after an assumeutxo snapshot have been validated but the snapshot itself has not been validate...
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:550
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30) ...
const std::list< CTransactionRef > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:146
constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept
Definition: validation.h:518
Abstract view on the open txout dataset.
Definition: coins.h:307
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
Chainstate & ValidatedChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return fully validated chainstate that should be used for indexing, to support indexes that need to i...
Definition: validation.h:1139
Validation result for package mempool acceptance.
Definition: validation.h:236
std::unique_ptr< Chainstate > RemoveChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Remove a chainstate.
Definition: validation.h:1148
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(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)
Find the best known block, and make it the tip of the block chain.
Definition: validation.h:781
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...
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
SnapshotCompletionResult
Definition: validation.h:902
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
kernel::Notifications & GetNotifications() const
Definition: validation.h:1012
CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex())
The last header for which a headerTip notification was issued.
Definition: validation.h:944
std::optional< std::pair< ScriptError, std::string > > operator()()
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:435
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:57
const Consensus::Params & GetConsensus() const
Definition: validation.h:1008
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
Definition: validation.h:1119
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the [start, end] (inclusive) of block heights we can prune.
SteadyClock::duration GUARDED_BY(::cs_main) time_index
Definition: validation.h:987
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const bilingual_str &message)
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1167
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:191
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:694
SteadyClock::duration GUARDED_BY(::cs_main) time_total
Definition: validation.h:988
Every block in the chain has been validated.
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:708
An output of a transaction.
Definition: transaction.h:139
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
static void CheckBlockIndex(benchmark::Bench &bench)
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1032
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:84
A base class defining functions for notifying about certain kernel events.
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Add a block to the candidate set if it has as much work as the current tip.
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Check if transaction will be final in the next block to be created.
Definition: validation.h:317
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.
DisconnectedBlockTransactions.
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:131
unsigned int nHeight
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:197
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
Definition: validation.h:186
#define Assume(val)
Assume is the identity function.
Definition: check.h:125
static MempoolAcceptResult MempoolTxDifferentWitness(const Wtxid &other_wtxid)
Definition: validation.h:190
256-bit unsigned big integer.
SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect
Definition: validation.h:993
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:76
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:338
ValidationCache m_validation_cache
Definition: validation.h:1040
Definition: messages.h:21
void InvalidateBlock(ChainstateManager &chainman, const uint256 block_hash)
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:216
SteadyClock::duration GUARDED_BY(::cs_main) time_verify
Definition: validation.h:985
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
SteadyClock::duration GUARDED_BY(::cs_main) time_flush
Definition: validation.h:991
int flags
Definition: bitcoin-tx.cpp:529
ValidationCache & operator=(const ValidationCache &)=delete
const CChainParams & GetParams() const
Definition: validation.h:1007
PackageValidationState m_state
Definition: validation.h:238
256-bit opaque blob.
Definition: uint256.h:195
CoinsCacheSizeState
Definition: validation.h:509
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
Definition: validation.h:386
const CTransaction * ptxTo
Definition: validation.h:342
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1010
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
fs::path StoragePath() const
Return path to chainstate leveldb directory.
kernel::Notifications & m_notifications
Definition: validation.h:438
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:186
auto result
Definition: common-types.h:74
bool HasValidProofOfWork(std::span< const CBlockHeader > headers, const Consensus::Params &consensusParams)
Check that the proof of work on each blockheader matches the value in nBits.
Assumeutxo
Chainstate assumeutxo validity.
Definition: validation.h:527
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:50
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:93
const CChainParams & Params()
Return the currently selected parameters.
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:77
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:34
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
static constexpr int32_t SEQ_ID_INIT_FROM_DISK
Definition: chain.h:40
SteadyClock::duration GUARDED_BY(::cs_main) time_check
Timers and counters used for benchmarking validation in both background and active chainstates...
Definition: validation.h:982
bool m_mempool cs
Definition: validation.h:785
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1066
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:396
VerifyDBResult
Definition: validation.h:426
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1166
Application-specific storage settings.
Definition: dbwrapper.h:33
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac...
Definition: feerate.h:31
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:34
const CBlockIndex *SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *TargetBlock() const EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlock(CBlockIndex *block) EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(boo ReachedTarget)() const EXCLUSIVE_LOCKS_REQUIRED(
The base of the snapshot this chainstate was created from.
Definition: validation.h:669
PackageMempoolAcceptResult(const Wtxid &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:256
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
unsigned int nIn
Definition: validation.h:343
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:721
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.
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for success case.
Definition: validation.h:203
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:558
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:167
SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate
Definition: validation.h:992
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:280
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:367
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:87
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
Definition: validation.h:225
MempoolAcceptResult(const Wtxid &other_wtxid)
Constructor for witness-swapped case.
Definition: validation.h:229
CuckooCache::cache< uint256, SignatureCacheHasher > m_script_execution_cache
Definition: validation.h:377
A hasher class for SHA-256.
Definition: sha256.h:13
Version of SteadyClock that is mockable in the context of tests (set the current value with SetMockTi...
Definition: time.h:38
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
Definition: validation.h:1128
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:571
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
Definition: validation.h:805
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
arith_uint256 CalculateClaimedHeadersWork(std::span< const CBlockHeader > headers)
Return the sum of the claimed work on a given set of headers.
SignatureCache * m_signature_cache
Definition: validation.h:347
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip...
Definition: validation.cpp:246
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:26
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:568
CTxMemPool * GetMempool()
Definition: validation.h:701
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:246
const std::optional< Wtxid > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness...
Definition: validation.h:165
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it...
Definition: txmempool.h:260
#define Assert(val)
Identity function.
Definition: check.h:113
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(NodeClock::time_poin m_next_write)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:891
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Definition: validation.h:177
SteadyClock::duration GUARDED_BY(::cs_main) time_undo
Definition: validation.h:986
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:37
transaction_identifier represents the two canonical transaction identifier types (txid, wtxid).
bool IsBlockMutated(const CBlock &block, bool check_witness_root)
Check if a block has been mutated (with respect to its merkle root and witness commitments).
SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total
Definition: validation.h:990
PrecomputedTransactionData * txdata
Definition: validation.h:346
SteadyClock::duration GUARDED_BY(::cs_main) time_forks
Definition: validation.h:983