Bitcoin ABC 0.34.5
P2P Digital Currency
Loading...
Searching...
No Matches
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>
18#include <chain.h>
19#include <checkqueue.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 <kernel/chain.h>
28#include <kernel/chainparams.h>
30#include <kernel/cs_main.h>
31#include <node/blockstorage.h>
32#include <policy/packages.h>
33#include <script/script_error.h>
34#include <sync.h>
35#include <txdb.h>
36#include <txmempool.h> // For CTxMemPool::cs
37#include <uint256.h>
38#include <util/check.h>
39#include <util/fs.h>
40#include <util/result.h>
41#include <util/time.h>
42#include <util/translation.h>
43
44#include <atomic>
45#include <cstdint>
46#include <map>
47#include <memory>
48#include <optional>
49#include <set>
50#include <string>
51#include <type_traits>
52#include <utility>
53#include <vector>
54
56class CChainParams;
57class Chainstate;
59class CScriptCheck;
60class CTxMemPool;
61class CTxUndo;
63
64struct ChainTxData;
65struct FlatFilePos;
67struct LockPoints;
68struct AssumeutxoData;
69namespace node {
70class SnapshotMetadata;
71} // namespace node
72namespace Consensus {
73struct Params;
74} // namespace Consensus
75namespace avalanche {
76class Processor;
77} // namespace avalanche
78namespace util {
79class SignalInterrupt;
80} // namespace util
81
82#define MIN_TRANSACTION_SIZE (::GetSerializeSize(CTransaction{}))
83
88static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
89static const signed int DEFAULT_CHECKBLOCKS = 6;
90static constexpr int DEFAULT_CHECKLEVEL{3};
104static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
105
107static constexpr int MAX_SCRIPTCHECK_THREADS{15};
108
111
113extern std::condition_variable g_best_block_cv;
115extern const CBlockIndex *g_best_block;
116
118extern const std::vector<std::string> CHECKLEVEL_DOC;
119
121private:
123 bool checkPoW : 1;
125
126public:
127 // Do full validation by default
128 explicit BlockValidationOptions(const Config &config);
129 explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
130 bool _checkPow = true,
131 bool _checkMerkleRoot = true)
132 : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
133 checkMerkleRoot(_checkMerkleRoot) {}
134
135 BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
136 BlockValidationOptions ret = *this;
137 ret.checkPoW = _checkPoW;
138 return ret;
139 }
140
142 withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
143 BlockValidationOptions ret = *this;
144 ret.checkMerkleRoot = _checkMerkleRoot;
145 return ret;
146 }
147
148 bool shouldValidatePoW() const { return checkPoW; }
150 uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
151};
152
153Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
154
155bool FatalError(kernel::Notifications &notifications,
156 BlockValidationState &state, const std::string &strMessage,
157 const bilingual_str &userMessage = {});
158
163double GuessVerificationProgress(const ChainTxData &data,
164 const CBlockIndex *pindex);
165
167void PruneBlockFilesManual(Chainstate &active_chainstate,
168 int nManualPruneHeight);
169
170// clang-format off
193// clang-format on
196 enum class ResultType {
198 VALID,
200 INVALID,
203 };
206
209
214 const std::optional<int64_t> m_vsize;
216 const std::optional<Amount> m_base_fees;
224 const std::optional<CFeeRate> m_effective_feerate;
231 const std::optional<std::vector<TxId>> m_txids_fee_calculations;
232
234 return MempoolAcceptResult(state);
235 }
236
238 FeeFailure(TxValidationState state, CFeeRate effective_feerate,
239 const std::vector<TxId> &txids_fee_calculations) {
240 return MempoolAcceptResult(state, effective_feerate,
241 txids_fee_calculations);
242 }
243
246 Success(int64_t vsize, Amount fees, CFeeRate effective_feerate,
247 const std::vector<TxId> &txids_fee_calculations) {
248 return MempoolAcceptResult(ResultType::VALID, vsize, fees,
249 effective_feerate, txids_fee_calculations);
250 }
251
256 static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees) {
257 return MempoolAcceptResult(vsize, fees);
258 }
259
260 // Private constructors. Use static methods MempoolAcceptResult::Success,
261 // etc. to construct.
262private:
266 m_base_fees(std::nullopt) {
267 // Can be invalid or error
268 Assume(!state.IsValid());
269 }
270
273 ResultType result_type, int64_t vsize, Amount fees,
274 CFeeRate effective_feerate,
275 const std::vector<TxId> &txids_fee_calculations)
276 : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees),
277 m_effective_feerate(effective_feerate),
278 m_txids_fee_calculations(txids_fee_calculations) {}
279
282 TxValidationState state, CFeeRate effective_feerate,
283 const std::vector<TxId> &txids_fee_calculations)
285 m_effective_feerate(effective_feerate),
286 m_txids_fee_calculations(txids_fee_calculations) {}
287
289 explicit MempoolAcceptResult(int64_t vsize, Amount fees)
291 m_base_fees(fees) {}
292};
293
306 std::map<TxId, MempoolAcceptResult> m_tx_results;
307
310 std::map<TxId, MempoolAcceptResult> &&results)
311 : m_state{state}, m_tx_results(std::move(results)) {}
312
317 explicit PackageMempoolAcceptResult(const TxId &txid,
318 const MempoolAcceptResult &result)
319 : m_tx_results{{txid, result}} {}
320};
321
345AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx,
346 int64_t accept_time, bool bypass_limits,
347 bool test_accept = false, unsigned int heightOverride = 0)
349
362ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool,
363 const Package &txns, bool test_accept)
365
371protected:
372 std::atomic<int64_t> remaining;
373
374public:
375 explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
376
377 bool consume_and_check(int consumed) {
378 auto newvalue = (remaining -= consumed);
379 return newvalue >= 0;
380 }
381
382 bool check() { return remaining >= 0; }
383};
384
386public:
388
389 // Let's make this bad boy copiable.
392
394 remaining = rhs.remaining.load();
395 return *this;
396 }
397
399 TxSigCheckLimiter txLimiter;
400 // Historically, there has not been a transaction with more than 20k sig
401 // checks on testnet or mainnet, so this effectively disable sigchecks.
402 txLimiter.remaining = 20000;
403 return txLimiter;
404 }
405};
406
433
464 const CCoinsViewCache &view, const uint32_t flags,
465 bool sigCacheStore, bool scriptCacheStore,
466 const PrecomputedTransactionData &txdata,
467 ValidationCache &validation_cache, int &nSigChecksOut,
468 TxSigCheckLimiter &txLimitSigChecks,
469 CheckInputsLimiter *pBlockLimitSigChecks,
470 std::vector<CScriptCheck> *pvChecks)
472
476static inline bool
478 const CCoinsViewCache &view, const uint32_t flags,
479 bool sigCacheStore, bool scriptCacheStore,
480 const PrecomputedTransactionData &txdata,
481 ValidationCache &validation_cache, int &nSigChecksOut)
483 TxSigCheckLimiter nSigChecksTxLimiter;
484 return CheckInputScripts(
485 tx, state, view, flags, sigCacheStore, scriptCacheStore, txdata,
486 validation_cache, nSigChecksOut, nSigChecksTxLimiter, nullptr, nullptr);
487}
488
492void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
493 int nHeight);
494
498void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
499 int nHeight);
500
505std::optional<std::vector<Coin>>
506GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view);
507
526std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
527 const CCoinsView &coins_view,
528 const CTransaction &tx);
529
539bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points);
540
549private:
551 const CTransaction *ptxTo;
552 unsigned int nIn;
553 uint32_t nFlags;
560
561public:
562 CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
563 SignatureCache &signature_cache, unsigned int nInIn,
564 uint32_t nFlagsIn, bool cacheIn,
565 const PrecomputedTransactionData &txdataIn,
566 TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
567 CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
568 : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
569 cacheStore(cacheIn), txdata(txdataIn),
570 m_signature_cache(&signature_cache),
571 pTxLimitSigChecks(pTxLimitSigChecksIn),
572 pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
573
574 CScriptCheck(const CScriptCheck &) = delete;
578
579 std::optional<std::pair<ScriptError, std::string>> operator()();
580
582};
583
584// CScriptCheck is used a lot in std::vector, make sure that's efficient
585static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
586static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
587static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
588
597bool CheckBlock(const CBlock &block, BlockValidationState &state,
598 const Consensus::Params &params,
599 BlockValidationOptions validationOptions);
600
606 BlockValidationState &state, const CChainParams &params,
607 Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
608 const std::function<NodeClock::time_point()> &adjusted_time_callback,
610
614bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
615 const Consensus::Params &consensusParams);
616
620bool IsBlockMutated(const CBlock &block);
621
627CalculateClaimedHeadersWork(const std::vector<CBlockHeader> &headers);
628
636
642private:
644
645public:
647
648public:
649 explicit CVerifyDB(kernel::Notifications &notifications);
650 ~CVerifyDB();
651
652 [[nodiscard]] VerifyDBResult VerifyDB(Chainstate &chainstate,
653 CCoinsView &coinsview,
654 int nCheckLevel, int nCheckDepth)
656};
657
660
671public:
675
679
682 std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
683
687 std::unique_ptr<CCoinsViewCache> m_connect_block_view GUARDED_BY(cs_main);
688
697 CoinsViews(DBParams db_params, CoinsViewOptions options);
698
700 void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
701};
702
705 CRITICAL = 2,
707 LARGE = 1,
708 OK = 0
709};
710
726protected:
732
736
739 std::unique_ptr<CoinsViews> m_coins_views;
740
753 bool m_disabled GUARDED_BY(::cs_main){false};
754
756
761 const CBlockIndex *m_avalancheFinalizedBlockIndex
762 GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
763
770 CRollingBloomFilter m_filterParkingPoliciesApplied =
771 CRollingBloomFilter{1000, 0.000001};
772
773 CBlockIndex const *m_best_fork_tip = nullptr;
774 CBlockIndex const *m_best_fork_base = nullptr;
775
777 const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};
778
779public:
783
788
789 explicit Chainstate(
790 CTxMemPool *mempool, node::BlockManager &blockman,
791 ChainstateManager &chainman,
792 std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
793
799
806 void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
807 std::string leveldb_name = "chainstate");
808
811 void InitCoinsCache(size_t cache_size_bytes)
813
817 bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
819 return m_coins_views && m_coins_views->m_cacheview;
820 }
821
825
832 const std::optional<BlockHash> m_from_snapshot_blockhash{};
833
839 const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
840
848 std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
849
853 Assert(m_coins_views);
854 return *Assert(m_coins_views->m_cacheview);
855 }
856
860 return Assert(m_coins_views)->m_dbview;
861 }
862
864 CTxMemPool *GetMempool() { return m_mempool; }
865
871 return Assert(m_coins_views)->m_catcherview;
872 }
873
875 void ResetCoinsViews() { m_coins_views.reset(); }
876
878 bool HasCoinsViews() const { return (bool)m_coins_views; }
879
881 size_t m_coinsdb_cache_size_bytes{0};
882
884 size_t m_coinstip_cache_size_bytes{0};
885
888 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
890
902 bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
903 int nManualPruneHeight = 0);
904
906 void ForceFlushStateToDisk();
907
910 void PruneAndFlush();
911
932 bool ActivateBestChain(BlockValidationState &state,
933 std::shared_ptr<const CBlock> pblock = nullptr,
934 avalanche::Processor *const avalanche = nullptr)
935 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
936 !cs_avalancheFinalizedBlockIndex)
938
939 // Block (dis)connection on a given view:
940 DisconnectResult DisconnectBlock(const CBlock &block,
941 const CBlockIndex *pindex,
942 CCoinsViewCache &view)
944 bool ConnectBlock(const CBlock &block, BlockValidationState &state,
945 CBlockIndex *pindex, CCoinsViewCache &view,
947 Amount *blockFees = nullptr, bool fJustCheck = false)
949
950 // Apply the effects of a block disconnection on the UTXO set.
951 bool DisconnectTip(BlockValidationState &state,
952 DisconnectedBlockTransactions *disconnectpool)
954
955 // Manual block validity manipulation:
961 bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex,
962 avalanche::Processor *const avalanche = nullptr)
963 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
964 !cs_avalancheFinalizedBlockIndex)
969 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
970 !cs_avalancheFinalizedBlockIndex);
972 bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex)
974 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
975 !cs_avalancheFinalizedBlockIndex);
976
980 bool AvalancheFinalizeBlock(CBlockIndex *pindex,
981 avalanche::Processor &avalanche)
982 EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_avalancheFinalizedBlockIndex);
983
987 void ClearAvalancheFinalizedBlock()
988 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
989
993 bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
994 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
995
997 void SetBlockFailureFlags(CBlockIndex *pindex)
999
1001 void ResetBlockFailureFlags(CBlockIndex *pindex)
1003 template <typename F>
1004 bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
1006 template <typename F, typename C, typename AC>
1007 void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
1008 C fChild, AC fAncestorWasChanged)
1010
1012 void UnparkBlockAndChildren(CBlockIndex *pindex)
1014
1016 void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1017
1019 bool ReplayBlocks();
1020
1025 bool LoadGenesisBlock();
1026
1027 void TryAddBlockIndexCandidate(CBlockIndex *pindex)
1029
1030 void PruneBlockIndexCandidates();
1031
1032 void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1033
1035 const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
1037
1042 bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1043
1047 CoinsCacheSizeState GetCoinsCacheSizeState()
1049
1051 GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
1052 size_t max_mempool_size_bytes)
1054
1055 std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1056
1059 RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1060 return m_mempool ? &m_mempool->cs : nullptr;
1061 }
1062
1063private:
1064 bool ActivateBestChainStep(
1065 BlockValidationState &state, CBlockIndex *pindexMostWork,
1066 const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
1067 const avalanche::Processor *const avalanche = nullptr,
1070 !cs_avalancheFinalizedBlockIndex);
1071 bool ConnectTip(BlockValidationState &state,
1072 BlockPolicyValidationState &blockPolicyState,
1073 CBlockIndex *pindexNew,
1074 const std::shared_ptr<const CBlock> &pblock,
1075 DisconnectedBlockTransactions &disconnectpool,
1076 const avalanche::Processor *const avalanche = nullptr,
1077 ChainstateRole chainstate_role = ChainstateRole::NORMAL)
1079 !cs_avalancheFinalizedBlockIndex);
1080 void InvalidBlockFound(CBlockIndex *pindex,
1081 const BlockValidationState &state)
1082 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1083 CBlockIndex *
1084 FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile,
1085 bool fAutoUnpark)
1086 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1087
1088 bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
1090
1091 void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
1093
1094 bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex,
1095 bool invalidate)
1096 EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex,
1097 !cs_avalancheFinalizedBlockIndex);
1098
1099 void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1100 void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
1102 void InvalidChainFound(CBlockIndex *pindexNew)
1103 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1104
1105 const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1107
1111 void UpdateTip(const CBlockIndex *pindexNew)
1113
1114 NodeClock::time_point m_next_write{NodeClock::time_point::max()};
1115
1120 [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk()
1122
1124};
1125
1127 SUCCESS,
1128 SKIPPED,
1129
1130 // Expected assumeutxo configuration data is not found for the height of the
1131 // base block.
1133
1134 // Failed to generate UTXO statistics (to check UTXO set hash) for the
1135 // background chainstate.
1137
1138 // The UTXO set hash of the background validation chainstate does not match
1139 // the one expected by assumeutxo chainparams.
1141
1142 // The blockhash of the current tip of the background validation chainstate
1143 // does not match the one expected by the snapshot chainstate.
1145};
1146
1175private:
1191 std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
1192
1202 std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
1203
1210 Chainstate *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1211
1212 CBlockIndex *m_best_invalid GUARDED_BY(::cs_main){nullptr};
1213 CBlockIndex *m_best_parked GUARDED_BY(::cs_main){nullptr};
1214
1216 CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex()){nullptr};
1217
1218 bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex());
1219
1227 [[nodiscard]] bool
1228 PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate,
1229 AutoFile &coins_file,
1230 const node::SnapshotMetadata &metadata);
1239 bool AcceptBlockHeader(
1240 const CBlockHeader &block, BlockValidationState &state,
1241 CBlockIndex **ppindex, bool min_pow_checked,
1242 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1245
1251 bool IsUsable(const Chainstate *const pchainstate) const
1253 return pchainstate && !pchainstate->m_disabled;
1254 }
1255
1257 SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main){};
1258
1262
1265 SteadyClock::duration GUARDED_BY(::cs_main) time_check{};
1266 SteadyClock::duration GUARDED_BY(::cs_main) time_forks{};
1267 SteadyClock::duration GUARDED_BY(::cs_main) time_connect{};
1268 SteadyClock::duration GUARDED_BY(::cs_main) time_verify{};
1269 SteadyClock::duration GUARDED_BY(::cs_main) time_index{};
1270 SteadyClock::duration GUARDED_BY(::cs_main) time_total{};
1271 int64_t GUARDED_BY(::cs_main) num_blocks_total{0};
1272 SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total{};
1273 SteadyClock::duration GUARDED_BY(::cs_main) time_flush{};
1274 SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate{};
1275 SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect{};
1276
1277public:
1279
1280 explicit ChainstateManager(const util::SignalInterrupt &interrupt,
1281 Options options,
1282 node::BlockManager::Options blockman_options);
1283
1286 std::function<void()> snapshot_download_completed = std::function<void()>();
1287
1288 const Config &GetConfig() const { return m_options.config; }
1289
1290 const CChainParams &GetParams() const {
1291 return m_options.config.GetChainParams();
1292 }
1294 return m_options.config.GetChainParams().GetConsensus();
1295 }
1296 bool ShouldCheckBlockIndex() const;
1298 return *Assert(m_options.minimum_chain_work);
1299 }
1301 return *Assert(m_options.assumed_valid_block);
1302 }
1304 return m_options.notifications;
1305 }
1306
1313 void CheckBlockIndex();
1314
1327 return ::cs_main;
1328 }
1329
1335
1337
1345 mutable std::atomic<bool> m_cached_finished_ibd{false};
1346
1352 std::atomic<int32_t> nBlockSequenceId{1};
1353
1355 int32_t nBlockReverseSequenceId = -1;
1357 arith_uint256 nLastPreciousChainwork = 0;
1358
1359 // Reset the memory-only sequence counters we use to track block arrival
1360 // (used by tests to reset state)
1363 nBlockSequenceId = 1;
1364 nBlockReverseSequenceId = -1;
1365 }
1366
1386 std::set<CBlockIndex *> m_failed_blocks;
1387
1392 CBlockIndex *m_best_header GUARDED_BY(::cs_main){nullptr};
1393
1396 size_t m_total_coinstip_cache{0};
1397 //
1400 size_t m_total_coinsdb_cache{0};
1401
1405 // constructor
1406 Chainstate &InitializeChainstate(CTxMemPool *mempool)
1408
1410 std::vector<Chainstate *> GetAll();
1411
1425 [[nodiscard]] util::Result<CBlockIndex *>
1426 ActivateSnapshot(AutoFile &coins_file,
1427 const node::SnapshotMetadata &metadata, bool in_memory);
1428
1436 SnapshotCompletionResult MaybeCompleteSnapshotValidation()
1438
1440 const CBlockIndex *GetSnapshotBaseBlock() const
1442
1444 Chainstate &ActiveChainstate() const;
1445 CChain &ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1446 return ActiveChainstate().m_chain;
1447 }
1448 int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1449 return ActiveChain().Height();
1450 }
1452 return ActiveChain().Tip();
1453 }
1454
1455 const CBlockIndex *GetAvalancheFinalizedTip() const;
1456
1459 return IsUsable(m_snapshot_chainstate.get()) &&
1460 IsUsable(m_ibd_chainstate.get());
1461 }
1462
1465 EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1466 return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip()
1467 : nullptr;
1468 }
1469
1472 return m_blockman.m_block_index;
1473 }
1474
1477 bool IsSnapshotActive() const;
1478
1479 std::optional<BlockHash> SnapshotBlockhash() const;
1480
1483 return m_snapshot_chainstate && m_ibd_chainstate &&
1484 m_ibd_chainstate->m_disabled;
1485 }
1486
1491 bool IsInitialBlockDownload() const;
1492
1524 void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp = nullptr,
1525 std::multimap<BlockHash, FlatFilePos>
1526 *blocks_with_unknown_parent = nullptr,
1527 avalanche::Processor *const avalanche = nullptr);
1528
1556 bool ProcessNewBlock(const std::shared_ptr<const CBlock> &block,
1557 bool force_processing, bool min_pow_checked,
1558 bool *new_block,
1559 avalanche::Processor *const avalanche = nullptr)
1561
1577 bool ProcessNewBlockHeaders(
1578 const std::vector<CBlockHeader> &block, bool min_pow_checked,
1579 BlockValidationState &state, const CBlockIndex **ppindex = nullptr,
1580 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1582
1601 bool AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
1602 BlockValidationState &state, bool fRequested,
1603 const FlatFilePos *dbp, bool *fNewBlock,
1604 bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1605
1606 void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
1607 const FlatFilePos &pos)
1609
1618 [[nodiscard]] MempoolAcceptResult
1619 ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1621
1624 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1625
1628 void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1629
1636 void ReportHeadersPresync(const arith_uint256 &work, int64_t height,
1637 int64_t timestamp);
1638
1641 bool DetectSnapshotChainstate(CTxMemPool *mempool)
1643
1644 void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1645
1648 [[nodiscard]] bool DeleteSnapshotChainstate()
1650
1653 Chainstate &ActivateExistingSnapshot(BlockHash base_blockhash)
1655
1665 bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1666
1675 Chainstate &GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1676
1680 std::pair<int, int> GetPruneRange(const Chainstate &chainstate,
1681 int last_height_can_prune)
1683
1686 std::optional<int> GetSnapshotBaseHeight() const
1688
1689 CCheckQueue<CScriptCheck> &GetCheckQueue() { return m_script_check_queue; }
1690
1694 void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1695
1697 bool DumpRecentHeadersTime(const fs::path &filePath) const
1698 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1700 bool LoadRecentHeadersTime(const fs::path &filePath)
1701 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1702};
1703
1705template <typename DEP>
1706bool DeploymentActiveAfter(const CBlockIndex *pindexPrev,
1707 const ChainstateManager &chainman, DEP dep) {
1708 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep);
1709}
1710
1711template <typename DEP>
1713 const ChainstateManager &chainman, DEP dep) {
1714 return DeploymentActiveAt(index, chainman.GetConsensus(), dep);
1715}
1716
1717#endif // BITCOIN_VALIDATION_H
int flags
static void InvalidateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition check.h:87
#define Assume(val)
Assume is the identity function.
Definition check.h:100
static void CheckBlockIndex(benchmark::Bench &bench)
Non-refcounted RAII wrapper for FILE*.
Definition streams.h:433
uint64_t getExcessiveBlockSize() const
Definition validation.h:150
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition validation.h:135
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition validation.h:129
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition validation.h:142
bool shouldValidatePoW() const
Definition validation.h:148
bool shouldValidateMerkleRoot() const
Definition validation.h:149
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:25
An in-memory indexed chain of blocks.
Definition chain.h:138
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition chainparams.h:86
The verifications are represented by a type T, which must provide an operator(), returning an std::op...
Definition checkqueue.h:33
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:357
CCoinsView backed by the coin database (chainstate/)
Definition txdb.h:49
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition coins.h:550
Abstract view on the open txout dataset.
Definition coins.h:303
Fee rate in satoshis per virtualbyte: Amount / vB the feerate is represented internally as FeeFrac.
Definition feerate.h:24
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition bloom.h:115
A hasher class for SHA-256.
Definition sha256.h:13
Closure representing one script verification.
Definition validation.h:548
CScriptCheck & operator=(CScriptCheck &&)=default
SignatureCache * m_signature_cache
Definition validation.h:557
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition validation.h:581
CScriptCheck(const CScriptCheck &)=delete
uint32_t nFlags
Definition validation.h:553
TxSigCheckLimiter * pTxLimitSigChecks
Definition validation.h:558
ScriptExecutionMetrics metrics
Definition validation.h:555
CTxOut m_tx_out
Definition validation.h:550
CScriptCheck(CScriptCheck &&)=default
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, SignatureCache &signature_cache, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
Definition validation.h:562
std::optional< std::pair< ScriptError, std::string > > operator()()
PrecomputedTransactionData txdata
Definition validation.h:556
const CTransaction * ptxTo
Definition validation.h:551
unsigned int nIn
Definition validation.h:552
CheckInputsLimiter * pBlockLimitSigChecks
Definition validation.h:559
CScriptCheck & operator=(const CScriptCheck &)=delete
The basic transaction that is broadcasted on the network and contained in blocks.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition txmempool.h:222
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition txmempool.h:316
An output of a transaction.
Restore the UTXO in a Coin at a given COutPoint.
Definition undo.h:61
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition validation.h:641
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition validation.h:643
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition validation.h:725
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition validation.h:731
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition validation.h:824
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition validation.h:878
CTxMemPool * GetMempool()
Definition validation.h:864
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition validation.h:868
Mutex cs_avalancheFinalizedBlockIndex
Definition validation.h:755
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition validation.h:735
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition validation.h:753
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition validation.h:858
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition validation.h:787
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition validation.h:739
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition validation.h:875
const CBlockIndex *m_avalancheFinalizedBlockIndex GUARDED_BY(cs_avalancheFinalizedBlockIndex)
The best block via avalanche voting.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition validation.h:782
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition validation.h:777
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total
std::unique_ptr< Chainstate > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
node::BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
ValidationCache m_validation_cache
int64_t GUARDED_BY(::cs_main) num_blocks_total
SteadyClock::duration GUARDED_BY(::cs_main) time_index
const Config & GetConfig() const
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect
kernel::Notifications & GetNotifications() const
SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
SteadyClock::duration GUARDED_BY(::cs_main) time_check
Timers and counters used for benchmarking validation in both background and active chainstates.
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
SteadyClock::duration GUARDED_BY(::cs_main) time_total
SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
SteadyClock::duration GUARDED_BY(::cs_main) time_forks
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex())
The last header for which a headerTip notification was issued.
const util::SignalInterrupt & m_interrupt
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
const CChainParams & GetParams() const
const Consensus::Params & GetConsensus() const
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
const arith_uint256 & MinimumChainWork() const
const Options m_options
SteadyClock::duration GUARDED_BY(::cs_main) time_verify
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
const BlockHash & AssumedValidBlock() const
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
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...
SteadyClock::duration GUARDED_BY(::cs_main) time_connect
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
SteadyClock::duration GUARDED_BY(::cs_main) time_flush
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition validation.h:370
bool consume_and_check(int consumed)
Definition validation.h:377
std::atomic< int64_t > remaining
Definition validation.h:372
CheckInputsLimiter(int64_t limit)
Definition validation.h:375
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition validation.h:670
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.
std::unique_ptr< CCoinsViewCache > m_connect_block_view GUARDED_BY(cs_main)
Temporary CCoinsViewCache layered on top of m_cacheview and passed to ConnectBlock().
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
cache implements a cache with properties similar to a cuckoo-set.
Different type to mark Mutex at global scope.
Definition sync.h:144
Valid signature cache, to avoid doing expensive ECDSA signature checking twice for every transaction ...
Definition sigcache.h:33
static TxSigCheckLimiter getDisabled()
Definition validation.h:398
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition validation.h:393
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition validation.h:390
Convenience class for initializing and passing the script execution cache and signature cache.
Definition validation.h:411
CuckooCache::cache< ScriptCacheElement, ScriptCacheHasher > m_script_execution_cache
Definition validation.h:419
ValidationCache & operator=(const ValidationCache &)=delete
ValidationCache(const ValidationCache &)=delete
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
Definition validation.h:429
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
Definition validation.h:415
SignatureCache m_signature_cache
Definition validation.h:420
bool IsValid() const
Definition validation.h:119
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...
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
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
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for the next block.
bool DeploymentActiveAt(const CBlockIndex &index, const Consensus::Params &params, Consensus::BuriedDeployment dep)
Determine if a deployment is active for this block.
DisconnectResult
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition chain.h:14
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
unsigned int nHeight
static void pool cs
Filesystem operations and types.
Definition fs.h:20
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition rcu.h:259
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition packages.h:40
std::shared_ptr< const CTransaction > CTransactionRef
Holds configuration for use during UTXO snapshot load and validation.
Definition chainparams.h:48
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:108
Holds various statistics on transactions within a chain.
Definition chainparams.h:73
User-controlled performance and debug options.
Definition txdb.h:40
Parameters that influence chain consensus.
Definition params.h:34
Application-specific storage settings.
Definition dbwrapper.h:34
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition validation.h:194
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition validation.h:214
MempoolAcceptResult(ResultType result_type, int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Generic constructor for success cases.
Definition validation.h:272
const ResultType m_result_type
Result type.
Definition validation.h:205
const std::optional< std::vector< TxId > > m_txids_fee_calculations
Contains the txids of the transactions used for fee-related checks.
Definition validation.h:231
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition validation.h:264
const TxValidationState m_state
Contains information about why the transaction failed.
Definition validation.h:208
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for fee-related failure case.
Definition validation.h:281
ResultType
Used to indicate the results of mempool validation.
Definition validation.h:196
@ MEMPOOL_ENTRY
Valid, transaction was already in the mempool.
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition validation.h:233
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition validation.h:224
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition validation.h:238
static MempoolAcceptResult Success(int64_t vsize, Amount fees, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for success case.
Definition validation.h:246
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition validation.h:256
MempoolAcceptResult(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition validation.h:289
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition validation.h:216
Mockable clock in the context of tests, otherwise the system clock.
Definition time.h:20
std::chrono::time_point< NodeClock > time_point
Definition time.h:21
Validation result for package mempool acceptance.
Definition validation.h:297
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition validation.h:317
PackageMempoolAcceptResult(PackageValidationState state, std::map< TxId, MempoolAcceptResult > &&results)
Definition validation.h:308
PackageValidationState m_state
Definition validation.h:298
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition validation.h:306
Precompute sighash midstate to avoid quadratic hashing.
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
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 AssertLockHeld(cs)
Definition sync.h:146
#define EXCLUSIVE_LOCKS_REQUIRED(...)
#define LOCKS_EXCLUDED(...)
#define LOCK_RETURNED(x)
std::chrono::time_point< std::chrono::steady_clock, std::chrono::milliseconds > SteadyMilliseconds
Definition time.h:33
GlobalMutex g_best_block_mutex
bool 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)
Check a block is completely valid from start to finish (only works on top of our current best block)
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition validation.h:107
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Calculate LockPoints required to check if transaction will be BIP68 final in the next block to be cre...
static constexpr int DEFAULT_CHECKLEVEL
Definition validation.h:90
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.
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:104
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.
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:88
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
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.
SnapshotCompletionResult
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition validation.h:110
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.
VerifyDBResult
Definition validation.h:629
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'.
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
bool IsBlockMutated(const CBlock &block)
Check if a block has been mutated (with respect to its merkle root).
CoinsCacheSizeState
Definition validation.h:703
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, ValidationCache &validation_cache, 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.
std::optional< std::vector< Coin > > GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view)
Get the coins spent by ptx from the coins_view.
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
arith_uint256 CalculateClaimedHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the claimed work on a given set of headers.
static const signed int DEFAULT_CHECKBLOCKS
Definition validation.h:89
FlushStateMode
Definition validation.h:659
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage={})