Bitcoin Core  26.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 std::string& strMessage, const bilingual_str& userMessage = {});
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 
283  const Package& txns, bool test_accept)
285 
286 /* Mempool validation helper functions */
287 
291 bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
292 
311 std::optional<LockPoints> CalculateLockPointsAtTip(
312  CBlockIndex* tip,
313  const CCoinsView& coins_view,
314  const CTransaction& tx);
315 
326  const LockPoints& lock_points);
327 
333 {
334 private:
337  unsigned int nIn;
338  unsigned int nFlags;
342 
343 public:
344  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
345  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), txdata(txdataIn) { }
346 
347  CScriptCheck(const CScriptCheck&) = delete;
351 
352  bool operator()();
353 
354  ScriptError GetScriptError() const { return error; }
355 };
356 
357 // CScriptCheck is used a lot in std::vector, make sure that's efficient
358 static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
359 static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
360 static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
361 
363 [[nodiscard]] bool InitScriptExecutionCache(size_t max_size_bytes);
364 
368 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
369 
372  const CChainParams& chainparams,
373  Chainstate& chainstate,
374  const CBlock& block,
375  CBlockIndex* pindexPrev,
376  bool fCheckPOW = true,
377  bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
378 
380 bool HasValidProofOfWork(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams);
381 
383 arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader>& headers);
384 
385 enum class VerifyDBResult {
386  SUCCESS,
388  INTERRUPTED,
391 };
392 
395 {
396 private:
398 
399 public:
400  explicit CVerifyDB(kernel::Notifications& notifications);
401  ~CVerifyDB();
402  [[nodiscard]] VerifyDBResult VerifyDB(
403  Chainstate& chainstate,
404  const Consensus::Params& consensus_params,
405  CCoinsView& coinsview,
406  int nCheckLevel,
407  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
408 };
409 
411 {
412  DISCONNECT_OK, // All good.
413  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
414  DISCONNECT_FAILED // Something else went wrong.
415 };
416 
417 class ConnectTrace;
418 
420 enum class FlushStateMode {
421  NONE,
422  IF_NEEDED,
423  PERIODIC,
424  ALWAYS
425 };
426 
436 class CoinsViews {
437 
438 public:
442 
445 
448  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
449 
456  CoinsViews(DBParams db_params, CoinsViewOptions options);
457 
459  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
460 };
461 
463 {
465  CRITICAL = 2,
467  LARGE = 1,
468  OK = 0
469 };
470 
486 {
487 protected:
494 
498 
500  std::unique_ptr<CoinsViews> m_coins_views;
501 
513  bool m_disabled GUARDED_BY(::cs_main) {false};
514 
516  const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main) {nullptr};
517 
518 public:
522 
527 
528  explicit Chainstate(
529  CTxMemPool* mempool,
530  node::BlockManager& blockman,
531  ChainstateManager& chainman,
532  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
533 
539 
546  void InitCoinsDB(
547  size_t cache_size_bytes,
548  bool in_memory,
549  bool should_wipe,
550  fs::path leveldb_name = "chainstate");
551 
554  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
555 
558  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
559  {
561  return m_coins_views && m_coins_views->m_cacheview;
562  }
563 
567 
573  const std::optional<uint256> m_from_snapshot_blockhash;
574 
580  const CBlockIndex* SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
581 
588  std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
589 
592  {
594  Assert(m_coins_views);
595  return *Assert(m_coins_views->m_cacheview);
596  }
597 
600  {
602  return Assert(m_coins_views)->m_dbview;
603  }
604 
607  {
608  return m_mempool;
609  }
610 
614  {
616  return Assert(m_coins_views)->m_catcherview;
617  }
618 
620  void ResetCoinsViews() { m_coins_views.reset(); }
621 
623  bool HasCoinsViews() const { return (bool)m_coins_views; }
624 
626  size_t m_coinsdb_cache_size_bytes{0};
627 
629  size_t m_coinstip_cache_size_bytes{0};
630 
633  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
635 
647  bool FlushStateToDisk(
648  BlockValidationState& state,
649  FlushStateMode mode,
650  int nManualPruneHeight = 0);
651 
653  void ForceFlushStateToDisk();
654 
657  void PruneAndFlush();
658 
680  bool ActivateBestChain(
681  BlockValidationState& state,
682  std::shared_ptr<const CBlock> pblock = nullptr)
683  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
685 
686  // Block (dis)connection on a given view:
687  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
689  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
690  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
691 
692  // Apply the effects of a block disconnection on the UTXO set.
693  bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
694 
695  // Manual block validity manipulation:
700  bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
701  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
703 
705  bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex)
706  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex)
708 
710  void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
711 
713  bool ReplayBlocks();
714 
716  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
718  bool LoadGenesisBlock();
719 
720  void TryAddBlockIndexCandidate(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
721 
722  void PruneBlockIndexCandidates();
723 
724  void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
725 
727  const CBlockIndex* FindForkInGlobalIndex(const CBlockLocator& locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
728 
730  bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
731 
735  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
736 
737  CoinsCacheSizeState GetCoinsCacheSizeState(
738  size_t max_coins_cache_size_bytes,
739  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
740 
742 
744  RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
745  {
746  return m_mempool ? &m_mempool->cs : nullptr;
747  }
748 
749 private:
750  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);
751  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);
752 
753  void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
754  CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
755 
756  bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
757 
758  void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
759  void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
760 
774  void MaybeUpdateMempoolForReorg(
775  DisconnectedBlockTransactions& disconnectpool,
776  bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
777 
779  void UpdateTip(const CBlockIndex* pindexNew)
781 
782  SteadyClock::time_point m_last_write{};
783  SteadyClock::time_point m_last_flush{};
784 
789  [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
790 
792 };
793 
794 
796  SUCCESS,
797  SKIPPED,
798 
799  // Expected assumeutxo configuration data is not found for the height of the
800  // base block.
802 
803  // Failed to generate UTXO statistics (to check UTXO set hash) for the background
804  // chainstate.
805  STATS_FAILED,
806 
807  // The UTXO set hash of the background validation chainstate does not match
808  // the one expected by assumeutxo chainparams.
810 
811  // The blockhash of the current tip of the background validation chainstate does
812  // not match the one expected by the snapshot chainstate.
814 };
815 
844 {
845 private:
862  std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
863 
874  std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
875 
878  Chainstate* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
879 
880  CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
881 
883  [[nodiscard]] bool PopulateAndValidateSnapshot(
884  Chainstate& snapshot_chainstate,
885  AutoFile& coins_file,
886  const node::SnapshotMetadata& metadata);
887 
895  bool AcceptBlockHeader(
896  const CBlockHeader& block,
897  BlockValidationState& state,
898  CBlockIndex** ppindex,
899  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
900  friend Chainstate;
901 
903  std::chrono::time_point<std::chrono::steady_clock> m_last_presync_update GUARDED_BY(::cs_main) {};
904 
905  std::array<ThresholdConditionCache, VERSIONBITS_NUM_BITS> m_warningcache GUARDED_BY(::cs_main);
906 
912  bool IsUsable(const Chainstate* const cs) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
913  return cs && !cs->m_disabled;
914  }
915 
918 
919 public:
921 
922  explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);
923 
926  std::function<void()> restart_indexes = std::function<void()>();
927 
928  const CChainParams& GetParams() const { return m_options.chainparams; }
929  const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
930  bool ShouldCheckBlockIndex() const { return *Assert(m_options.check_block_index); }
931  const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
932  const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
933  kernel::Notifications& GetNotifications() const { return m_options.notifications; };
934 
940  void CheckBlockIndex();
941 
954 
957  std::thread m_thread_load;
961 
969  mutable std::atomic<bool> m_cached_finished_ibd{false};
970 
976  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
978  int32_t nBlockReverseSequenceId = -1;
980  arith_uint256 nLastPreciousChainwork = 0;
981 
982  // Reset the memory-only sequence counters we use to track block arrival
983  // (used by tests to reset state)
985  {
987  nBlockSequenceId = 1;
988  nBlockReverseSequenceId = -1;
989  }
990 
991 
1011  std::set<CBlockIndex*> m_failed_blocks;
1012 
1014  CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};
1015 
1018  int64_t m_total_coinstip_cache{0};
1019  //
1022  int64_t m_total_coinsdb_cache{0};
1023 
1027  // constructor
1028  Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1029 
1031  std::vector<Chainstate*> GetAll();
1032 
1046  [[nodiscard]] bool ActivateSnapshot(
1047  AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
1048 
1056  SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1057 
1059  const CBlockIndex* GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1060 
1062  Chainstate& ActiveChainstate() const;
1063  CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
1064  int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
1065  CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
1066 
1069  return IsUsable(m_snapshot_chainstate.get()) && IsUsable(m_ibd_chainstate.get());
1070  }
1071 
1074  return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip() : nullptr;
1075  }
1076 
1078  {
1080  return m_blockman.m_block_index;
1081  }
1082 
1087 
1090  bool IsSnapshotActive() const;
1091 
1092  std::optional<uint256> SnapshotBlockhash() const;
1093 
1096  {
1097  return m_snapshot_chainstate && m_ibd_chainstate && m_ibd_chainstate->m_disabled;
1098  }
1099 
1101  bool IsInitialBlockDownload() const;
1102 
1129  void LoadExternalBlockFile(
1130  AutoFile& file_in,
1131  FlatFilePos* dbp = nullptr,
1132  std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);
1133 
1158  bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1159 
1171  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1172 
1192  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);
1193 
1194  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1195 
1202  [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1204 
1206  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1207 
1210  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1211 
1213  void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1214 
1216  std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1217 
1222  void ReportHeadersPresync(const arith_uint256& work, int64_t height, int64_t timestamp);
1223 
1226  bool DetectSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1227 
1228  void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1229 
1232  [[nodiscard]] bool DeleteSnapshotChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1233 
1236  Chainstate& ActivateExistingSnapshot(uint256 base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1237 
1247  bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1248 
1257  Chainstate& GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1258 
1262  std::pair<int, int> GetPruneRange(
1263  const Chainstate& chainstate, int last_height_can_prune) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1264 
1267  std::optional<int> GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1268 
1269  CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }
1270 
1271  ~ChainstateManager();
1272 };
1273 
1275 template<typename DEP>
1276 bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1277 {
1278  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1279 }
1280 
1281 template<typename DEP>
1282 bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1283 {
1284  return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1285 }
1286 
1287 template<typename DEP>
1288 bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1289 {
1290  return DeploymentEnabled(chainman.GetConsensus(), dep);
1291 }
1292 
1294 bool IsBIP30Repeat(const CBlockIndex& block_index);
1295 
1297 bool IsBIP30Unspendable(const CBlockIndex& block_index);
1298 
1299 #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:150
An in-memory indexed chain of blocks.
Definition: chain.h:447
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:333
CScriptCheck & operator=(CScriptCheck &&)=default
bool operator()()
ScriptError GetScriptError() const
Definition: validation.h:354
CScriptCheck(const CScriptCheck &)=delete
PrecomputedTransactionData * txdata
Definition: validation.h:341
CTxOut m_tx_out
Definition: validation.h:335
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:344
CScriptCheck(CScriptCheck &&)=default
bool cacheStore
Definition: validation.h:339
ScriptError error
Definition: validation.h:340
unsigned int nFlags
Definition: validation.h:338
CScriptCheck & operator=(const CScriptCheck &)=delete
const CTransaction * ptxTo
Definition: validation.h:336
unsigned int nIn
Definition: validation.h:337
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:300
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:388
An output of a transaction.
Definition: transaction.h:150
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:395
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:397
CVerifyDB(kernel::Notifications &notifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:486
CTxMemPool * GetMempool()
Definition: validation.h:606
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:493
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:566
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:623
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:599
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:573
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:497
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:513
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:526
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:500
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:516
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:620
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:613
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:516
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:844
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:878
const CChainParams & GetParams() const
Definition: validation.h:928
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:931
std::thread m_thread_load
Definition: validation.h:957
bool ShouldCheckBlockIndex() const
Definition: validation.h:930
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1077
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1095
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:953
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
Definition: validation.h:917
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1068
const util::SignalInterrupt & m_interrupt
Definition: validation.h:955
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1064
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1086
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1065
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:903
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1073
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:880
const Options m_options
Definition: validation.h:956
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:932
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1014
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1031
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:1011
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:933
bool IsUsable(const Chainstate *const cs) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
Definition: validation.h:912
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:984
const Consensus::Params & GetConsensus() const
Definition: validation.h:929
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:960
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:436
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:109
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:120
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)
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
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h: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:311
bool InitScriptExecutionCache(size_t max_size_bytes)
Initializes the script-execution cache.
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h: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:1276
SnapshotCompletionResult
Definition: validation.h:795
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1288
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:80
bool IsBIP30Unspendable(const CBlockIndex &block_index)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)
VerifyDBResult
Definition: validation.h:385
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:463
@ 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:1282
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:420
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:114
DisconnectResult
Definition: validation.h:411
@ DISCONNECT_FAILED
Definition: validation.h:414
@ DISCONNECT_UNCLEAN
Definition: validation.h:413
@ DISCONNECT_OK
Definition: validation.h:412
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage={})