Bitcoin Core  27.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 #include <arith_uint256.h>
10 #include <attributes.h>
11 #include <chain.h>
12 #include <checkqueue.h>
13 #include <kernel/chain.h>
14 #include <consensus/amount.h>
15 #include <deploymentstatus.h>
16 #include <kernel/chainparams.h>
18 #include <kernel/cs_main.h> // IWYU pragma: export
19 #include <node/blockstorage.h>
20 #include <policy/feerate.h>
21 #include <policy/packages.h>
22 #include <policy/policy.h>
23 #include <script/script_error.h>
24 #include <sync.h>
25 #include <txdb.h>
26 #include <txmempool.h> // For CTxMemPool::cs
27 #include <uint256.h>
28 #include <util/check.h>
29 #include <util/fs.h>
30 #include <util/hasher.h>
31 #include <util/result.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 <type_traits>
44 #include <utility>
45 #include <vector>
46 
47 class Chainstate;
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 namespace util {
62 class SignalInterrupt;
63 } // namespace util
64 
66 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
67 static const signed int DEFAULT_CHECKBLOCKS = 6;
68 static constexpr int DEFAULT_CHECKLEVEL{3};
69 // Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
70 // At 1MB per block, 288 blocks = 288MB.
71 // Add 15% for Undo data = 331MB
72 // Add 20% for Orphan block rate = 397MB
73 // We want the low water mark after pruning to be at least 397 MB and since we prune in
74 // full block file chunks, we need the high water mark which triggers the prune to be
75 // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
76 // Setting the target to >= 550 MiB will make it likely we can respect the target.
77 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
78 
83  POST_INIT
84 };
85 
87 extern std::condition_variable g_best_block_cv;
89 extern uint256 g_best_block;
90 
92 extern const std::vector<std::string> CHECKLEVEL_DOC;
93 
94 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
95 
96 bool FatalError(kernel::Notifications& notifications, BlockValidationState& state, const bilingual_str& message);
97 
99 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
100 
102 void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
103 
128  enum class ResultType {
129  VALID,
130  INVALID,
131  MEMPOOL_ENTRY,
133  };
136 
139 
141  const std::list<CTransactionRef> m_replaced_transactions;
143  const std::optional<int64_t> m_vsize;
145  const std::optional<CAmount> m_base_fees;
151  const std::optional<CFeeRate> m_effective_feerate;
157  const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations;
158 
160  const std::optional<uint256> m_other_wtxid;
161 
163  return MempoolAcceptResult(state);
164  }
165 
167  CFeeRate effective_feerate,
168  const std::vector<Wtxid>& wtxids_fee_calculations) {
169  return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations);
170  }
171 
172  static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
173  int64_t vsize,
174  CAmount fees,
175  CFeeRate effective_feerate,
176  const std::vector<Wtxid>& wtxids_fee_calculations) {
177  return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
178  effective_feerate, wtxids_fee_calculations);
179  }
180 
181  static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
182  return MempoolAcceptResult(vsize, fees);
183  }
184 
186  return MempoolAcceptResult(other_wtxid);
187  }
188 
189 // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
190 private:
193  : m_result_type(ResultType::INVALID), m_state(state) {
194  Assume(!state.IsValid()); // Can be invalid or error
195  }
196 
198  explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
199  int64_t vsize,
200  CAmount fees,
201  CFeeRate effective_feerate,
202  const std::vector<Wtxid>& wtxids_fee_calculations)
203  : m_result_type(ResultType::VALID),
204  m_replaced_transactions(std::move(replaced_txns)),
205  m_vsize{vsize},
206  m_base_fees(fees),
207  m_effective_feerate(effective_feerate),
208  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
209 
212  CFeeRate effective_feerate,
213  const std::vector<Wtxid>& wtxids_fee_calculations)
214  : m_result_type(ResultType::INVALID),
215  m_state(state),
216  m_effective_feerate(effective_feerate),
217  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
218 
220  explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
221  : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
222 
224  explicit MempoolAcceptResult(const uint256& other_wtxid)
225  : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
226 };
227 
232 {
240  std::map<uint256, MempoolAcceptResult> m_tx_results;
241 
243  std::map<uint256, MempoolAcceptResult>&& results)
244  : m_state{state}, m_tx_results(std::move(results)) {}
245 
247  std::map<uint256, MempoolAcceptResult>&& results)
248  : m_state{state}, m_tx_results(std::move(results)) {}
249 
251  explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
252  : m_tx_results{ {wtxid, result} } {}
253 };
254 
270  int64_t accept_time, bool bypass_limits, bool test_accept)
272 
284  const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
286 
287 /* Mempool validation helper functions */
288 
292 bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
293 
312 std::optional<LockPoints> CalculateLockPointsAtTip(
313  CBlockIndex* tip,
314  const CCoinsView& coins_view,
315  const CTransaction& tx);
316 
327  const LockPoints& lock_points);
328 
334 {
335 private:
338  unsigned int nIn;
339  unsigned int nFlags;
343 
344 public:
345  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
346  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), txdata(txdataIn) { }
347 
348  CScriptCheck(const CScriptCheck&) = delete;
352 
353  bool operator()();
354 
355  ScriptError GetScriptError() const { return error; }
356 };
357 
358 // CScriptCheck is used a lot in std::vector, make sure that's efficient
359 static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
360 static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
361 static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
362 
364 [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
365 
369 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
370 
373  const CChainParams& chainparams,
374  Chainstate& chainstate,
375  const CBlock& block,
376  CBlockIndex* pindexPrev,
377  bool fCheckPOW = true,
378  bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
379 
381 bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
382 
384 bool IsBlockMutated(const CBlock& block, bool check_witness_root);
385 
388 
389 enum class VerifyDBResult {
390  SUCCESS,
392  INTERRUPTED,
395 };
396 
399 {
400 private:
402 
403 public:
404  explicit CVerifyDB(kernel::Notifications& notifications);
405  ~CVerifyDB();
406  [[nodiscard]] VerifyDBResult VerifyDB(
407  Chainstate& chainstate,
408  const Consensus::Params& consensus_params,
409  CCoinsView& coinsview,
410  int nCheckLevel,
411  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
412 };
413 
415 {
416  DISCONNECT_OK, // All good.
417  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
418  DISCONNECT_FAILED // Something else went wrong.
419 };
420 
421 class ConnectTrace;
422 
424 enum class FlushStateMode {
425  NONE,
426  IF_NEEDED,
427  PERIODIC,
428  ALWAYS
429 };
430 
440 class CoinsViews {
441 
442 public:
446 
449 
452  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
453 
460  CoinsViews(DBParams db_params, CoinsViewOptions options);
461 
463  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
464 };
465 
467 {
469  CRITICAL = 2,
471  LARGE = 1,
472  OK = 0
473 };
474 
490 {
491 protected:
498 
502 
504  std::unique_ptr<CoinsViews> m_coins_views;
505 
517  bool m_disabled GUARDED_BY(::cs_main) {false};
518 
520  const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main) {nullptr};
521 
522 public:
526 
531 
532  explicit Chainstate(
533  CTxMemPool* mempool,
534  node::BlockManager& blockman,
535  ChainstateManager& chainman,
536  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
537 
543 
550  void InitCoinsDB(
551  size_t cache_size_bytes,
552  bool in_memory,
553  bool should_wipe,
554  fs::path leveldb_name = "chainstate");
555 
558  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
559 
562  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
563  {
565  return m_coins_views && m_coins_views->m_cacheview;
566  }
567 
571 
577  const std::optional<uint256> m_from_snapshot_blockhash;
578 
584  const CBlockIndex* SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
585 
593  std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
594 
597  {
599  Assert(m_coins_views);
600  return *Assert(m_coins_views->m_cacheview);
601  }
602 
605  {
607  return Assert(m_coins_views)->m_dbview;
608  }
609 
612  {
613  return m_mempool;
614  }
615 
619  {
621  return Assert(m_coins_views)->m_catcherview;
622  }
623 
625  void ResetCoinsViews() { m_coins_views.reset(); }
626 
628  bool HasCoinsViews() const { return (bool)m_coins_views; }
629 
631  size_t m_coinsdb_cache_size_bytes{0};
632 
634  size_t m_coinstip_cache_size_bytes{0};
635 
638  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
640 
652  bool FlushStateToDisk(
653  BlockValidationState& state,
654  FlushStateMode mode,
655  int nManualPruneHeight = 0);
656 
658  void ForceFlushStateToDisk();
659 
662  void PruneAndFlush();
663 
685  bool ActivateBestChain(
686  BlockValidationState& state,
687  std::shared_ptr<const CBlock> pblock = nullptr)
688  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
690 
691  // Block (dis)connection on a given view:
692  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
694  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
695  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
696 
697  // Apply the effects of a block disconnection on the UTXO set.
698  bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
699 
700  // Manual block validity manipulation:
705  bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
706  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
708 
710  bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
711  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
713 
715  void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
716 
718  bool ReplayBlocks();
719 
721  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
723  bool LoadGenesisBlock();
724 
725  void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
726 
727  void PruneBlockIndexCandidates();
728 
729  void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
730 
732  const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
733 
735  bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
736 
740  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
741 
742  CoinsCacheSizeState GetCoinsCacheSizeState(
743  size_t max_coins_cache_size_bytes,
744  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
745 
747 
749  RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
750  {
751  return m_mempool ? &m_mempool->cs : nullptr;
752  }
753 
754 private:
755  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);
756  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);
757 
758  void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
759  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
760 
761  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
762 
763  void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
764  void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
765 
779  void MaybeUpdateMempoolForReorg(
780  DisconnectedBlockTransactions& disconnectpool,
781  bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
782 
784  void UpdateTip(const CBlockIndex* pindexNew)
786 
787  SteadyClock::time_point m_last_write{};
788  SteadyClock::time_point m_last_flush{};
789 
794  [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
795 
797 };
798 
799 
801  SUCCESS,
802  SKIPPED,
803 
804  // Expected assumeutxo configuration data is not found for the height of the
805  // base block.
807 
808  // Failed to generate UTXO statistics (to check UTXO set hash) for the background
809  // chainstate.
810  STATS_FAILED,
811 
812  // The UTXO set hash of the background validation chainstate does not match
813  // the one expected by assumeutxo chainparams.
815 
816  // The blockhash of the current tip of the background validation chainstate does
817  // not match the one expected by the snapshot chainstate.
819 };
820 
849 {
850 private:
867  std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
868 
879  std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
880 
883  Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
884 
885  CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
886 
888  [[nodiscard]] bool PopulateAndValidateSnapshot(
889  Chainstate& snapshot_chainstate,
890  AutoFile& coins_file,
891  const node::SnapshotMetadata& metadata);
892 
900  bool AcceptBlockHeader(
901  const CBlockHeader& block,
902  BlockValidationState& state,
903  CBlockIndex** ppindex,
904  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
905  friend Chainstate;
906 
908  std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
909 
910  std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> m_warningcache GUARDED_BY(::cs_main);
911 
917  bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
918  return cs && !cs->m_disabled;
919  }
920 
923 
924 public:
926 
927  explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);
928 
931  std::function<void()> restart_indexes = std::function<void()>();
932 
933  const CChainParams& GetParams() const { return m_options.chainparams; }
934  const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
935  bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); }
936  const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
937  const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
938  kernel::Notifications& GetNotifications() const { return m_options.notifications; };
939 
945  void CheckBlockIndex();
946 
959 
962  std::thread m_thread_load;
966 
974  mutable std::atomic<bool> m_cached_finished_ibd{false};
975 
981  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
983  int32_t nBlockReverseSequenceId = -1;
985  arith_uint256 nLastPreciousChainwork = 0;
986 
987  // Reset the memory-only sequence counters we use to track block arrival
988  // (used by tests to reset state)
990  {
992  nBlockSequenceId = 1;
993  nBlockReverseSequenceId = -1;
994  }
995 
996 
1016  std::set<CBlockIndex*> m_failed_blocks;
1017 
1019  CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};
1020 
1023  int64_t m_total_coinstip_cache{0};
1024  //
1027  int64_t m_total_coinsdb_cache{0};
1028 
1032  // constructor
1033  Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1034 
1036  std::vector<Chainstate*> GetAll();
1037 
1051  [[nodiscard]] bool ActivateSnapshot(
1052  AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
1053 
1061  SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1062 
1064  const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1065 
1067  Chainstate& ActiveChainstate() const;
1068  CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
1069  int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
1070  CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
1071 
1074  return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get());
1075  }
1076 
1079  return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() : nullptr;
1080  }
1081 
1083  {
1085  return m_blockman.m_block_index;
1086  }
1087 
1092 
1095  bool IsSnapshotActive() const;
1096 
1097  std::optional<uint256> SnapshotBlockhash() const;
1098 
1101  {
1102  return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
1103  }
1104 
1106  bool IsInitialBlockDownload() const;
1107 
1134  void LoadExternalBlockFile(
1135  AutoFile& file_in,
1136  FlatFilePos* dbp = nullptr,
1137  std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);
1138 
1163  bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1164 
1176  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1177 
1197  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);
1198 
1199  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1200 
1207  [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1209 
1211  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1212 
1215  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1216 
1218  void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1219 
1221  std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1222 
1227  void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
1228 
1231  bool DetectSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1232 
1233  void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1234 
1237  [[nodiscard]] bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1238 
1241  Chainstate& ActivateExistingSnapshot(uint256 base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1242 
1252  bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1253 
1262  Chainstate& GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1263 
1267  std::pair<int, int> GetPruneRange(
1268  const Chainstate& chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1269 
1272  std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1273 
1274  CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }
1275 
1276  ~ChainstateManager();
1277 };
1278 
1280 template<typename DEP>
1281 bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1282 {
1283  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1284 }
1285 
1286 template<typename DEP>
1287 bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1288 {
1289  return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1290 }
1291 
1292 template<typename DEP>
1293 bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1294 {
1295  return DeploymentEnabled(chainman.GetConsensus(), dep);
1296 }
1297 
1299 bool IsBIP30Repeat(const CBlockIndex& block_index);
1300 
1302 bool IsBIP30Unspendable(const CBlockIndex& block_index);
1303 
1304 #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:77
#define Assume(val)
Assume is the identity function.
Definition: check.h:89
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:389
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:141
An in-memory indexed chain of blocks.
Definition: chain.h:418
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:81
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:229
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:54
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:376
Abstract view on the open txout dataset.
Definition: coins.h:173
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:334
CScriptCheck & operator=(CScriptCheck &&)=default
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:355
CScriptCheck(const CScriptCheck &)=delete
PrecomputedTransactionData * txdata
Definition: validation.h:342
CTxOut m_tx_out
Definition: validation.h:336
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:345
CScriptCheck(CScriptCheck &&)=default
bool cacheStore
Definition: validation.h:340
ScriptError error
Definition: validation.h:341
unsigned int nFlags
Definition: validation.h:339
CScriptCheck & operator=(const CScriptCheck &)=delete
const CTransaction * ptxTo
Definition: validation.h:337
unsigned int nIn
Definition: validation.h:338
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:302
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:389
An output of a transaction.
Definition: transaction.h:150
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:399
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:401
CVerifyDB(kernel::Notifications &notifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:490
CTxMemPool * GetMempool()
Definition: validation.h:611
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:497
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:570
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:628
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:604
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:577
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:501
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:517
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:530
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:504
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:520
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:625
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:618
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:520
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:849
std::array< ThresholdConditionCache, VERSIONBITS_NUM_BITS > m_warningcache GUARDED_BY(::cs_main)
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:883
const CChainParams & GetParams() const
Definition: validation.h:933
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:936
std::thread m_thread_load
Definition: validation.h:962
bool ShouldCheckBlockIndex() const
Definition: validation.h:935
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1082
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1100
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:958
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
Definition: validation.h:922
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1073
const util::SignalInterrupt & m_interrupt
Definition: validation.h:960
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1069
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1091
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1070
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:908
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1078
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:885
const Options m_options
Definition: validation.h:961
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...
const uint256 & AssumedValidBlock() const
Definition: validation.h:937
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1019
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1036
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:1016
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
kernel::Notifications & GetNotifications() const
Definition: validation.h:938
bool IsUsable(const Chainstate *const cs) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
Definition: validation.h:917
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:989
const Consensus::Params & GetConsensus() const
Definition: validation.h:934
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:965
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:440
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...
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.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
DisconnectedBlockTransactions.
Different type to mark Mutex at global scope.
Definition: sync.h:140
bool IsValid() const
Definition: validation.h:122
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:81
256-bit unsigned big integer.
A base class defining functions for notifying about certain kernel events.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:135
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:25
256-bit opaque blob.
Definition: uint256.h:106
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
unsigned int nHeight
static void pool cs
Transaction validation functions.
Filesystem operations and types.
Definition: init.h:25
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:83
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:50
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
@ 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:110
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:47
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:124
Holds various statistics on transactions within a chain.
Definition: chainparams.h:70
User-controlled performance and debug options.
Definition: txdb.h:44
Parameters that influence chain consensus.
Definition: params.h:74
Application-specific storage settings.
Definition: dbwrapper.h:33
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:126
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
Definition: validation.h:143
const ResultType m_result_type
Result type.
Definition: validation.h:135
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
Definition: validation.h:220
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:145
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:192
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:138
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
Definition: validation.h:185
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:128
@ DIFFERENT_WITNESS
Valid, transaction was already in the mempool.
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:162
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Definition: validation.h:166
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:151
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:198
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:160
const std::list< CTransactionRef > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:141
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
Definition: validation.h:181
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:172
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:211
const std::optional< std::vector< Wtxid > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
Definition: validation.h:157
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
Definition: validation.h:224
Validation result for package mempool acceptance.
Definition: validation.h:232
PackageValidationState m_state
Definition: validation.h:233
PackageMempoolAcceptResult(PackageValidationState state, std::map< uint256, MempoolAcceptResult > &&results)
Definition: validation.h:242
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:251
std::map< uint256, MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:240
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< uint256, MempoolAcceptResult > &&results)
Definition: validation.h:246
Bilingual messages:
Definition: translation.h:18
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
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
std::chrono::steady_clock SteadyClock
Definition: time.h:25
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:139
AssertLockHeld(pool.cs)
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).
GlobalMutex g_best_block_mutex
Definition: validation.cpp:109
std::condition_variable g_best_block_cv
Definition: validation.cpp:110
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:68
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:77
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
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:242
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:312
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const bilingual_str &message)
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:66
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:1281
SnapshotCompletionResult
Definition: validation.h:800
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1293
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:80
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.
bool IsBIP30Unspendable(const CBlockIndex &block_index)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
VerifyDBResult
Definition: validation.h:389
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:94
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CoinsCacheSizeState
Definition: validation.h:467
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW=true, bool fCheckMerkleRoot=true) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check a block is completely valid from start to finish (only works on top of our current best block)
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1287
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:67
FlushStateMode
Definition: validation.h:424
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:111
DisconnectResult
Definition: validation.h:415
@ DISCONNECT_FAILED
Definition: validation.h:418
@ DISCONNECT_UNCLEAN
Definition: validation.h:417
@ DISCONNECT_OK
Definition: validation.h:416