Bitcoin ABC 0.34.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>
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
84static const bool DEFAULT_PEERBLOOMFILTERS = true;
85
90static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
91static const signed int DEFAULT_CHECKBLOCKS = 6;
92static constexpr int DEFAULT_CHECKLEVEL{3};
106static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
107
109static constexpr int MAX_SCRIPTCHECK_THREADS{15};
110
113
115extern std::condition_variable g_best_block_cv;
117extern const CBlockIndex *g_best_block;
118
120extern const std::vector<std::string> CHECKLEVEL_DOC;
121
123private:
125 bool checkPoW : 1;
127
128public:
129 // Do full validation by default
130 explicit BlockValidationOptions(const Config &config);
131 explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
132 bool _checkPow = true,
133 bool _checkMerkleRoot = true)
134 : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
135 checkMerkleRoot(_checkMerkleRoot) {}
136
137 BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
138 BlockValidationOptions ret = *this;
139 ret.checkPoW = _checkPoW;
140 return ret;
141 }
142
144 withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
145 BlockValidationOptions ret = *this;
146 ret.checkMerkleRoot = _checkMerkleRoot;
147 return ret;
148 }
149
150 bool shouldValidatePoW() const { return checkPoW; }
152 uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
153};
154
155Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
156
157bool FatalError(kernel::Notifications &notifications,
158 BlockValidationState &state, const std::string &strMessage,
159 const bilingual_str &userMessage = {});
160
165double GuessVerificationProgress(const ChainTxData &data,
166 const CBlockIndex *pindex);
167
169void PruneBlockFilesManual(Chainstate &active_chainstate,
170 int nManualPruneHeight);
171
172// clang-format off
195// clang-format on
198 enum class ResultType {
200 VALID,
202 INVALID,
204 MEMPOOL_ENTRY,
205 };
208
211
216 const std::optional<int64_t> m_vsize;
218 const std::optional<Amount> m_base_fees;
226 const std::optional<CFeeRate> m_effective_feerate;
233 const std::optional<std::vector<TxId>> m_txids_fee_calculations;
234
236 return MempoolAcceptResult(state);
237 }
238
240 FeeFailure(TxValidationState state, CFeeRate effective_feerate,
241 const std::vector<TxId> &txids_fee_calculations) {
242 return MempoolAcceptResult(state, effective_feerate,
243 txids_fee_calculations);
244 }
245
248 Success(int64_t vsize, Amount fees, CFeeRate effective_feerate,
249 const std::vector<TxId> &txids_fee_calculations) {
250 return MempoolAcceptResult(ResultType::VALID, vsize, fees,
251 effective_feerate, txids_fee_calculations);
252 }
253
258 static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees) {
259 return MempoolAcceptResult(vsize, fees);
260 }
261
262 // Private constructors. Use static methods MempoolAcceptResult::Success,
263 // etc. to construct.
264private:
267 : m_result_type(ResultType::INVALID), m_state(state),
268 m_base_fees(std::nullopt) {
269 // Can be invalid or error
270 Assume(!state.IsValid());
271 }
272
275 ResultType result_type, int64_t vsize, Amount fees,
276 CFeeRate effective_feerate,
277 const std::vector<TxId> &txids_fee_calculations)
278 : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees),
279 m_effective_feerate(effective_feerate),
280 m_txids_fee_calculations(txids_fee_calculations) {}
281
284 TxValidationState state, CFeeRate effective_feerate,
285 const std::vector<TxId> &txids_fee_calculations)
286 : m_result_type(ResultType::INVALID), m_state(state),
287 m_effective_feerate(effective_feerate),
288 m_txids_fee_calculations(txids_fee_calculations) {}
289
291 explicit MempoolAcceptResult(int64_t vsize, Amount fees)
292 : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize},
293 m_base_fees(fees) {}
294};
295
308 std::map<TxId, MempoolAcceptResult> m_tx_results;
309
312 std::map<TxId, MempoolAcceptResult> &&results)
313 : m_state{state}, m_tx_results(std::move(results)) {}
314
319 explicit PackageMempoolAcceptResult(const TxId &txid,
320 const MempoolAcceptResult &result)
321 : m_tx_results{{txid, result}} {}
322};
323
347AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx,
348 int64_t accept_time, bool bypass_limits,
349 bool test_accept = false, unsigned int heightOverride = 0)
351
364ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool,
365 const Package &txns, bool test_accept)
367
373protected:
374 std::atomic<int64_t> remaining;
375
376public:
377 explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
378
379 bool consume_and_check(int consumed) {
380 auto newvalue = (remaining -= consumed);
381 return newvalue >= 0;
382 }
383
384 bool check() { return remaining >= 0; }
385};
386
388public:
390
391 // Let's make this bad boy copiable.
393 : CheckInputsLimiter(rhs.remaining.load()) {}
394
396 remaining = rhs.remaining.load();
397 return *this;
398 }
399
401 TxSigCheckLimiter txLimiter;
402 // Historically, there has not been a transaction with more than 20k sig
403 // checks on testnet or mainnet, so this effectively disable sigchecks.
404 txLimiter.remaining = 20000;
405 return txLimiter;
406 }
407};
408
414private:
418
419public:
423
424 ValidationCache(size_t script_execution_cache_bytes,
425 size_t signature_cache_bytes);
426
429
433 }
434};
435
465bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
466 const CCoinsViewCache &view, const uint32_t flags,
467 bool sigCacheStore, bool scriptCacheStore,
468 const PrecomputedTransactionData &txdata,
469 ValidationCache &validation_cache, int &nSigChecksOut,
470 TxSigCheckLimiter &txLimitSigChecks,
471 CheckInputsLimiter *pBlockLimitSigChecks,
472 std::vector<CScriptCheck> *pvChecks)
474
478static inline bool
479CheckInputScripts(const CTransaction &tx, TxValidationState &state,
480 const CCoinsViewCache &view, const uint32_t flags,
481 bool sigCacheStore, bool scriptCacheStore,
482 const PrecomputedTransactionData &txdata,
483 ValidationCache &validation_cache, int &nSigChecksOut)
485 TxSigCheckLimiter nSigChecksTxLimiter;
486 return CheckInputScripts(
487 tx, state, view, flags, sigCacheStore, scriptCacheStore, txdata,
488 validation_cache, nSigChecksOut, nSigChecksTxLimiter, nullptr, nullptr);
489}
490
494void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
495 int nHeight);
496
500void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
501 int nHeight);
502
507std::optional<std::vector<Coin>>
508GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view);
509
528std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
529 const CCoinsView &coins_view,
530 const CTransaction &tx);
531
541bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points);
542
551private:
553 const CTransaction *ptxTo;
554 unsigned int nIn;
555 uint32_t nFlags;
562
563public:
564 CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
565 SignatureCache &signature_cache, unsigned int nInIn,
566 uint32_t nFlagsIn, bool cacheIn,
567 const PrecomputedTransactionData &txdataIn,
568 TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
569 CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
570 : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
571 cacheStore(cacheIn), txdata(txdataIn),
572 m_signature_cache(&signature_cache),
573 pTxLimitSigChecks(pTxLimitSigChecksIn),
574 pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
575
576 CScriptCheck(const CScriptCheck &) = delete;
580
581 std::optional<std::pair<ScriptError, std::string>> operator()();
582
584};
585
586// CScriptCheck is used a lot in std::vector, make sure that's efficient
587static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
588static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
589static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
590
599bool CheckBlock(const CBlock &block, BlockValidationState &state,
600 const Consensus::Params &params,
601 BlockValidationOptions validationOptions);
602
608 BlockValidationState &state, const CChainParams &params,
609 Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
610 const std::function<NodeClock::time_point()> &adjusted_time_callback,
612
616bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
617 const Consensus::Params &consensusParams);
618
622bool IsBlockMutated(const CBlock &block);
623
629CalculateClaimedHeadersWork(const std::vector<CBlockHeader> &headers);
630
631enum class VerifyDBResult {
632 SUCCESS,
634 INTERRUPTED,
637};
638
644private:
646
647public:
649
650public:
651 explicit CVerifyDB(kernel::Notifications &notifications);
652 ~CVerifyDB();
653
654 [[nodiscard]] VerifyDBResult VerifyDB(Chainstate &chainstate,
655 CCoinsView &coinsview,
656 int nCheckLevel, int nCheckDepth)
658};
659
661enum class FlushStateMode { NONE, IF_NEEDED, PERIODIC, ALWAYS };
662
673public:
677
681
684 std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
685
689 std::unique_ptr<CCoinsViewCache> m_connect_block_view GUARDED_BY(cs_main);
690
699 CoinsViews(DBParams db_params, CoinsViewOptions options);
700
702 void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
703};
704
707 CRITICAL = 2,
709 LARGE = 1,
710 OK = 0
711};
712
728protected:
734
738
741 std::unique_ptr<CoinsViews> m_coins_views;
742
755 bool m_disabled GUARDED_BY(::cs_main){false};
756
758
763 const CBlockIndex *m_avalancheFinalizedBlockIndex
764 GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
765
772 CRollingBloomFilter m_filterParkingPoliciesApplied =
773 CRollingBloomFilter{1000, 0.000001};
774
775 CBlockIndex const *m_best_fork_tip = nullptr;
776 CBlockIndex const *m_best_fork_base = nullptr;
777
779 const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};
780
781public:
785
790
791 explicit Chainstate(
792 CTxMemPool *mempool, node::BlockManager &blockman,
793 ChainstateManager &chainman,
794 std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
795
801
808 void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
809 std::string leveldb_name = "chainstate");
810
813 void InitCoinsCache(size_t cache_size_bytes)
815
819 bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
821 return m_coins_views && m_coins_views->m_cacheview;
822 }
823
827
834 const std::optional<BlockHash> m_from_snapshot_blockhash{};
835
841 const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
842
850 std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
851
855 Assert(m_coins_views);
856 return *Assert(m_coins_views->m_cacheview);
857 }
858
862 return Assert(m_coins_views)->m_dbview;
863 }
864
866 CTxMemPool *GetMempool() { return m_mempool; }
867
873 return Assert(m_coins_views)->m_catcherview;
874 }
875
877 void ResetCoinsViews() { m_coins_views.reset(); }
878
880 bool HasCoinsViews() const { return (bool)m_coins_views; }
881
883 size_t m_coinsdb_cache_size_bytes{0};
884
886 size_t m_coinstip_cache_size_bytes{0};
887
890 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
892
904 bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
905 int nManualPruneHeight = 0);
906
908 void ForceFlushStateToDisk();
909
912 void PruneAndFlush();
913
934 bool ActivateBestChain(BlockValidationState &state,
935 std::shared_ptr<const CBlock> pblock = nullptr,
936 avalanche::Processor *const avalanche = nullptr)
937 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
938 !cs_avalancheFinalizedBlockIndex)
940
941 // Block (dis)connection on a given view:
942 DisconnectResult DisconnectBlock(const CBlock &block,
943 const CBlockIndex *pindex,
944 CCoinsViewCache &view)
946 bool ConnectBlock(const CBlock &block, BlockValidationState &state,
947 CBlockIndex *pindex, CCoinsViewCache &view,
949 Amount *blockFees = nullptr, bool fJustCheck = false)
951
952 // Apply the effects of a block disconnection on the UTXO set.
953 bool DisconnectTip(BlockValidationState &state,
954 DisconnectedBlockTransactions *disconnectpool)
956
957 // Manual block validity manipulation:
963 bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex,
964 avalanche::Processor *const avalanche = nullptr)
965 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
966 !cs_avalancheFinalizedBlockIndex)
971 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
972 !cs_avalancheFinalizedBlockIndex);
974 bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex)
976 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
977 !cs_avalancheFinalizedBlockIndex);
978
982 bool AvalancheFinalizeBlock(CBlockIndex *pindex,
983 avalanche::Processor &avalanche)
984 EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_avalancheFinalizedBlockIndex);
985
989 void ClearAvalancheFinalizedBlock()
990 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
991
995 bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
996 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
997
999 void SetBlockFailureFlags(CBlockIndex *pindex)
1001
1003 void ResetBlockFailureFlags(CBlockIndex *pindex)
1005 template <typename F>
1006 bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
1008 template <typename F, typename C, typename AC>
1009 void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
1010 C fChild, AC fAncestorWasChanged)
1012
1014 void UnparkBlockAndChildren(CBlockIndex *pindex)
1016
1018 void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1019
1021 bool ReplayBlocks();
1022
1027 bool LoadGenesisBlock();
1028
1029 void TryAddBlockIndexCandidate(CBlockIndex *pindex)
1031
1032 void PruneBlockIndexCandidates();
1033
1034 void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1035
1037 const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
1039
1044 bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1045
1049 CoinsCacheSizeState GetCoinsCacheSizeState()
1051
1053 GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
1054 size_t max_mempool_size_bytes)
1056
1058
1061 RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1062 return m_mempool ? &m_mempool->cs : nullptr;
1063 }
1064
1065private:
1066 bool ActivateBestChainStep(
1067 BlockValidationState &state, CBlockIndex *pindexMostWork,
1068 const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
1069 const avalanche::Processor *const avalanche = nullptr,
1072 !cs_avalancheFinalizedBlockIndex);
1073 bool ConnectTip(BlockValidationState &state,
1074 BlockPolicyValidationState &blockPolicyState,
1075 CBlockIndex *pindexNew,
1076 const std::shared_ptr<const CBlock> &pblock,
1077 DisconnectedBlockTransactions &disconnectpool,
1078 const avalanche::Processor *const avalanche = nullptr,
1079 ChainstateRole chainstate_role = ChainstateRole::NORMAL)
1081 !cs_avalancheFinalizedBlockIndex);
1082 void InvalidBlockFound(CBlockIndex *pindex,
1083 const BlockValidationState &state)
1084 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1085 CBlockIndex *
1086 FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile,
1087 bool fAutoUnpark)
1088 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1089
1090 bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
1092
1093 void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
1095
1096 bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex,
1097 bool invalidate)
1098 EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex,
1099 !cs_avalancheFinalizedBlockIndex);
1100
1101 void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1102 void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
1104 void InvalidChainFound(CBlockIndex *pindexNew)
1105 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1106
1107 const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1109
1113 void UpdateTip(const CBlockIndex *pindexNew)
1115
1116 NodeClock::time_point m_next_write{NodeClock::time_point::max()};
1117
1122 [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk()
1124
1126};
1127
1129 SUCCESS,
1130 SKIPPED,
1131
1132 // Expected assumeutxo configuration data is not found for the height of the
1133 // base block.
1135
1136 // Failed to generate UTXO statistics (to check UTXO set hash) for the
1137 // background chainstate.
1139
1140 // The UTXO set hash of the background validation chainstate does not match
1141 // the one expected by assumeutxo chainparams.
1143
1144 // The blockhash of the current tip of the background validation chainstate
1145 // does not match the one expected by the snapshot chainstate.
1147};
1148
1177private:
1193 std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
1194
1204 std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
1205
1212 Chainstate *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1213
1214 CBlockIndex *m_best_invalid GUARDED_BY(::cs_main){nullptr};
1215 CBlockIndex *m_best_parked GUARDED_BY(::cs_main){nullptr};
1216
1218 CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex()){nullptr};
1219
1220 bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex());
1221
1229 [[nodiscard]] bool
1230 PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate,
1231 AutoFile &coins_file,
1232 const node::SnapshotMetadata &metadata);
1241 bool AcceptBlockHeader(
1242 const CBlockHeader &block, BlockValidationState &state,
1243 CBlockIndex **ppindex, bool min_pow_checked,
1244 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1247
1253 bool IsUsable(const Chainstate *const pchainstate) const
1255 return pchainstate && !pchainstate->m_disabled;
1256 }
1257
1259 SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main){};
1260
1264
1267 SteadyClock::duration GUARDED_BY(::cs_main) time_check{};
1268 SteadyClock::duration GUARDED_BY(::cs_main) time_forks{};
1269 SteadyClock::duration GUARDED_BY(::cs_main) time_connect{};
1270 SteadyClock::duration GUARDED_BY(::cs_main) time_verify{};
1271 SteadyClock::duration GUARDED_BY(::cs_main) time_index{};
1272 SteadyClock::duration GUARDED_BY(::cs_main) time_total{};
1273 int64_t GUARDED_BY(::cs_main) num_blocks_total{0};
1274 SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total{};
1275 SteadyClock::duration GUARDED_BY(::cs_main) time_flush{};
1276 SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate{};
1277 SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect{};
1278
1279public:
1281
1282 explicit ChainstateManager(const util::SignalInterrupt &interrupt,
1283 Options options,
1284 node::BlockManager::Options blockman_options);
1285
1288 std::function<void()> snapshot_download_completed = std::function<void()>();
1289
1290 const Config &GetConfig() const { return m_options.config; }
1291
1292 const CChainParams &GetParams() const {
1293 return m_options.config.GetChainParams();
1294 }
1296 return m_options.config.GetChainParams().GetConsensus();
1297 }
1298 bool ShouldCheckBlockIndex() const;
1300 return *Assert(m_options.minimum_chain_work);
1301 }
1303 return *Assert(m_options.assumed_valid_block);
1304 }
1306 return m_options.notifications;
1307 }
1308
1315 void CheckBlockIndex();
1316
1330 }
1331
1337
1339
1347 mutable std::atomic<bool> m_cached_finished_ibd{false};
1348
1354 std::atomic<int32_t> nBlockSequenceId{1};
1355
1357 int32_t nBlockReverseSequenceId = -1;
1359 arith_uint256 nLastPreciousChainwork = 0;
1360
1361 // Reset the memory-only sequence counters we use to track block arrival
1362 // (used by tests to reset state)
1365 nBlockSequenceId = 1;
1366 nBlockReverseSequenceId = -1;
1367 }
1368
1388 std::set<CBlockIndex *> m_failed_blocks;
1389
1394 CBlockIndex *m_best_header GUARDED_BY(::cs_main){nullptr};
1395
1398 size_t m_total_coinstip_cache{0};
1399 //
1402 size_t m_total_coinsdb_cache{0};
1403
1407 // constructor
1408 Chainstate &InitializeChainstate(CTxMemPool *mempool)
1410
1412 std::vector<Chainstate *> GetAll();
1413
1427 [[nodiscard]] util::Result<CBlockIndex *>
1428 ActivateSnapshot(AutoFile &coins_file,
1429 const node::SnapshotMetadata &metadata, bool in_memory);
1430
1438 SnapshotCompletionResult MaybeCompleteSnapshotValidation()
1440
1442 const CBlockIndex *GetSnapshotBaseBlock() const
1444
1446 Chainstate &ActiveChainstate() const;
1447 CChain &ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1448 return ActiveChainstate().m_chain;
1449 }
1450 int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1451 return ActiveChain().Height();
1452 }
1454 return ActiveChain().Tip();
1455 }
1456
1457 const CBlockIndex *GetAvalancheFinalizedTip() const;
1458
1461 return IsUsable(m_snapshot_chainstate.get()) &&
1462 IsUsable(m_ibd_chainstate.get());
1463 }
1464
1467 EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1468 return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip()
1469 : nullptr;
1470 }
1471
1474 return m_blockman.m_block_index;
1475 }
1476
1479 bool IsSnapshotActive() const;
1480
1481 std::optional<BlockHash> SnapshotBlockhash() const;
1482
1485 return m_snapshot_chainstate && m_ibd_chainstate &&
1486 m_ibd_chainstate->m_disabled;
1487 }
1488
1493 bool IsInitialBlockDownload() const;
1494
1526 void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp = nullptr,
1527 std::multimap<BlockHash, FlatFilePos>
1528 *blocks_with_unknown_parent = nullptr,
1529 avalanche::Processor *const avalanche = nullptr);
1530
1558 bool ProcessNewBlock(const std::shared_ptr<const CBlock> &block,
1559 bool force_processing, bool min_pow_checked,
1560 bool *new_block,
1561 avalanche::Processor *const avalanche = nullptr)
1563
1579 bool ProcessNewBlockHeaders(
1580 const std::vector<CBlockHeader> &block, bool min_pow_checked,
1581 BlockValidationState &state, const CBlockIndex **ppindex = nullptr,
1582 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1584
1603 bool AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
1604 BlockValidationState &state, bool fRequested,
1605 const FlatFilePos *dbp, bool *fNewBlock,
1606 bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1607
1608 void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
1609 const FlatFilePos &pos)
1611
1620 [[nodiscard]] MempoolAcceptResult
1621 ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1623
1626 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1627
1630 void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1631
1638 void ReportHeadersPresync(const arith_uint256 &work, int64_t height,
1639 int64_t timestamp);
1640
1643 bool DetectSnapshotChainstate(CTxMemPool *mempool)
1645
1646 void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1647
1650 [[nodiscard]] bool DeleteSnapshotChainstate()
1652
1655 Chainstate &ActivateExistingSnapshot(BlockHash base_blockhash)
1657
1667 bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1668
1677 Chainstate &GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1678
1682 std::pair<int, int> GetPruneRange(const Chainstate &chainstate,
1683 int last_height_can_prune)
1685
1688 std::optional<int> GetSnapshotBaseHeight() const
1690
1691 CCheckQueue<CScriptCheck> &GetCheckQueue() { return m_script_check_queue; }
1692
1696 void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1697
1699 bool DumpRecentHeadersTime(const fs::path &filePath) const
1700 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1702 bool LoadRecentHeadersTime(const fs::path &filePath)
1703 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1704};
1705
1707template <typename DEP>
1708bool DeploymentActiveAfter(const CBlockIndex *pindexPrev,
1709 const ChainstateManager &chainman, DEP dep) {
1710 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep);
1711}
1712
1713template <typename DEP>
1715 const ChainstateManager &chainman, DEP dep) {
1716 return DeploymentActiveAt(index, chainman.GetConsensus(), dep);
1717}
1718
1719#endif // BITCOIN_VALIDATION_H
int flags
Definition: bitcoin-tx.cpp:544
static void InvalidateBlock(ChainstateManager &chainman, avalanche::Processor *const avalanche, const BlockHash &block_hash)
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:21
#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:152
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:137
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition: validation.h:131
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:144
BlockValidationOptions(const Config &config)
Definition: validation.cpp:117
bool shouldValidatePoW() const
Definition: validation.h:150
uint64_t excessiveBlockSize
Definition: validation.h:124
bool shouldValidateMerkleRoot() const
Definition: validation.h:151
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
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:550
CScriptCheck & operator=(CScriptCheck &&)=default
SignatureCache * m_signature_cache
Definition: validation.h:559
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:583
CScriptCheck(const CScriptCheck &)=delete
uint32_t nFlags
Definition: validation.h:555
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:560
ScriptExecutionMetrics metrics
Definition: validation.h:557
CTxOut m_tx_out
Definition: validation.h:552
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:564
bool cacheStore
Definition: validation.h:556
std::optional< std::pair< ScriptError, std::string > > operator()()
PrecomputedTransactionData txdata
Definition: validation.h:558
const CTransaction * ptxTo
Definition: validation.h:553
unsigned int nIn
Definition: validation.h:554
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:561
CScriptCheck & operator=(const CScriptCheck &)=delete
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.
Definition: transaction.h:128
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:643
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:645
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:727
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:733
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:826
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:880
CTxMemPool * GetMempool()
Definition: validation.h:866
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:870
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:757
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:737
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:755
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:860
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:789
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:741
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:877
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:784
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:779
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1176
SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total
Definition: validation.h:1274
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(
Definition: validation.h:1472
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1394
ValidationCache m_validation_cache
Definition: validation.h:1338
int64_t GUARDED_BY(::cs_main) num_blocks_total
Definition: validation.h:1273
SteadyClock::duration GUARDED_BY(::cs_main) time_index
Definition: validation.h:1271
const Config & GetConfig() const
Definition: validation.h:1290
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1466
SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect
Definition: validation.h:1277
kernel::Notifications & GetNotifications() const
Definition: validation.h:1305
SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
Definition: validation.h:1259
SteadyClock::duration GUARDED_BY(::cs_main) time_check
Timers and counters used for benchmarking validation in both background and active chainstates.
Definition: validation.h:1267
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1328
SteadyClock::duration GUARDED_BY(::cs_main) time_total
Definition: validation.h:1272
SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate
Definition: validation.h:1276
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1484
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
Definition: validation.h:1263
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1453
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:1214
SteadyClock::duration GUARDED_BY(::cs_main) time_forks
Definition: validation.h:1268
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1460
CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex())
The last header for which a headerTip notification was issued.
Definition: validation.h:1218
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1332
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1450
const CChainParams & GetParams() const
Definition: validation.h:1292
const Consensus::Params & GetConsensus() const
Definition: validation.h:1295
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
Definition: validation.h:1215
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1299
const Options m_options
Definition: validation.h:1333
SteadyClock::duration GUARDED_BY(::cs_main) time_verify
Definition: validation.h:1270
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:1212
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1302
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1412
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:1388
SteadyClock::duration GUARDED_BY(::cs_main) time_connect
Definition: validation.h:1269
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(
Definition: validation.h:1363
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1336
SteadyClock::duration GUARDED_BY(::cs_main) time_flush
Definition: validation.h:1275
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:372
bool consume_and_check(int consumed)
Definition: validation.h:379
std::atomic< int64_t > remaining
Definition: validation.h:374
CheckInputsLimiter(int64_t limit)
Definition: validation.h:377
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:672
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.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Definition: config.h:19
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:400
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition: validation.h:395
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition: validation.h:392
Convenience class for initializing and passing the script execution cache and signature cache.
Definition: validation.h:413
CuckooCache::cache< ScriptCacheElement, ScriptCacheHasher > m_script_execution_cache
Definition: validation.h:421
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
ValidationCache & operator=(const ValidationCache &)=delete
ValidationCache(const ValidationCache &)=delete
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
Definition: validation.h:431
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
Definition: validation.h:417
SignatureCache m_signature_cache
Definition: validation.h:422
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...
Definition: blockstorage.h:114
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:31
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
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
Definition: messages.h:12
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:72
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
Definition: transaction.h:315
static std::string ToString(const CService &ip)
Definition: db.h:36
@ OK
The message verification was successful.
Definition: amount.h:23
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:196
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition: validation.h:216
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:274
const ResultType m_result_type
Result type.
Definition: validation.h:207
const std::optional< std::vector< TxId > > m_txids_fee_calculations
Contains the txids of the transactions used for fee-related checks.
Definition: validation.h:233
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:266
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:210
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:283
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:198
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:235
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:226
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition: validation.h:240
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:248
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:258
MempoolAcceptResult(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:291
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:218
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:299
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition: validation.h:319
PackageMempoolAcceptResult(PackageValidationState state, std::map< TxId, MempoolAcceptResult > &&results)
Definition: validation.h:310
PackageValidationState m_state
Definition: validation.h:300
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:308
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
An options struct for BlockManager, more ergonomically referred to as BlockManager::Options due to th...
An options struct for ChainstateManager, more ergonomically referred to as ChainstateManager::Options...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h: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:33
AssertLockHeld(pool.cs)
GlobalMutex g_best_block_mutex
Definition: validation.cpp:113
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:109
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:114
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...
Definition: validation.cpp:177
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:92
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:106
bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:201
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:90
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:115
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:1708
SnapshotCompletionResult
Definition: validation.h:1128
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:112
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:631
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:95
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:705
@ 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.
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1714
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:91
FlushStateMode
Definition: validation.h:661
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:84
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage={})