Bitcoin ABC  0.29.2
P2P Digital Currency
validation.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 The Bitcoin Core developers
3 // Copyright (c) 2017-2020 The Bitcoin developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #ifndef BITCOIN_VALIDATION_H
8 #define BITCOIN_VALIDATION_H
9 
10 #if defined(HAVE_CONFIG_H)
11 #include <config/bitcoin-config.h>
12 #endif
13 
14 #include <arith_uint256.h>
15 #include <attributes.h>
16 #include <blockfileinfo.h>
17 #include <blockindexcomparators.h>
18 #include <chain.h>
19 #include <chainparams.h>
20 #include <common/bloom.h>
21 #include <config.h>
22 #include <consensus/amount.h>
23 #include <consensus/consensus.h>
24 #include <deploymentstatus.h>
25 #include <disconnectresult.h>
26 #include <flatfile.h>
27 #include <fs.h>
29 #include <kernel/cs_main.h>
30 #include <node/blockstorage.h>
31 #include <policy/packages.h>
32 #include <script/script_error.h>
33 #include <script/script_metrics.h>
34 #include <shutdown.h>
35 #include <sync.h>
36 #include <txdb.h>
37 #include <txmempool.h> // For CTxMemPool::cs
38 #include <uint256.h>
39 #include <util/check.h>
40 #include <util/translation.h>
41 
42 #include <atomic>
43 #include <cstdint>
44 #include <map>
45 #include <memory>
46 #include <optional>
47 #include <set>
48 #include <string>
49 #include <thread>
50 #include <utility>
51 #include <vector>
52 
54 class CChainParams;
55 class Chainstate;
56 class ChainstateManager;
57 class CScriptCheck;
58 class CTxMemPool;
59 class CTxUndo;
61 
62 struct ChainTxData;
63 struct FlatFilePos;
65 struct LockPoints;
66 struct AssumeutxoData;
67 namespace node {
68 class SnapshotMetadata;
69 } // namespace node
70 namespace Consensus {
71 struct Params;
72 } // namespace Consensus
73 
74 namespace Consensus {
75 struct Params;
76 }
77 
78 #define MIN_TRANSACTION_SIZE \
79  (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
80 
82 static const int MAX_SCRIPTCHECK_THREADS = 15;
84 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
85 
86 static const bool DEFAULT_PEERBLOOMFILTERS = true;
87 
89 static const int DEFAULT_STOPATHEIGHT = 0;
94 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
95 static const signed int DEFAULT_CHECKBLOCKS = 6;
96 static const unsigned int DEFAULT_CHECKLEVEL = 3;
110 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
111 
114 
116 extern std::condition_variable g_best_block_cv;
118 extern uint256 g_best_block;
119 
121 extern const std::vector<std::string> CHECKLEVEL_DOC;
122 
124 private:
126  bool checkPoW : 1;
127  bool checkMerkleRoot : 1;
128 
129 public:
130  // Do full validation by default
131  explicit BlockValidationOptions(const Config &config);
132  explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
133  bool _checkPow = true,
134  bool _checkMerkleRoot = true)
135  : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
136  checkMerkleRoot(_checkMerkleRoot) {}
137 
138  BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
139  BlockValidationOptions ret = *this;
140  ret.checkPoW = _checkPoW;
141  return ret;
142  }
143 
145  withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
146  BlockValidationOptions ret = *this;
147  ret.checkMerkleRoot = _checkMerkleRoot;
148  return ret;
149  }
150 
151  bool shouldValidatePoW() const { return checkPoW; }
152  bool shouldValidateMerkleRoot() const { return checkMerkleRoot; }
153  uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
154 };
155 
159 void StartScriptCheckWorkerThreads(int threads_num);
160 
165 
166 Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
167 
168 bool AbortNode(BlockValidationState &state, const std::string &strMessage,
169  const bilingual_str &userMessage = bilingual_str{});
170 
175 double GuessVerificationProgress(const ChainTxData &data,
176  const CBlockIndex *pindex);
177 
179 void PruneBlockFilesManual(Chainstate &active_chainstate,
180  int nManualPruneHeight);
181 
187  enum class ResultType {
189  VALID,
191  INVALID,
194  };
197 
198  // The following fields are only present when m_result_type =
199  // ResultType::VALID or MEMPOOL_ENTRY
204  const std::optional<int64_t> m_vsize;
206  const std::optional<Amount> m_base_fees;
208  return MempoolAcceptResult(state);
209  }
210 
212  static MempoolAcceptResult Success(int64_t vsize, Amount fees) {
213  return MempoolAcceptResult(ResultType::VALID, vsize, fees);
214  }
215 
220  static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees) {
221  return MempoolAcceptResult(ResultType::MEMPOOL_ENTRY, vsize, fees);
222  }
223 
224  // Private constructors. Use static methods MempoolAcceptResult::Success,
225  // etc. to construct.
226 private:
229  : m_result_type(ResultType::INVALID), m_state(state),
230  m_base_fees(std::nullopt) {
231  // Can be invalid or error
232  Assume(!state.IsValid());
233  }
234 
236  explicit MempoolAcceptResult(ResultType result_type, int64_t vsize,
237  Amount fees)
238  : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees) {}
239 };
240 
253  std::map<const TxId, const MempoolAcceptResult> m_tx_results;
254 
257  std::map<const TxId, const MempoolAcceptResult> &&results)
258  : m_state{state}, m_tx_results(std::move(results)) {}
259 
264  explicit PackageMempoolAcceptResult(const TxId &txid,
265  const MempoolAcceptResult &result)
266  : m_tx_results{{txid, result}} {}
267 };
268 
292 AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx,
293  int64_t accept_time, bool bypass_limits,
294  bool test_accept = false, unsigned int heightOverride = 0)
296 
309 ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool,
310  const Package &txns, bool test_accept)
312 
318 protected:
319  std::atomic<int64_t> remaining;
320 
321 public:
322  explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
323 
324  bool consume_and_check(int consumed) {
325  auto newvalue = (remaining -= consumed);
326  return newvalue >= 0;
327  }
328 
329  bool check() { return remaining >= 0; }
330 };
331 
333 public:
335 
336  // Let's make this bad boy copiable.
338  : CheckInputsLimiter(rhs.remaining.load()) {}
339 
341  remaining = rhs.remaining.load();
342  return *this;
343  }
344 
346  TxSigCheckLimiter txLimiter;
347  // Historically, there has not been a transaction with more than 20k sig
348  // checks on testnet or mainnet, so this effectively disable sigchecks.
349  txLimiter.remaining = 20000;
350  return txLimiter;
351  }
352 };
353 
354 class ConnectTrace;
355 
385 bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
386  const CCoinsViewCache &view, const uint32_t flags,
387  bool sigCacheStore, bool scriptCacheStore,
388  const PrecomputedTransactionData &txdata,
389  int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks,
390  CheckInputsLimiter *pBlockLimitSigChecks,
391  std::vector<CScriptCheck> *pvChecks)
393 
397 static inline bool
399  const CCoinsViewCache &view, const uint32_t flags,
400  bool sigCacheStore, bool scriptCacheStore,
401  const PrecomputedTransactionData &txdata, int &nSigChecksOut)
403  TxSigCheckLimiter nSigChecksTxLimiter;
404  return CheckInputScripts(tx, state, view, flags, sigCacheStore,
405  scriptCacheStore, txdata, nSigChecksOut,
406  nSigChecksTxLimiter, nullptr, nullptr);
407 }
408 
412 void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
413  int nHeight);
414 
418 void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
419  int nHeight);
420 
439 bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view,
440  const CTransaction &tx, LockPoints *lp = nullptr,
441  bool useExistingLockPoints = false);
442 
451 private:
454  unsigned int nIn;
455  uint32_t nFlags;
462 
463 public:
465  : ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false),
467  pBlockLimitSigChecks(nullptr) {}
468 
469  CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
470  unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn,
471  const PrecomputedTransactionData &txdataIn,
472  TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
473  CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
474  : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
475  cacheStore(cacheIn), error(ScriptError::UNKNOWN), txdata(txdataIn),
476  pTxLimitSigChecks(pTxLimitSigChecksIn),
477  pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
478 
479  bool operator()();
480 
481  void swap(CScriptCheck &check) noexcept {
482  std::swap(ptxTo, check.ptxTo);
483  std::swap(m_tx_out, check.m_tx_out);
484  std::swap(nIn, check.nIn);
485  std::swap(nFlags, check.nFlags);
486  std::swap(cacheStore, check.cacheStore);
487  std::swap(error, check.error);
488  std::swap(metrics, check.metrics);
489  std::swap(txdata, check.txdata);
490  std::swap(pTxLimitSigChecks, check.pTxLimitSigChecks);
491  std::swap(pBlockLimitSigChecks, check.pBlockLimitSigChecks);
492  }
493 
494  ScriptError GetScriptError() const { return error; }
495 
497 };
498 
507 bool CheckBlock(const CBlock &block, BlockValidationState &state,
508  const Consensus::Params &params,
509  BlockValidationOptions validationOptions);
510 
518  const CBlockIndex *active_chain_tip, const Consensus::Params &params,
519  const CTransaction &tx, TxValidationState &state)
521 
527  BlockValidationState &state, const CChainParams &params,
528  Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
529  const std::function<NodeClock::time_point()> &adjusted_time_callback,
531 
535 bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
536  const Consensus::Params &consensusParams);
537 
539 arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader> &headers);
540 
541 enum class VerifyDBResult {
542  SUCCESS,
544  INTERRUPTED,
547 };
548 
553 class CVerifyDB {
554 public:
555  CVerifyDB();
556 
557  ~CVerifyDB();
558 
559  [[nodiscard]] VerifyDBResult VerifyDB(Chainstate &chainstate,
560  CCoinsView &coinsview,
561  int nCheckLevel, int nCheckDepth)
563 };
564 
567 
577 class CoinsViews {
578 public:
582 
586 
589  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
590 
599  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory,
600  bool should_wipe);
601 
603  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
604 };
605 
608  CRITICAL = 2,
610  LARGE = 1,
611  OK = 0
612 };
613 
628 class Chainstate {
629 protected:
635 
641  std::atomic<int32_t> nBlockSequenceId{1};
643  int32_t nBlockReverseSequenceId = -1;
645  arith_uint256 nLastPreciousChainwork = 0;
646 
653  mutable std::atomic<bool> m_cached_finished_ibd{false};
654 
658 
661  std::unique_ptr<CoinsViews> m_coins_views;
662 
675  bool m_disabled GUARDED_BY(::cs_main){false};
676 
678 
683  const CBlockIndex *m_avalancheFinalizedBlockIndex
684  GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
685 
692  CRollingBloomFilter m_filterParkingPoliciesApplied =
693  CRollingBloomFilter{1000, 0.000001};
694 
695  CBlockIndex const *m_best_fork_tip = nullptr;
696  CBlockIndex const *m_best_fork_base = nullptr;
697 
698 public:
702 
707 
708  explicit Chainstate(
709  CTxMemPool *mempool, node::BlockManager &blockman,
710  ChainstateManager &chainman,
711  std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
712 
719  void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
720  std::string leveldb_name = "chainstate");
721 
724  void InitCoinsCache(size_t cache_size_bytes)
726 
730  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
732  return m_coins_views && m_coins_views->m_cacheview;
733  }
734 
738 
745  const std::optional<BlockHash> m_from_snapshot_blockhash{};
746 
750  return m_from_snapshot_blockhash.has_value();
751  }
752 
760  std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
761 
765  Assert(m_coins_views);
766  return *Assert(m_coins_views->m_cacheview);
767  }
768 
772  return Assert(m_coins_views)->m_dbview;
773  }
774 
776  CTxMemPool *GetMempool() { return m_mempool; }
777 
783  return Assert(m_coins_views)->m_catcherview;
784  }
785 
787  void ResetCoinsViews() { m_coins_views.reset(); }
788 
790  bool HasCoinsViews() const { return (bool)m_coins_views; }
791 
793  size_t m_coinsdb_cache_size_bytes{0};
794 
796  size_t m_coinstip_cache_size_bytes{0};
797 
800  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
802 
834  void LoadExternalBlockFile(FILE *fileIn, FlatFilePos *dbp = nullptr,
835  std::multimap<BlockHash, FlatFilePos>
836  *blocks_with_unknown_parent = nullptr)
837  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
838  !cs_avalancheFinalizedBlockIndex);
839 
851  bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
852  int nManualPruneHeight = 0);
853 
855  void ForceFlushStateToDisk();
856 
859  void PruneAndFlush();
860 
887  bool ActivateBestChain(BlockValidationState &state,
888  std::shared_ptr<const CBlock> pblock = nullptr,
889  bool skip_checkblockindex = false)
890  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
891  !cs_avalancheFinalizedBlockIndex)
893 
894  bool AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
895  BlockValidationState &state, bool fRequested,
896  const FlatFilePos *dbp, bool *fNewBlock,
897  bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
898 
899  // Block (dis)connection on a given view:
900  DisconnectResult DisconnectBlock(const CBlock &block,
901  const CBlockIndex *pindex,
902  CCoinsViewCache &view)
904  bool ConnectBlock(const CBlock &block, BlockValidationState &state,
905  CBlockIndex *pindex, CCoinsViewCache &view,
906  BlockValidationOptions options,
907  Amount *blockFees = nullptr, bool fJustCheck = false)
909 
910  // Apply the effects of a block disconnection on the UTXO set.
911  bool DisconnectTip(BlockValidationState &state,
912  DisconnectedBlockTransactions *disconnectpool)
914 
915  // Manual block validity manipulation:
921  bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex)
922  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
923  !cs_avalancheFinalizedBlockIndex)
926  bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex)
928  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
929  !cs_avalancheFinalizedBlockIndex);
931  bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex)
933  EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
934  !cs_avalancheFinalizedBlockIndex);
935 
939  bool AvalancheFinalizeBlock(CBlockIndex *pindex)
940  EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
941 
945  void ClearAvalancheFinalizedBlock()
946  EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
947 
951  bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
952  EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
953 
955  void ResetBlockFailureFlags(CBlockIndex *pindex)
957  template <typename F>
958  bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
960  template <typename F, typename C, typename AC>
961  void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
962  C fChild, AC fAncestorWasChanged)
964 
966  void UnparkBlockAndChildren(CBlockIndex *pindex)
968 
970  void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
971 
973  bool ReplayBlocks();
974 
979  bool LoadGenesisBlock();
980 
981  void PruneBlockIndexCandidates();
982 
983  void UnloadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
984 
989  bool IsInitialBlockDownload() const;
990 
992  const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
994 
1001  void CheckBlockIndex();
1002 
1004  void
1005  LoadMempool(const fs::path &load_path,
1006  fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
1007 
1010  bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1011 
1015  CoinsCacheSizeState GetCoinsCacheSizeState()
1017 
1019  GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
1020  size_t max_mempool_size_bytes)
1022 
1024 
1027  RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1028  return m_mempool ? &m_mempool->cs : nullptr;
1029  }
1030 
1031 private:
1032  bool ActivateBestChainStep(BlockValidationState &state,
1033  CBlockIndex *pindexMostWork,
1034  const std::shared_ptr<const CBlock> &pblock,
1035  bool &fInvalidFound, ConnectTrace &connectTrace)
1036  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs,
1037  !cs_avalancheFinalizedBlockIndex);
1038  bool ConnectTip(BlockValidationState &state,
1039  BlockPolicyValidationState &blockPolicyState,
1040  CBlockIndex *pindexNew,
1041  const std::shared_ptr<const CBlock> &pblock,
1042  ConnectTrace &connectTrace,
1043  DisconnectedBlockTransactions &disconnectpool)
1044  EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs,
1045  !cs_avalancheFinalizedBlockIndex);
1046  void InvalidBlockFound(CBlockIndex *pindex,
1047  const BlockValidationState &state)
1048  EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1049  CBlockIndex *
1050  FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile)
1051  EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1052  void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
1053  const FlatFilePos &pos)
1055 
1056  bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
1058 
1059  void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
1061 
1062  bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex,
1063  bool invalidate)
1064  EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex,
1065  !cs_avalancheFinalizedBlockIndex);
1066 
1067  void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1068  void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
1070  void InvalidChainFound(CBlockIndex *pindexNew)
1071  EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1072 
1073  const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1075 
1079  void UpdateTip(const CBlockIndex *pindexNew)
1081 
1082  std::chrono::microseconds m_last_write{0};
1083  std::chrono::microseconds m_last_flush{0};
1084 
1089  void InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1090 
1092 };
1093 
1095  SUCCESS,
1096  SKIPPED,
1097 
1098  // Expected assumeutxo configuration data is not found for the height of the
1099  // base block.
1101 
1102  // Failed to generate UTXO statistics (to check UTXO set hash) for the
1103  // background chainstate.
1104  STATS_FAILED,
1105 
1106  // The UTXO set hash of the background validation chainstate does not match
1107  // the one expected by assumeutxo chainparams.
1108  HASH_MISMATCH,
1109 
1110  // The blockhash of the current tip of the background validation chainstate
1111  // does not match the one expected by the snapshot chainstate.
1113 };
1114 
1143 private:
1159  std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
1160 
1170  std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
1171 
1181  Chainstate *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1182 
1183  CBlockIndex *m_best_invalid GUARDED_BY(::cs_main){nullptr};
1184  CBlockIndex *m_best_parked GUARDED_BY(::cs_main){nullptr};
1185 
1187  [[nodiscard]] bool
1188  PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate,
1189  AutoFile &coins_file,
1190  const node::SnapshotMetadata &metadata);
1199  bool AcceptBlockHeader(
1200  const CBlockHeader &block, BlockValidationState &state,
1201  CBlockIndex **ppindex, bool min_pow_checked,
1202  const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1204  friend Chainstate;
1205 
1207  const CBlockIndex *GetSnapshotBaseBlock() const
1209 
1212  std::optional<int> GetSnapshotBaseHeight() const
1214 
1220  bool IsUsable(const Chainstate *const pchainstate) const
1222  return pchainstate && !pchainstate->m_disabled;
1223  }
1224 
1226  SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main){};
1227 
1228 public:
1230 
1231  explicit ChainstateManager(Options options);
1232 
1233  const Config &GetConfig() const { return m_options.config; }
1234 
1235  const CChainParams &GetParams() const {
1236  return m_options.config.GetChainParams();
1237  }
1239  return m_options.config.GetChainParams().GetConsensus();
1240  }
1241  bool ShouldCheckBlockIndex() const {
1242  return *Assert(m_options.check_block_index);
1243  }
1245  return *Assert(m_options.minimum_chain_work);
1246  }
1247  const BlockHash &AssumedValidBlock() const {
1248  return *Assert(m_options.assumed_valid_block);
1249  }
1250 
1264  }
1265 
1267  std::thread m_load_block;
1271 
1291  std::set<CBlockIndex *> m_failed_blocks;
1292 
1297  CBlockIndex *m_best_header GUARDED_BY(::cs_main){nullptr};
1298 
1301  int64_t m_total_coinstip_cache{0};
1302  //
1305  int64_t m_total_coinsdb_cache{0};
1306 
1310  // constructor
1311  Chainstate &InitializeChainstate(CTxMemPool *mempool)
1313 
1315  std::vector<Chainstate *> GetAll();
1316 
1330  [[nodiscard]] bool ActivateSnapshot(AutoFile &coins_file,
1331  const node::SnapshotMetadata &metadata,
1332  bool in_memory);
1333 
1341  SnapshotCompletionResult MaybeCompleteSnapshotValidation(
1342  std::function<void(bilingual_str)> shutdown_fnc =
1343  [](bilingual_str msg) { AbortNode(msg.original, msg); })
1345 
1347  Chainstate &ActiveChainstate() const;
1349  return ActiveChainstate().m_chain;
1350  }
1351  int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1352  return ActiveChain().Height();
1353  }
1355  return ActiveChain().Tip();
1356  }
1357 
1360  return m_blockman.m_block_index;
1361  }
1362 
1365  bool IsSnapshotActive() const;
1366 
1367  std::optional<BlockHash> SnapshotBlockhash() const;
1368 
1371  return m_snapshot_chainstate && m_ibd_chainstate &&
1372  m_ibd_chainstate->m_disabled;
1373  }
1374 
1402  bool ProcessNewBlock(const std::shared_ptr<const CBlock> &block,
1403  bool force_processing, bool min_pow_checked,
1404  bool *new_block) LOCKS_EXCLUDED(cs_main);
1405 
1421  bool ProcessNewBlockHeaders(
1422  const std::vector<CBlockHeader> &block, bool min_pow_checked,
1423  BlockValidationState &state, const CBlockIndex **ppindex = nullptr,
1424  const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1426 
1435  [[nodiscard]] MempoolAcceptResult
1436  ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1438 
1441  bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1442 
1445  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1446 
1453  void ReportHeadersPresync(const arith_uint256 &work, int64_t height,
1454  int64_t timestamp);
1455 
1458  bool DetectSnapshotChainstate(CTxMemPool *mempool)
1460 
1461  void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1462 
1465  Chainstate &ActivateExistingSnapshot(CTxMemPool *mempool,
1466  BlockHash base_blockhash)
1468 
1478  bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1479 };
1480 
1482 template <typename DEP>
1483 bool DeploymentActiveAfter(const CBlockIndex *pindexPrev,
1484  const ChainstateManager &chainman, DEP dep) {
1485  return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep);
1486 }
1487 
1488 template <typename DEP>
1490  const ChainstateManager &chainman, DEP dep) {
1491  return DeploymentActiveAt(index, chainman.GetConsensus(), dep);
1492 }
1493 
1501 const AssumeutxoData *ExpectedAssumeutxo(const int height,
1502  const CChainParams &params);
1503 
1504 #endif // BITCOIN_VALIDATION_H
int flags
Definition: bitcoin-tx.cpp:533
@ UNKNOWN
Unused.
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:84
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:528
uint64_t getExcessiveBlockSize() const
Definition: validation.h:153
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:138
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition: validation.h:132
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:145
BlockValidationOptions(const Config &config)
Definition: validation.cpp:113
bool shouldValidatePoW() const
Definition: validation.h:151
uint64_t excessiveBlockSize
Definition: validation.h:125
bool shouldValidateMerkleRoot() const
Definition: validation.h:152
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
An in-memory indexed chain of blocks.
Definition: chain.h:140
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:74
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:203
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:56
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:339
Abstract view on the open txout dataset.
Definition: coins.h:147
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:115
Closure representing one script verification.
Definition: validation.h:450
bool operator()()
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
Definition: validation.h:469
ScriptError GetScriptError() const
Definition: validation.h:494
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:496
uint32_t nFlags
Definition: validation.h:455
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:460
ScriptExecutionMetrics metrics
Definition: validation.h:458
CTxOut m_tx_out
Definition: validation.h:452
void swap(CScriptCheck &check) noexcept
Definition: validation.h:481
bool cacheStore
Definition: validation.h:456
ScriptError error
Definition: validation.h:457
PrecomputedTransactionData txdata
Definition: validation.h:459
const CTransaction * ptxTo
Definition: validation.h:453
unsigned int nIn
Definition: validation.h:454
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:461
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:209
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:296
An output of a transaction.
Definition: transaction.h:128
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:553
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:628
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:760
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:780
CTxMemPool * GetMempool()
Definition: validation.h:776
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:634
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:737
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:790
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:770
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:675
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:657
bool reliesOnAssumedValid()
Return true if this chainstate relies on blocks that are assumed-valid.
Definition: validation.h:749
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:675
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:706
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:661
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:787
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:763
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:701
const CBlockIndex *m_avalancheFinalizedBlockIndex GUARDED_BY(cs_avalancheFinalizedBlockIndex)
The best block via avalanche voting.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1142
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1348
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:1181
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
Definition: validation.h:1184
const CChainParams & GetParams() const
Definition: validation.h:1235
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1244
SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
Definition: validation.h:1226
bool ShouldCheckBlockIndex() const
Definition: validation.h:1241
const Config & GetConfig() const
Definition: validation.h:1233
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1247
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1358
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1370
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1262
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1351
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1354
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:1183
const Options m_options
Definition: validation.h:1266
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1297
std::thread m_load_block
Definition: validation.h:1267
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1315
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:1291
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
const Consensus::Params & GetConsensus() const
Definition: validation.h:1238
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1270
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:317
bool consume_and_check(int consumed)
Definition: validation.h:324
std::atomic< int64_t > remaining
Definition: validation.h:319
CheckInputsLimiter(int64_t limit)
Definition: validation.h:322
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:577
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(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Definition: config.h:17
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
Different type to mark Mutex at global scope.
Definition: sync.h:144
static TxSigCheckLimiter getDisabled()
Definition: validation.h:345
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition: validation.h:340
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition: validation.h:337
bool IsValid() const
Definition: validation.h:112
256-bit unsigned big integer.
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:68
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:21
256-bit opaque blob.
Definition: uint256.h:129
static const uint64_t MAX_TX_SIGCHECKS
Allowed number of signature check operations per transaction.
Definition: consensus.h:22
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
DisconnectResult
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
unsigned int nHeight
LockPoints lp
static void pool cs
Filesystem operations and types.
Definition: fs.h:20
Bridge operations to C stdio.
Definition: fs.cpp:26
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:28
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: fs.h:198
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, FopenFn mockable_fopen_function)
Definition: init.h:28
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:59
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:38
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
@ PERIODIC
Called by RandAddPeriodic()
ScriptError
Definition: script_error.h:11
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Definition: amount.h:19
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:105
Holds various statistics on transactions within a chain.
Definition: chainparams.h:61
Parameters that influence chain consensus.
Definition: params.h:34
Validation result for a single transaction mempool acceptance.
Definition: validation.h:185
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition: validation.h:204
const ResultType m_result_type
Definition: validation.h:195
static MempoolAcceptResult Success(int64_t vsize, Amount fees)
Constructor for success case.
Definition: validation.h:212
MempoolAcceptResult(ResultType result_type, int64_t vsize, Amount fees)
Generic constructor for success cases.
Definition: validation.h:236
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:228
const TxValidationState m_state
Definition: validation.h:196
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:187
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:207
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:220
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:206
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:244
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition: validation.h:264
std::map< const TxId, const MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:253
PackageMempoolAcceptResult(PackageValidationState state, std::map< const TxId, const MempoolAcceptResult > &&results)
Definition: validation.h:255
const PackageValidationState m_state
Definition: validation.h:245
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:325
Struct for holding cumulative results from executing a script or a sequence of scripts.
A TxId is the identifier of a transaction.
Definition: txid.h:14
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:55
#define LOCK_RETURNED(x)
Definition: threadsafety.h:54
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition: time.h:31
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex *active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
AssertLockHeld(pool.cs)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
GlobalMutex g_best_block_mutex
Definition: validation.cpp:109
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:110
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
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
Definition: validation.h:110
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks, CheckInputsLimiter *pBlockLimitSigChecks, std::vector< CScriptCheck > *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:96
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:94
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:1483
SnapshotCompletionResult
Definition: validation.h:1094
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:82
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &params)
Return the expected assumeutxo value for a given height, if one exists.
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:113
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:84
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false, unsigned int heightOverride=0) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex *active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(boo TestBlockValidity)(BlockValidationState &state, const CChainParams &params, Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev, const std::function< NodeClock::time_point()> &adjusted_time_callback, BlockValidationOptions validationOptions) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: validation.h:526
VerifyDBResult
Definition: validation.h:541
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:100
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:140
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
CoinsCacheSizeState
Definition: validation.h:606
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1489
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:95
FlushStateMode
Definition: validation.h:566
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:111
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:86
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:89