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 
129  enum class ResultType {
130  VALID,
131  INVALID,
132  MEMPOOL_ENTRY,
134  };
137 
140 
142  const std::optional<std::list<CTransactionRef>> m_replaced_transactions;
144  const std::optional<int64_t> m_vsize;
146  const std::optional<CAmount> m_base_fees;
152  const std::optional<CFeeRate> m_effective_feerate;
158  const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations;
159 
161  const std::optional<uint256> m_other_wtxid;
162 
164  return MempoolAcceptResult(state);
165  }
166 
168  CFeeRate effective_feerate,
169  const std::vector<Wtxid>& wtxids_fee_calculations) {
170  return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations);
171  }
172 
173  static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
174  int64_t vsize,
175  CAmount fees,
176  CFeeRate effective_feerate,
177  const std::vector<Wtxid>& wtxids_fee_calculations) {
178  return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
179  effective_feerate, wtxids_fee_calculations);
180  }
181 
182  static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
183  return MempoolAcceptResult(vsize, fees);
184  }
185 
187  return MempoolAcceptResult(other_wtxid);
188  }
189 
190 // Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
191 private:
194  : m_result_type(ResultType::INVALID), m_state(state) {
195  Assume(!state.IsValid()); // Can be invalid or error
196  }
197 
199  explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
200  int64_t vsize,
201  CAmount fees,
202  CFeeRate effective_feerate,
203  const std::vector<Wtxid>& wtxids_fee_calculations)
204  : m_result_type(ResultType::VALID),
205  m_replaced_transactions(std::move(replaced_txns)),
206  m_vsize{vsize},
207  m_base_fees(fees),
208  m_effective_feerate(effective_feerate),
209  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
210 
213  CFeeRate effective_feerate,
214  const std::vector<Wtxid>& wtxids_fee_calculations)
215  : m_result_type(ResultType::INVALID),
216  m_state(state),
217  m_effective_feerate(effective_feerate),
218  m_wtxids_fee_calculations(wtxids_fee_calculations) {}
219 
221  explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
222  : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
223 
225  explicit MempoolAcceptResult(const uint256& other_wtxid)
226  : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
227 };
228 
233 {
241  std::map<uint256, MempoolAcceptResult> m_tx_results;
242 
244  std::map<uint256, MempoolAcceptResult>&& results)
245  : m_state{state}, m_tx_results(std::move(results)) {}
246 
248  std::map<uint256, MempoolAcceptResult>&& results)
249  : m_state{state}, m_tx_results(std::move(results)) {}
250 
252  explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
253  : m_tx_results{ {wtxid, result} } {}
254 };
255 
271  int64_t accept_time, bool bypass_limits, bool test_accept)
273 
285  const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
287 
288 /* Mempool validation helper functions */
289 
293 bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
294 
313 std::optional<LockPoints> CalculateLockPointsAtTip(
314  CBlockIndex* tip,
315  const CCoinsView& coins_view,
316  const CTransaction& tx);
317 
328  const LockPoints& lock_points);
329 
335 {
336 private:
339  unsigned int nIn;
340  unsigned int nFlags;
344 
345 public:
346  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
347  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), txdata(txdataIn) { }
348 
349  CScriptCheck(const CScriptCheck&) = delete;
353 
354  bool operator()();
355 
356  ScriptError GetScriptError() const { return error; }
357 };
358 
359 // CScriptCheck is used a lot in std::vector, make sure that's efficient
360 static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
361 static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
362 static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
363 
365 [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
366 
370 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
371 
374  const CChainParams& chainparams,
375  Chainstate& chainstate,
376  const CBlock& block,
377  CBlockIndex* pindexPrev,
378  bool fCheckPOW = true,
379  bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
380 
382 bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
383 
385 bool IsBlockMutated(const CBlock& block, bool check_witness_root);
386 
389 
390 enum class VerifyDBResult {
391  SUCCESS,
393  INTERRUPTED,
396 };
397 
400 {
401 private:
403 
404 public:
405  explicit CVerifyDB(kernel::Notifications& notifications);
406  ~CVerifyDB();
407  [[nodiscard]] VerifyDBResult VerifyDB(
408  Chainstate& chainstate,
409  const Consensus::Params& consensus_params,
410  CCoinsView& coinsview,
411  int nCheckLevel,
412  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
413 };
414 
416 {
417  DISCONNECT_OK, // All good.
418  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
419  DISCONNECT_FAILED // Something else went wrong.
420 };
421 
422 class ConnectTrace;
423 
425 enum class FlushStateMode {
426  NONE,
427  IF_NEEDED,
428  PERIODIC,
429  ALWAYS
430 };
431 
441 class CoinsViews {
442 
443 public:
447 
450 
453  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
454 
461  CoinsViews(DBParams db_params, CoinsViewOptions options);
462 
464  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
465 };
466 
468 {
470  CRITICAL = 2,
472  LARGE = 1,
473  OK = 0
474 };
475 
491 {
492 protected:
499 
503 
505  std::unique_ptr<CoinsViews> m_coins_views;
506 
518  bool m_disabled GUARDED_BY(::cs_main) {false};
519 
521  const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main) {nullptr};
522 
523 public:
527 
532 
533  explicit Chainstate(
534  CTxMemPool* mempool,
535  node::BlockManager& blockman,
536  ChainstateManager& chainman,
537  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
538 
544 
551  void InitCoinsDB(
552  size_t cache_size_bytes,
553  bool in_memory,
554  bool should_wipe,
555  fs::path leveldb_name = "chainstate");
556 
559  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
560 
563  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
564  {
566  return m_coins_views && m_coins_views->m_cacheview;
567  }
568 
572 
578  const std::optional<uint256> m_from_snapshot_blockhash;
579 
585  const CBlockIndex* SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
586 
594  std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
595 
598  {
600  Assert(m_coins_views);
601  return *Assert(m_coins_views->m_cacheview);
602  }
603 
606  {
608  return Assert(m_coins_views)->m_dbview;
609  }
610 
613  {
614  return m_mempool;
615  }
616 
620  {
622  return Assert(m_coins_views)->m_catcherview;
623  }
624 
626  void ResetCoinsViews() { m_coins_views.reset(); }
627 
629  bool HasCoinsViews() const { return (bool)m_coins_views; }
630 
632  size_t m_coinsdb_cache_size_bytes{0};
633 
635  size_t m_coinstip_cache_size_bytes{0};
636 
639  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
641 
653  bool FlushStateToDisk(
654  BlockValidationState& state,
655  FlushStateMode mode,
656  int nManualPruneHeight = 0);
657 
659  void ForceFlushStateToDisk();
660 
663  void PruneAndFlush();
664 
686  bool ActivateBestChain(
687  BlockValidationState& state,
688  std::shared_ptr<const CBlock> pblock = nullptr)
689  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
691 
692  // Block (dis)connection on a given view:
693  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
695  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
696  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
697 
698  // Apply the effects of a block disconnection on the UTXO set.
699  bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
700 
701  // Manual block validity manipulation:
706  bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
707  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
709 
711  bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
712  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
714 
716  void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
717 
719  bool ReplayBlocks();
720 
722  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
724  bool LoadGenesisBlock();
725 
726  void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
727 
728  void PruneBlockIndexCandidates();
729 
730  void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
731 
733  const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
734 
736  bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
737 
741  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
742 
743  CoinsCacheSizeState GetCoinsCacheSizeState(
744  size_t max_coins_cache_size_bytes,
745  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
746 
748 
750  RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
751  {
752  return m_mempool ? &m_mempool->cs : nullptr;
753  }
754 
755 private:
756  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);
757  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);
758 
759  void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
760  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
761 
762  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
763 
764  void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
765  void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
766 
780  void MaybeUpdateMempoolForReorg(
781  DisconnectedBlockTransactions& disconnectpool,
782  bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
783 
785  void UpdateTip(const CBlockIndex* pindexNew)
787 
788  SteadyClock::time_point m_last_write{};
789  SteadyClock::time_point m_last_flush{};
790 
795  [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
796 
798 };
799 
800 
802  SUCCESS,
803  SKIPPED,
804 
805  // Expected assumeutxo configuration data is not found for the height of the
806  // base block.
808 
809  // Failed to generate UTXO statistics (to check UTXO set hash) for the background
810  // chainstate.
811  STATS_FAILED,
812 
813  // The UTXO set hash of the background validation chainstate does not match
814  // the one expected by assumeutxo chainparams.
816 
817  // The blockhash of the current tip of the background validation chainstate does
818  // not match the one expected by the snapshot chainstate.
820 };
821 
850 {
851 private:
868  std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
869 
880  std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
881 
884  Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
885 
886  CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
887 
889  [[nodiscard]] bool PopulateAndValidateSnapshot(
890  Chainstate& snapshot_chainstate,
891  AutoFile& coins_file,
892  const node::SnapshotMetadata& metadata);
893 
901  bool AcceptBlockHeader(
902  const CBlockHeader& block,
903  BlockValidationState& state,
904  CBlockIndex** ppindex,
905  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
906  friend Chainstate;
907 
909  std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
910 
911  std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> m_warningcache GUARDED_BY(::cs_main);
912 
918  bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
919  return cs && !cs->m_disabled;
920  }
921 
924 
925 public:
927 
928  explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);
929 
932  std::function<void()> restart_indexes = std::function<void()>();
933 
934  const CChainParams& GetParams() const { return m_options.chainparams; }
935  const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
936  bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); }
937  const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
938  const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
939  kernel::Notifications& GetNotifications() const { return m_options.notifications; };
940 
946  void CheckBlockIndex();
947 
960 
963  std::thread m_thread_load;
967 
975  mutable std::atomic<bool> m_cached_finished_ibd{false};
976 
982  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
984  int32_t nBlockReverseSequenceId = -1;
986  arith_uint256 nLastPreciousChainwork = 0;
987 
988  // Reset the memory-only sequence counters we use to track block arrival
989  // (used by tests to reset state)
991  {
993  nBlockSequenceId = 1;
994  nBlockReverseSequenceId = -1;
995  }
996 
997 
1017  std::set<CBlockIndex*> m_failed_blocks;
1018 
1020  CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};
1021 
1024  int64_t m_total_coinstip_cache{0};
1025  //
1028  int64_t m_total_coinsdb_cache{0};
1029 
1033  // constructor
1034  Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1035 
1037  std::vector<Chainstate*> GetAll();
1038 
1052  [[nodiscard]] bool ActivateSnapshot(
1053  AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
1054 
1062  SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1063 
1065  const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1066 
1068  Chainstate& ActiveChainstate() const;
1069  CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
1070  int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
1071  CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
1072 
1075  return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get());
1076  }
1077 
1080  return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() : nullptr;
1081  }
1082 
1084  {
1086  return m_blockman.m_block_index;
1087  }
1088 
1093 
1096  bool IsSnapshotActive() const;
1097 
1098  std::optional<uint256> SnapshotBlockhash() const;
1099 
1102  {
1103  return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
1104  }
1105 
1107  bool IsInitialBlockDownload() const;
1108 
1135  void LoadExternalBlockFile(
1136  AutoFile& file_in,
1137  FlatFilePos* dbp = nullptr,
1138  std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);
1139 
1164  bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1165 
1177  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1178 
1198  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);
1199 
1200  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1201 
1208  [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1210 
1212  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1213 
1216  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1217 
1219  void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1220 
1222  std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1223 
1228  void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
1229 
1232  bool DetectSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1233 
1234  void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1235 
1238  [[nodiscard]] bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1239 
1242  Chainstate& ActivateExistingSnapshot(uint256 base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1243 
1253  bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1254 
1263  Chainstate& GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1264 
1268  std::pair<int, int> GetPruneRange(
1269  const Chainstate& chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1270 
1273  std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1274 
1275  CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }
1276 
1277  ~ChainstateManager();
1278 };
1279 
1281 template<typename DEP>
1282 bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1283 {
1284  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1285 }
1286 
1287 template<typename DEP>
1288 bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1289 {
1290  return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1291 }
1292 
1293 template<typename DEP>
1294 bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1295 {
1296  return DeploymentEnabled(chainman.GetConsensus(), dep);
1297 }
1298 
1300 bool IsBIP30Repeat(const CBlockIndex& block_index);
1301 
1303 bool IsBIP30Unspendable(const CBlockIndex& block_index);
1304 
1305 #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:335
CScriptCheck & operator=(CScriptCheck &&)=default
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:356
CScriptCheck(const CScriptCheck &)=delete
PrecomputedTransactionData * txdata
Definition: validation.h:343
CTxOut m_tx_out
Definition: validation.h:337
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:346
CScriptCheck(CScriptCheck &&)=default
bool cacheStore
Definition: validation.h:341
ScriptError error
Definition: validation.h:342
unsigned int nFlags
Definition: validation.h:340
CScriptCheck & operator=(const CScriptCheck &)=delete
const CTransaction * ptxTo
Definition: validation.h:338
unsigned int nIn
Definition: validation.h:339
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:390
An output of a transaction.
Definition: transaction.h:150
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:400
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:402
CVerifyDB(kernel::Notifications &notifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:491
CTxMemPool * GetMempool()
Definition: validation.h:612
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:498
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:571
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:629
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:605
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:578
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:502
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:518
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:531
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:505
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:521
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:626
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:619
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:521
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:850
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:884
const CChainParams & GetParams() const
Definition: validation.h:934
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:937
std::thread m_thread_load
Definition: validation.h:963
bool ShouldCheckBlockIndex() const
Definition: validation.h:936
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1083
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1101
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:959
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
Definition: validation.h:923
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1074
const util::SignalInterrupt & m_interrupt
Definition: validation.h:961
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1070
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1092
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1071
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:909
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1079
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:886
const Options m_options
Definition: validation.h:962
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:938
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1020
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1037
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:1017
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:939
bool IsUsable(const Chainstate *const cs) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
Definition: validation.h:918
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:990
const Consensus::Params & GetConsensus() const
Definition: validation.h:935
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:966
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:441
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:137
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:85
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:127
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
Definition: validation.h:144
const ResultType m_result_type
Result type.
Definition: validation.h:136
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
Definition: validation.h:221
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:146
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:142
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:193
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:139
static MempoolAcceptResult MempoolTxDifferentWitness(const uint256 &other_wtxid)
Definition: validation.h:186
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:129
@ DIFFERENT_WITNESS
Valid, transaction was already in the mempool.
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:163
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Definition: validation.h:167
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:152
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:199
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:161
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
Definition: validation.h:182
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:173
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:212
const std::optional< std::vector< Wtxid > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
Definition: validation.h:158
MempoolAcceptResult(const uint256 &other_wtxid)
Constructor for witness-swapped case.
Definition: validation.h:225
Validation result for package mempool acceptance.
Definition: validation.h:233
PackageValidationState m_state
Definition: validation.h:234
PackageMempoolAcceptResult(PackageValidationState state, std::map< uint256, MempoolAcceptResult > &&results)
Definition: validation.h:243
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:252
std::map< uint256, MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:241
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< uint256, MempoolAcceptResult > &&results)
Definition: validation.h:247
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:142
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:112
std::condition_variable g_best_block_cv
Definition: validation.cpp:113
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:245
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:313
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:1282
SnapshotCompletionResult
Definition: validation.h:801
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1294
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:390
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:97
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CoinsCacheSizeState
Definition: validation.h:468
@ 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:1288
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:425
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:114
DisconnectResult
Definition: validation.h:416
@ DISCONNECT_FAILED
Definition: validation.h:419
@ DISCONNECT_UNCLEAN
Definition: validation.h:418
@ DISCONNECT_OK
Definition: validation.h:417