Bitcoin ABC 0.32.6
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 <common/bloom.h>
20#include <config.h>
21#include <consensus/amount.h>
22#include <consensus/consensus.h>
23#include <deploymentstatus.h>
24#include <disconnectresult.h>
25#include <flatfile.h>
26#include <kernel/chain.h>
27#include <kernel/chainparams.h>
29#include <kernel/cs_main.h>
30#include <node/blockstorage.h>
31#include <policy/packages.h>
32#include <script/script_error.h>
34#include <script/scriptcache.h>
35#include <script/sigcache.h>
36#include <shutdown.h>
37#include <sync.h>
38#include <txdb.h>
39#include <txmempool.h> // For CTxMemPool::cs
40#include <uint256.h>
41#include <util/check.h>
42#include <util/fs.h>
43#include <util/result.h>
44#include <util/time.h>
45#include <util/translation.h>
46
47#include <atomic>
48#include <cstdint>
49#include <map>
50#include <memory>
51#include <optional>
52#include <set>
53#include <string>
54#include <thread>
55#include <type_traits>
56#include <utility>
57#include <vector>
58
60class CChainParams;
61class Chainstate;
63class CScriptCheck;
64class CTxMemPool;
65class CTxUndo;
67
68struct ChainTxData;
69struct FlatFilePos;
71struct LockPoints;
72struct AssumeutxoData;
73namespace node {
74class SnapshotMetadata;
75} // namespace node
76namespace Consensus {
77struct Params;
78} // namespace Consensus
79namespace avalanche {
80class Processor;
81} // namespace avalanche
82namespace util {
83class SignalInterrupt;
84} // namespace util
85
86#define MIN_TRANSACTION_SIZE (::GetSerializeSize(CTransaction{}))
87
89static const int MAX_SCRIPTCHECK_THREADS = 15;
91static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
92
93static const bool DEFAULT_PEERBLOOMFILTERS = true;
94
99static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
100static const signed int DEFAULT_CHECKBLOCKS = 6;
101static constexpr int DEFAULT_CHECKLEVEL{3};
115static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
116
119
121extern std::condition_variable g_best_block_cv;
123extern const CBlockIndex *g_best_block;
124
126extern const std::vector<std::string> CHECKLEVEL_DOC;
127
129private:
131 bool checkPoW : 1;
133
134public:
135 // Do full validation by default
136 explicit BlockValidationOptions(const Config &config);
137 explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
138 bool _checkPow = true,
139 bool _checkMerkleRoot = true)
140 : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
141 checkMerkleRoot(_checkMerkleRoot) {}
142
143 BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
144 BlockValidationOptions ret = *this;
145 ret.checkPoW = _checkPoW;
146 return ret;
147 }
148
150 withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
151 BlockValidationOptions ret = *this;
152 ret.checkMerkleRoot = _checkMerkleRoot;
153 return ret;
154 }
155
156 bool shouldValidatePoW() const { return checkPoW; }
158 uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
159};
160
164void StartScriptCheckWorkerThreads(int threads_num);
165
170
171Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
172
173bool FatalError(kernel::Notifications &notifications,
174 BlockValidationState &state, const std::string &strMessage,
175 const bilingual_str &userMessage = {});
176
181double GuessVerificationProgress(const ChainTxData &data,
182 const CBlockIndex *pindex);
183
185void PruneBlockFilesManual(Chainstate &active_chainstate,
186 int nManualPruneHeight);
187
188// clang-format off
211// clang-format on
214 enum class ResultType {
216 VALID,
218 INVALID,
220 MEMPOOL_ENTRY,
221 };
224
227
232 const std::optional<int64_t> m_vsize;
234 const std::optional<Amount> m_base_fees;
242 const std::optional<CFeeRate> m_effective_feerate;
249 const std::optional<std::vector<TxId>> m_txids_fee_calculations;
250
252 return MempoolAcceptResult(state);
253 }
254
256 FeeFailure(TxValidationState state, CFeeRate effective_feerate,
257 const std::vector<TxId> &txids_fee_calculations) {
258 return MempoolAcceptResult(state, effective_feerate,
259 txids_fee_calculations);
260 }
261
264 Success(int64_t vsize, Amount fees, CFeeRate effective_feerate,
265 const std::vector<TxId> &txids_fee_calculations) {
266 return MempoolAcceptResult(ResultType::VALID, vsize, fees,
267 effective_feerate, txids_fee_calculations);
268 }
269
274 static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees) {
275 return MempoolAcceptResult(vsize, fees);
276 }
277
278 // Private constructors. Use static methods MempoolAcceptResult::Success,
279 // etc. to construct.
280private:
283 : m_result_type(ResultType::INVALID), m_state(state),
284 m_base_fees(std::nullopt) {
285 // Can be invalid or error
286 Assume(!state.IsValid());
287 }
288
291 ResultType result_type, int64_t vsize, Amount fees,
292 CFeeRate effective_feerate,
293 const std::vector<TxId> &txids_fee_calculations)
294 : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees),
295 m_effective_feerate(effective_feerate),
296 m_txids_fee_calculations(txids_fee_calculations) {}
297
300 TxValidationState state, CFeeRate effective_feerate,
301 const std::vector<TxId> &txids_fee_calculations)
302 : m_result_type(ResultType::INVALID), m_state(state),
303 m_effective_feerate(effective_feerate),
304 m_txids_fee_calculations(txids_fee_calculations) {}
305
307 explicit MempoolAcceptResult(int64_t vsize, Amount fees)
308 : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize},
309 m_base_fees(fees) {}
310};
311
324 std::map<TxId, MempoolAcceptResult> m_tx_results;
325
328 std::map<TxId, MempoolAcceptResult> &&results)
329 : m_state{state}, m_tx_results(std::move(results)) {}
330
335 explicit PackageMempoolAcceptResult(const TxId &txid,
336 const MempoolAcceptResult &result)
337 : m_tx_results{{txid, result}} {}
338};
339
363AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx,
364 int64_t accept_time, bool bypass_limits,
365 bool test_accept = false, unsigned int heightOverride = 0)
367
380ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool,
381 const Package &txns, bool test_accept)
383
389protected:
390 std::atomic<int64_t> remaining;
391
392public:
393 explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
394
395 bool consume_and_check(int consumed) {
396 auto newvalue = (remaining -= consumed);
397 return newvalue >= 0;
398 }
399
400 bool check() { return remaining >= 0; }
401};
402
404public:
406
407 // Let's make this bad boy copiable.
409 : CheckInputsLimiter(rhs.remaining.load()) {}
410
412 remaining = rhs.remaining.load();
413 return *this;
414 }
415
417 TxSigCheckLimiter txLimiter;
418 // Historically, there has not been a transaction with more than 20k sig
419 // checks on testnet or mainnet, so this effectively disable sigchecks.
420 txLimiter.remaining = 20000;
421 return txLimiter;
422 }
423};
424
430private:
434
435public:
439
440 ValidationCache(size_t script_execution_cache_bytes,
441 size_t signature_cache_bytes);
442
445
449 }
450};
451
481bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
482 const CCoinsViewCache &view, const uint32_t flags,
483 bool sigCacheStore, bool scriptCacheStore,
484 const PrecomputedTransactionData &txdata,
485 ValidationCache &validation_cache, int &nSigChecksOut,
486 TxSigCheckLimiter &txLimitSigChecks,
487 CheckInputsLimiter *pBlockLimitSigChecks,
488 std::vector<CScriptCheck> *pvChecks)
490
494static inline bool
495CheckInputScripts(const CTransaction &tx, TxValidationState &state,
496 const CCoinsViewCache &view, const uint32_t flags,
497 bool sigCacheStore, bool scriptCacheStore,
498 const PrecomputedTransactionData &txdata,
499 ValidationCache &validation_cache, int &nSigChecksOut)
501 TxSigCheckLimiter nSigChecksTxLimiter;
502 return CheckInputScripts(
503 tx, state, view, flags, sigCacheStore, scriptCacheStore, txdata,
504 validation_cache, nSigChecksOut, nSigChecksTxLimiter, nullptr, nullptr);
505}
506
510void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
511 int nHeight);
512
516void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
517 int nHeight);
518
522std::vector<Coin> GetSpentCoins(const CTransactionRef &ptx,
523 const CCoinsViewCache &coins_view);
524
543std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
544 const CCoinsView &coins_view,
545 const CTransaction &tx);
546
556bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points);
557
566private:
568 const CTransaction *ptxTo;
569 unsigned int nIn;
570 uint32_t nFlags;
577
578public:
579 CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
580 SignatureCache &signature_cache, unsigned int nInIn,
581 uint32_t nFlagsIn, bool cacheIn,
582 const PrecomputedTransactionData &txdataIn,
583 TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
584 CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
585 : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
586 cacheStore(cacheIn), txdata(txdataIn),
587 m_signature_cache(&signature_cache),
588 pTxLimitSigChecks(pTxLimitSigChecksIn),
589 pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
590
591 CScriptCheck(const CScriptCheck &) = delete;
595
596 std::optional<std::pair<ScriptError, std::string>> operator()();
597
599};
600
601// CScriptCheck is used a lot in std::vector, make sure that's efficient
602static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
603static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
604static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
605
614bool CheckBlock(const CBlock &block, BlockValidationState &state,
615 const Consensus::Params &params,
616 BlockValidationOptions validationOptions);
617
623 BlockValidationState &state, const CChainParams &params,
624 Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
625 const std::function<NodeClock::time_point()> &adjusted_time_callback,
627
631bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
632 const Consensus::Params &consensusParams);
633
637bool IsBlockMutated(const CBlock &block);
638
640arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader> &headers);
641
642enum class VerifyDBResult {
643 SUCCESS,
645 INTERRUPTED,
648};
649
655private:
657
658public:
660
661public:
662 explicit CVerifyDB(kernel::Notifications &notifications);
663 ~CVerifyDB();
664
665 [[nodiscard]] VerifyDBResult VerifyDB(Chainstate &chainstate,
666 CCoinsView &coinsview,
667 int nCheckLevel, int nCheckDepth)
669};
670
672enum class FlushStateMode { NONE, IF_NEEDED, PERIODIC, ALWAYS };
673
684public:
688
692
695 std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
696
705 CoinsViews(DBParams db_params, CoinsViewOptions options);
706
708 void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
709};
710
713 CRITICAL = 2,
715 LARGE = 1,
716 OK = 0
717};
718
734protected:
740
744
747 std::unique_ptr<CoinsViews> m_coins_views;
748
761 bool m_disabled GUARDED_BY(::cs_main){false};
762
764
769 const CBlockIndex *m_avalancheFinalizedBlockIndex
770 GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
771
778 CRollingBloomFilter m_filterParkingPoliciesApplied =
779 CRollingBloomFilter{1000, 0.000001};
780
781 CBlockIndex const *m_best_fork_tip = nullptr;
782 CBlockIndex const *m_best_fork_base = nullptr;
783
785 const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};
786
787public:
791
796
797 explicit Chainstate(
798 CTxMemPool *mempool, node::BlockManager &blockman,
799 ChainstateManager &chainman,
800 std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
801
807
814 void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
815 std::string leveldb_name = "chainstate");
816
819 void InitCoinsCache(size_t cache_size_bytes)
821
825 bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
827 return m_coins_views && m_coins_views->m_cacheview;
828 }
829
833
840 const std::optional<BlockHash> m_from_snapshot_blockhash{};
841
847 const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
848
856 std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
857
861 Assert(m_coins_views);
862 return *Assert(m_coins_views->m_cacheview);
863 }
864
868 return Assert(m_coins_views)->m_dbview;
869 }
870
872 CTxMemPool *GetMempool() { return m_mempool; }
873
879 return Assert(m_coins_views)->m_catcherview;
880 }
881
883 void ResetCoinsViews() { m_coins_views.reset(); }
884
886 bool HasCoinsViews() const { return (bool)m_coins_views; }
887
889 size_t m_coinsdb_cache_size_bytes{0};
890
892 size_t m_coinstip_cache_size_bytes{0};
893
896 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
898
910 bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
911 int nManualPruneHeight = 0);
912
914 void ForceFlushStateToDisk();
915
918 void PruneAndFlush();
919
940 bool ActivateBestChain(BlockValidationState &state,
941 std::shared_ptr<const CBlock> pblock = nullptr,
942 avalanche::Processor *const avalanche = nullptr)
943 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
944 !cs_avalancheFinalizedBlockIndex)
946
947 // Block (dis)connection on a given view:
948 DisconnectResult DisconnectBlock(const CBlock &block,
949 const CBlockIndex *pindex,
950 CCoinsViewCache &view)
952 bool ConnectBlock(const CBlock &block, BlockValidationState &state,
953 CBlockIndex *pindex, CCoinsViewCache &view,
955 Amount *blockFees = nullptr, bool fJustCheck = false)
957
958 // Apply the effects of a block disconnection on the UTXO set.
959 bool DisconnectTip(BlockValidationState &state,
960 DisconnectedBlockTransactions *disconnectpool)
962
963 // Manual block validity manipulation:
969 bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex,
970 avalanche::Processor *const avalanche = nullptr)
971 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
972 !cs_avalancheFinalizedBlockIndex)
977 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
978 !cs_avalancheFinalizedBlockIndex);
980 bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex)
982 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
983 !cs_avalancheFinalizedBlockIndex);
984
988 bool AvalancheFinalizeBlock(CBlockIndex *pindex,
989 avalanche::Processor &avalanche)
990 EXCLUSIVE_LOCKS_REQUIRED(::cs_main, !cs_avalancheFinalizedBlockIndex);
991
995 void ClearAvalancheFinalizedBlock()
996 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
997
1001 bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
1002 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
1003
1005 void SetBlockFailureFlags(CBlockIndex *pindex)
1007
1009 void ResetBlockFailureFlags(CBlockIndex *pindex)
1011 template <typename F>
1012 bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
1014 template <typename F, typename C, typename AC>
1015 void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
1016 C fChild, AC fAncestorWasChanged)
1018
1020 void UnparkBlockAndChildren(CBlockIndex *pindex)
1022
1024 void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1025
1027 bool ReplayBlocks();
1028
1033 bool LoadGenesisBlock();
1034
1035 void TryAddBlockIndexCandidate(CBlockIndex *pindex)
1037
1038 void PruneBlockIndexCandidates();
1039
1040 void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1041
1043 const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
1045
1047 void
1048 LoadMempool(const fs::path &load_path,
1049 fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
1050
1053 bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1054
1058 CoinsCacheSizeState GetCoinsCacheSizeState()
1060
1062 GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
1063 size_t max_mempool_size_bytes)
1065
1067
1070 RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1071 return m_mempool ? &m_mempool->cs : nullptr;
1072 }
1073
1074private:
1075 bool ActivateBestChainStep(
1076 BlockValidationState &state, CBlockIndex *pindexMostWork,
1077 const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
1078 const avalanche::Processor *const avalanche = nullptr,
1081 !cs_avalancheFinalizedBlockIndex);
1082 bool ConnectTip(BlockValidationState &state,
1083 BlockPolicyValidationState &blockPolicyState,
1084 CBlockIndex *pindexNew,
1085 const std::shared_ptr<const CBlock> &pblock,
1086 DisconnectedBlockTransactions &disconnectpool,
1087 const avalanche::Processor *const avalanche = nullptr,
1088 ChainstateRole chainstate_role = ChainstateRole::NORMAL)
1090 !cs_avalancheFinalizedBlockIndex);
1091 void InvalidBlockFound(CBlockIndex *pindex,
1092 const BlockValidationState &state)
1093 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1094 CBlockIndex *
1095 FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile,
1096 bool fAutoUnpark)
1097 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1098
1099 bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
1101
1102 void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
1104
1105 bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex,
1106 bool invalidate)
1107 EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex,
1108 !cs_avalancheFinalizedBlockIndex);
1109
1110 void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1111 void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
1113 void InvalidChainFound(CBlockIndex *pindexNew)
1114 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1115
1116 const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1118
1122 void UpdateTip(const CBlockIndex *pindexNew)
1124
1125 NodeClock::time_point m_next_write{NodeClock::time_point::max()};
1126
1131 [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk()
1133
1135};
1136
1138 SUCCESS,
1139 SKIPPED,
1140
1141 // Expected assumeutxo configuration data is not found for the height of the
1142 // base block.
1144
1145 // Failed to generate UTXO statistics (to check UTXO set hash) for the
1146 // background chainstate.
1148
1149 // The UTXO set hash of the background validation chainstate does not match
1150 // the one expected by assumeutxo chainparams.
1152
1153 // The blockhash of the current tip of the background validation chainstate
1154 // does not match the one expected by the snapshot chainstate.
1156};
1157
1186private:
1202 std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
1203
1213 std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
1214
1221 Chainstate *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1222
1223 CBlockIndex *m_best_invalid GUARDED_BY(::cs_main){nullptr};
1224 CBlockIndex *m_best_parked GUARDED_BY(::cs_main){nullptr};
1225
1233 [[nodiscard]] bool
1234 PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate,
1235 AutoFile &coins_file,
1236 const node::SnapshotMetadata &metadata);
1245 bool AcceptBlockHeader(
1246 const CBlockHeader &block, BlockValidationState &state,
1247 CBlockIndex **ppindex, bool min_pow_checked,
1248 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1251
1257 bool IsUsable(const Chainstate *const pchainstate) const
1259 return pchainstate && !pchainstate->m_disabled;
1260 }
1261
1263 SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main){};
1264
1265public:
1267
1268 explicit ChainstateManager(const util::SignalInterrupt &interrupt,
1269 Options options,
1270 node::BlockManager::Options blockman_options);
1271
1274 std::function<void()> snapshot_download_completed = std::function<void()>();
1275
1276 const Config &GetConfig() const { return m_options.config; }
1277
1278 const CChainParams &GetParams() const {
1279 return m_options.config.GetChainParams();
1280 }
1282 return m_options.config.GetChainParams().GetConsensus();
1283 }
1285 return *Assert(m_options.check_block_index);
1286 }
1288 return *Assert(m_options.minimum_chain_work);
1289 }
1291 return *Assert(m_options.assumed_valid_block);
1292 }
1294 return m_options.notifications;
1295 }
1296 int StopAtHeight() const { return m_options.stop_at_height; }
1297
1304 void CheckBlockIndex();
1305
1319 }
1320
1323 std::thread m_thread_load;
1327
1329
1337 mutable std::atomic<bool> m_cached_finished_ibd{false};
1338
1344 std::atomic<int32_t> nBlockSequenceId{1};
1345
1347 int32_t nBlockReverseSequenceId = -1;
1349 arith_uint256 nLastPreciousChainwork = 0;
1350
1351 // Reset the memory-only sequence counters we use to track block arrival
1352 // (used by tests to reset state)
1355 nBlockSequenceId = 1;
1356 nBlockReverseSequenceId = -1;
1357 }
1358
1378 std::set<CBlockIndex *> m_failed_blocks;
1379
1384 CBlockIndex *m_best_header GUARDED_BY(::cs_main){nullptr};
1385
1388 size_t m_total_coinstip_cache{0};
1389 //
1392 size_t m_total_coinsdb_cache{0};
1393
1397 // constructor
1398 Chainstate &InitializeChainstate(CTxMemPool *mempool)
1400
1402 std::vector<Chainstate *> GetAll();
1403
1417 [[nodiscard]] util::Result<CBlockIndex *>
1418 ActivateSnapshot(AutoFile &coins_file,
1419 const node::SnapshotMetadata &metadata, bool in_memory);
1420
1428 SnapshotCompletionResult MaybeCompleteSnapshotValidation()
1430
1432 const CBlockIndex *GetSnapshotBaseBlock() const
1434
1436 Chainstate &ActiveChainstate() const;
1437 CChain &ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1438 return ActiveChainstate().m_chain;
1439 }
1440 int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1441 return ActiveChain().Height();
1442 }
1444 return ActiveChain().Tip();
1445 }
1446
1447 const CBlockIndex *GetAvalancheFinalizedTip() const;
1448
1451 return IsUsable(m_snapshot_chainstate.get()) &&
1452 IsUsable(m_ibd_chainstate.get());
1453 }
1454
1457 EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1458 return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip()
1459 : nullptr;
1460 }
1461
1464 return m_blockman.m_block_index;
1465 }
1466
1469 bool IsSnapshotActive() const;
1470
1471 std::optional<BlockHash> SnapshotBlockhash() const;
1472
1475 return m_snapshot_chainstate && m_ibd_chainstate &&
1476 m_ibd_chainstate->m_disabled;
1477 }
1478
1483 bool IsInitialBlockDownload() const;
1484
1516 void LoadExternalBlockFile(AutoFile &file_in, FlatFilePos *dbp = nullptr,
1517 std::multimap<BlockHash, FlatFilePos>
1518 *blocks_with_unknown_parent = nullptr,
1519 avalanche::Processor *const avalanche = nullptr);
1520
1548 bool ProcessNewBlock(const std::shared_ptr<const CBlock> &block,
1549 bool force_processing, bool min_pow_checked,
1550 bool *new_block,
1551 avalanche::Processor *const avalanche = nullptr)
1553
1569 bool ProcessNewBlockHeaders(
1570 const std::vector<CBlockHeader> &block, bool min_pow_checked,
1571 BlockValidationState &state, const CBlockIndex **ppindex = nullptr,
1572 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1574
1593 bool AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
1594 BlockValidationState &state, bool fRequested,
1595 const FlatFilePos *dbp, bool *fNewBlock,
1596 bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1597
1598 void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
1599 const FlatFilePos &pos)
1601
1610 [[nodiscard]] MempoolAcceptResult
1611 ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1613
1616 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1617
1620 void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1621
1628 void ReportHeadersPresync(const arith_uint256 &work, int64_t height,
1629 int64_t timestamp);
1630
1633 bool DetectSnapshotChainstate(CTxMemPool *mempool)
1635
1636 void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1637
1640 [[nodiscard]] bool DeleteSnapshotChainstate()
1642
1645 Chainstate &ActivateExistingSnapshot(BlockHash base_blockhash)
1647
1657 bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1658
1667 Chainstate &GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1668
1672 std::pair<int, int> GetPruneRange(const Chainstate &chainstate,
1673 int last_height_can_prune)
1675
1678 std::optional<int> GetSnapshotBaseHeight() const
1680
1684 void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1685
1687 bool DumpRecentHeadersTime(const fs::path &filePath) const
1688 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1690 bool LoadRecentHeadersTime(const fs::path &filePath)
1691 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1692};
1693
1695template <typename DEP>
1696bool DeploymentActiveAfter(const CBlockIndex *pindexPrev,
1697 const ChainstateManager &chainman, DEP dep) {
1698 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep);
1699}
1700
1701template <typename DEP>
1703 const ChainstateManager &chainman, DEP dep) {
1704 return DeploymentActiveAt(index, chainman.GetConsensus(), dep);
1705}
1706
1707#endif // BITCOIN_VALIDATION_H
int flags
Definition: bitcoin-tx.cpp:542
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:84
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:430
uint64_t getExcessiveBlockSize() const
Definition: validation.h:158
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:143
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition: validation.h:137
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:150
BlockValidationOptions(const Config &config)
Definition: validation.cpp:123
bool shouldValidatePoW() const
Definition: validation.h:156
uint64_t excessiveBlockSize
Definition: validation.h:130
bool shouldValidateMerkleRoot() const
Definition: validation.h:157
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:363
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:520
Abstract view on the open txout dataset.
Definition: coins.h:305
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
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:565
CScriptCheck & operator=(CScriptCheck &&)=default
SignatureCache * m_signature_cache
Definition: validation.h:574
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:598
CScriptCheck(const CScriptCheck &)=delete
uint32_t nFlags
Definition: validation.h:570
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:575
ScriptExecutionMetrics metrics
Definition: validation.h:572
CTxOut m_tx_out
Definition: validation.h:567
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:579
bool cacheStore
Definition: validation.h:571
std::optional< std::pair< ScriptError, std::string > > operator()()
PrecomputedTransactionData txdata
Definition: validation.h:573
const CTransaction * ptxTo
Definition: validation.h:568
unsigned int nIn
Definition: validation.h:569
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:576
CScriptCheck & operator=(const CScriptCheck &)=delete
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:317
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:654
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:656
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:733
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:739
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:832
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:886
CTxMemPool * GetMempool()
Definition: validation.h:872
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:876
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:763
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:743
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:761
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:866
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:795
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:747
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:883
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:790
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:785
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
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:1462
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1384
ValidationCache m_validation_cache
Definition: validation.h:1328
const Config & GetConfig() const
Definition: validation.h:1276
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1456
std::thread m_thread_load
Definition: validation.h:1323
kernel::Notifications & GetNotifications() const
Definition: validation.h:1293
SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
Definition: validation.h:1263
bool ShouldCheckBlockIndex() const
Definition: validation.h:1284
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1317
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1474
bool IsUsable(const Chainstate *const pchainstate) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
Definition: validation.h:1257
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1443
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:1223
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1450
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1321
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1440
int StopAtHeight() const
Definition: validation.h:1296
const CChainParams & GetParams() const
Definition: validation.h:1278
const Consensus::Params & GetConsensus() const
Definition: validation.h:1281
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
Definition: validation.h:1224
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1287
const Options m_options
Definition: validation.h:1322
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:1221
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1290
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1402
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:1378
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:1353
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1326
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:388
bool consume_and_check(int consumed)
Definition: validation.h:395
std::atomic< int64_t > remaining
Definition: validation.h:390
CheckInputsLimiter(int64_t limit)
Definition: validation.h:393
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:683
std::unique_ptr< CCoinsViewCache > m_cacheview GUARDED_BY(cs_main)
This is the top layer of the cache hierarchy - it keeps as many coins in memory as can fit per the db...
CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main)
This view wraps access to the leveldb instance and handles read errors gracefully.
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
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:416
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition: validation.h:411
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition: validation.h:408
Convenience class for initializing and passing the script execution cache and signature cache.
Definition: validation.h:429
CuckooCache::cache< ScriptCacheElement, ScriptCacheHasher > m_script_execution_cache
Definition: validation.h:437
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:447
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
Definition: validation.h:433
SignatureCache m_signature_cache
Definition: validation.h:438
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:116
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:30
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
Bridge operations to C stdio.
Definition: fs.cpp:28
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: fs.h:203
bool LoadMempool(CTxMemPool &pool, const fs::path &load_path, Chainstate &active_chainstate, FopenFn mockable_fopen_function)
Definition: init.h:31
std::unordered_map< BlockHash, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:74
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
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:108
Definition: amount.h:21
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:31
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:212
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition: validation.h:232
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:290
const ResultType m_result_type
Result type.
Definition: validation.h:223
const std::optional< std::vector< TxId > > m_txids_fee_calculations
Contains the txids of the transactions used for fee-related checks.
Definition: validation.h:249
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:282
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:226
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:299
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:214
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:251
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:242
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition: validation.h:256
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:264
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:274
MempoolAcceptResult(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:307
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:234
Mockable clock in the context of tests, otherwise the system clock.
Definition: time.h:18
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:315
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition: validation.h:335
PackageMempoolAcceptResult(PackageValidationState state, std::map< TxId, MempoolAcceptResult > &&results)
Definition: validation.h:326
PackageValidationState m_state
Definition: validation.h:316
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:324
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:31
AssertLockHeld(pool.cs)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
GlobalMutex g_best_block_mutex
Definition: validation.cpp:119
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)
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:120
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:186
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:101
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
arith_uint256 CalculateHeadersWork(const std::vector< CBlockHeader > &headers)
Return the sum of the work on a given set of headers.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev?...
Definition: validation.h:115
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:210
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:99
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:121
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:1696
SnapshotCompletionResult
Definition: validation.h:1137
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:89
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:118
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:91
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false, unsigned int heightOverride=0) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
VerifyDBResult
Definition: validation.h:642
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:101
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:711
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
std::vector< Coin > GetSpentCoins(const CTransactionRef &ptx, const CCoinsViewCache &coins_view)
Get the coins spent by ptx from the coins_view.
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.
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1702
void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:100
FlushStateMode
Definition: validation.h:672
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:93
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage={})