Bitcoin ABC 0.31.5
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 <shutdown.h>
35#include <sync.h>
36#include <txdb.h>
37#include <txmempool.h> // For CTxMemPool::cs
38#include <uint256.h>
39#include <util/check.h>
40#include <util/fs.h>
41#include <util/result.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 <thread>
52#include <type_traits>
53#include <utility>
54#include <vector>
55
57class CChainParams;
58class Chainstate;
60class CScriptCheck;
61class CTxMemPool;
62class CTxUndo;
64
65struct ChainTxData;
66struct FlatFilePos;
68struct LockPoints;
69struct AssumeutxoData;
70namespace node {
71class SnapshotMetadata;
72} // namespace node
73namespace Consensus {
74struct Params;
75} // namespace Consensus
76namespace avalanche {
77class Processor;
78} // namespace avalanche
79
80#define MIN_TRANSACTION_SIZE \
81 (::GetSerializeSize(CTransaction(), PROTOCOL_VERSION))
82
84static const int MAX_SCRIPTCHECK_THREADS = 15;
86static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
87
88static const bool DEFAULT_PEERBLOOMFILTERS = true;
89
91static const int DEFAULT_STOPATHEIGHT = 0;
96static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
97static const signed int DEFAULT_CHECKBLOCKS = 6;
98static constexpr int DEFAULT_CHECKLEVEL{3};
112static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
113
116
118extern std::condition_variable g_best_block_cv;
120extern const CBlockIndex *g_best_block;
121
123extern const std::vector<std::string> CHECKLEVEL_DOC;
124
126private:
128 bool checkPoW : 1;
130
131public:
132 // Do full validation by default
133 explicit BlockValidationOptions(const Config &config);
134 explicit BlockValidationOptions(uint64_t _excessiveBlockSize,
135 bool _checkPow = true,
136 bool _checkMerkleRoot = true)
137 : excessiveBlockSize(_excessiveBlockSize), checkPoW(_checkPow),
138 checkMerkleRoot(_checkMerkleRoot) {}
139
140 BlockValidationOptions withCheckPoW(bool _checkPoW = true) const {
141 BlockValidationOptions ret = *this;
142 ret.checkPoW = _checkPoW;
143 return ret;
144 }
145
147 withCheckMerkleRoot(bool _checkMerkleRoot = true) const {
148 BlockValidationOptions ret = *this;
149 ret.checkMerkleRoot = _checkMerkleRoot;
150 return ret;
151 }
152
153 bool shouldValidatePoW() const { return checkPoW; }
155 uint64_t getExcessiveBlockSize() const { return excessiveBlockSize; }
156};
157
161void StartScriptCheckWorkerThreads(int threads_num);
162
167
168Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams);
169
170bool AbortNode(BlockValidationState &state, const std::string &strMessage,
171 const bilingual_str &userMessage = bilingual_str{});
172
177double GuessVerificationProgress(const ChainTxData &data,
178 const CBlockIndex *pindex);
179
181void PruneBlockFilesManual(Chainstate &active_chainstate,
182 int nManualPruneHeight);
183
184// clang-format off
207// clang-format on
210 enum class ResultType {
212 VALID,
214 INVALID,
216 MEMPOOL_ENTRY,
217 };
220
223
228 const std::optional<int64_t> m_vsize;
230 const std::optional<Amount> m_base_fees;
238 const std::optional<CFeeRate> m_effective_feerate;
245 const std::optional<std::vector<TxId>> m_txids_fee_calculations;
246
248 return MempoolAcceptResult(state);
249 }
250
252 FeeFailure(TxValidationState state, CFeeRate effective_feerate,
253 const std::vector<TxId> &txids_fee_calculations) {
254 return MempoolAcceptResult(state, effective_feerate,
255 txids_fee_calculations);
256 }
257
260 Success(int64_t vsize, Amount fees, CFeeRate effective_feerate,
261 const std::vector<TxId> &txids_fee_calculations) {
262 return MempoolAcceptResult(ResultType::VALID, vsize, fees,
263 effective_feerate, txids_fee_calculations);
264 }
265
270 static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees) {
271 return MempoolAcceptResult(vsize, fees);
272 }
273
274 // Private constructors. Use static methods MempoolAcceptResult::Success,
275 // etc. to construct.
276private:
279 : m_result_type(ResultType::INVALID), m_state(state),
280 m_base_fees(std::nullopt) {
281 // Can be invalid or error
282 Assume(!state.IsValid());
283 }
284
287 ResultType result_type, int64_t vsize, Amount fees,
288 CFeeRate effective_feerate,
289 const std::vector<TxId> &txids_fee_calculations)
290 : m_result_type(result_type), m_vsize{vsize}, m_base_fees(fees),
291 m_effective_feerate(effective_feerate),
292 m_txids_fee_calculations(txids_fee_calculations) {}
293
296 TxValidationState state, CFeeRate effective_feerate,
297 const std::vector<TxId> &txids_fee_calculations)
298 : m_result_type(ResultType::INVALID), m_state(state),
299 m_effective_feerate(effective_feerate),
300 m_txids_fee_calculations(txids_fee_calculations) {}
301
303 explicit MempoolAcceptResult(int64_t vsize, Amount fees)
304 : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize},
305 m_base_fees(fees) {}
306};
307
320 std::map<TxId, MempoolAcceptResult> m_tx_results;
321
324 std::map<TxId, MempoolAcceptResult> &&results)
325 : m_state{state}, m_tx_results(std::move(results)) {}
326
331 explicit PackageMempoolAcceptResult(const TxId &txid,
332 const MempoolAcceptResult &result)
333 : m_tx_results{{txid, result}} {}
334};
335
359AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx,
360 int64_t accept_time, bool bypass_limits,
361 bool test_accept = false, unsigned int heightOverride = 0)
363
376ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool,
377 const Package &txns, bool test_accept)
379
385protected:
386 std::atomic<int64_t> remaining;
387
388public:
389 explicit CheckInputsLimiter(int64_t limit) : remaining(limit) {}
390
391 bool consume_and_check(int consumed) {
392 auto newvalue = (remaining -= consumed);
393 return newvalue >= 0;
394 }
395
396 bool check() { return remaining >= 0; }
397};
398
400public:
402
403 // Let's make this bad boy copiable.
405 : CheckInputsLimiter(rhs.remaining.load()) {}
406
408 remaining = rhs.remaining.load();
409 return *this;
410 }
411
413 TxSigCheckLimiter txLimiter;
414 // Historically, there has not been a transaction with more than 20k sig
415 // checks on testnet or mainnet, so this effectively disable sigchecks.
416 txLimiter.remaining = 20000;
417 return txLimiter;
418 }
419};
420
450bool CheckInputScripts(const CTransaction &tx, TxValidationState &state,
451 const CCoinsViewCache &view, const uint32_t flags,
452 bool sigCacheStore, bool scriptCacheStore,
453 const PrecomputedTransactionData &txdata,
454 int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks,
455 CheckInputsLimiter *pBlockLimitSigChecks,
456 std::vector<CScriptCheck> *pvChecks)
458
462static inline bool
463CheckInputScripts(const CTransaction &tx, TxValidationState &state,
464 const CCoinsViewCache &view, const uint32_t flags,
465 bool sigCacheStore, bool scriptCacheStore,
466 const PrecomputedTransactionData &txdata, int &nSigChecksOut)
468 TxSigCheckLimiter nSigChecksTxLimiter;
469 return CheckInputScripts(tx, state, view, flags, sigCacheStore,
470 scriptCacheStore, txdata, nSigChecksOut,
471 nSigChecksTxLimiter, nullptr, nullptr);
472}
473
477void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
478 int nHeight);
479
483void UpdateCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo,
484 int nHeight);
485
504std::optional<LockPoints> CalculateLockPointsAtTip(CBlockIndex *tip,
505 const CCoinsView &coins_view,
506 const CTransaction &tx);
507
517bool CheckSequenceLocksAtTip(CBlockIndex *tip, const LockPoints &lock_points);
518
527private:
529 const CTransaction *ptxTo;
530 unsigned int nIn;
531 uint32_t nFlags;
538
539public:
540 CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn,
541 unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn,
542 const PrecomputedTransactionData &txdataIn,
543 TxSigCheckLimiter *pTxLimitSigChecksIn = nullptr,
544 CheckInputsLimiter *pBlockLimitSigChecksIn = nullptr)
545 : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn),
546 cacheStore(cacheIn), txdata(txdataIn),
547 pTxLimitSigChecks(pTxLimitSigChecksIn),
548 pBlockLimitSigChecks(pBlockLimitSigChecksIn) {}
549
550 CScriptCheck(const CScriptCheck &) = delete;
554
555 bool operator()();
556
557 ScriptError GetScriptError() const { return error; }
558
560};
561
562// CScriptCheck is used a lot in std::vector, make sure that's efficient
563static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
564static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
565static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
566
575bool CheckBlock(const CBlock &block, BlockValidationState &state,
576 const Consensus::Params &params,
577 BlockValidationOptions validationOptions);
578
586 const CBlockIndex &active_chain_tip, const Consensus::Params &params,
587 const CTransaction &tx, TxValidationState &state)
589
595 BlockValidationState &state, const CChainParams &params,
596 Chainstate &chainstate, const CBlock &block, CBlockIndex *pindexPrev,
597 const std::function<NodeClock::time_point()> &adjusted_time_callback,
599
603bool HasValidProofOfWork(const std::vector<CBlockHeader> &headers,
604 const Consensus::Params &consensusParams);
605
609bool IsBlockMutated(const CBlock &block);
610
612arith_uint256 CalculateHeadersWork(const std::vector<CBlockHeader> &headers);
613
614enum class VerifyDBResult {
615 SUCCESS,
617 INTERRUPTED,
620};
621
627private:
629
630public:
632
633public:
634 explicit CVerifyDB(kernel::Notifications &notifications);
635 ~CVerifyDB();
636
637 [[nodiscard]] VerifyDBResult VerifyDB(Chainstate &chainstate,
638 CCoinsView &coinsview,
639 int nCheckLevel, int nCheckDepth)
641};
642
645
656public:
660
664
667 std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
668
677 CoinsViews(DBParams db_params, CoinsViewOptions options);
678
680 void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
681};
682
685 CRITICAL = 2,
687 LARGE = 1,
688 OK = 0
689};
690
706protected:
712
716
719 std::unique_ptr<CoinsViews> m_coins_views;
720
733 bool m_disabled GUARDED_BY(::cs_main){false};
734
736
741 const CBlockIndex *m_avalancheFinalizedBlockIndex
742 GUARDED_BY(cs_avalancheFinalizedBlockIndex) = nullptr;
743
750 CRollingBloomFilter m_filterParkingPoliciesApplied =
751 CRollingBloomFilter{1000, 0.000001};
752
753 CBlockIndex const *m_best_fork_tip = nullptr;
754 CBlockIndex const *m_best_fork_base = nullptr;
755
757 const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};
758
759public:
763
768
769 explicit Chainstate(
770 CTxMemPool *mempool, node::BlockManager &blockman,
771 ChainstateManager &chainman,
772 std::optional<BlockHash> from_snapshot_blockhash = std::nullopt);
773
779
786 void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe,
787 std::string leveldb_name = "chainstate");
788
791 void InitCoinsCache(size_t cache_size_bytes)
793
797 bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
799 return m_coins_views && m_coins_views->m_cacheview;
800 }
801
805
812 const std::optional<BlockHash> m_from_snapshot_blockhash{};
813
819 const CBlockIndex *SnapshotBase() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
820
828 std::set<CBlockIndex *, CBlockIndexWorkComparator> setBlockIndexCandidates;
829
833 Assert(m_coins_views);
834 return *Assert(m_coins_views->m_cacheview);
835 }
836
840 return Assert(m_coins_views)->m_dbview;
841 }
842
844 CTxMemPool *GetMempool() { return m_mempool; }
845
851 return Assert(m_coins_views)->m_catcherview;
852 }
853
855 void ResetCoinsViews() { m_coins_views.reset(); }
856
858 bool HasCoinsViews() const { return (bool)m_coins_views; }
859
861 size_t m_coinsdb_cache_size_bytes{0};
862
864 size_t m_coinstip_cache_size_bytes{0};
865
868 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
870
882 bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode,
883 int nManualPruneHeight = 0);
884
886 void ForceFlushStateToDisk();
887
890 void PruneAndFlush();
891
912 bool ActivateBestChain(BlockValidationState &state,
913 std::shared_ptr<const CBlock> pblock = nullptr,
914 avalanche::Processor *const avalanche = nullptr)
915 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
916 !cs_avalancheFinalizedBlockIndex)
918
919 // Block (dis)connection on a given view:
920 DisconnectResult DisconnectBlock(const CBlock &block,
921 const CBlockIndex *pindex,
922 CCoinsViewCache &view)
924 bool ConnectBlock(const CBlock &block, BlockValidationState &state,
925 CBlockIndex *pindex, CCoinsViewCache &view,
927 Amount *blockFees = nullptr, bool fJustCheck = false)
929
930 // Apply the effects of a block disconnection on the UTXO set.
931 bool DisconnectTip(BlockValidationState &state,
932 DisconnectedBlockTransactions *disconnectpool)
934
935 // Manual block validity manipulation:
941 bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex,
942 avalanche::Processor *const avalanche = nullptr)
943 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
944 !cs_avalancheFinalizedBlockIndex)
949 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
950 !cs_avalancheFinalizedBlockIndex);
952 bool ParkBlock(BlockValidationState &state, CBlockIndex *pindex)
954 EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex,
955 !cs_avalancheFinalizedBlockIndex);
956
960 bool AvalancheFinalizeBlock(CBlockIndex *pindex,
961 avalanche::Processor &avalanche)
962 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
963
967 void ClearAvalancheFinalizedBlock()
968 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
969
973 bool IsBlockAvalancheFinalized(const CBlockIndex *pindex) const
974 EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex);
975
977 void SetBlockFailureFlags(CBlockIndex *pindex)
979
981 void ResetBlockFailureFlags(CBlockIndex *pindex)
983 template <typename F>
984 bool UpdateFlagsForBlock(CBlockIndex *pindexBase, CBlockIndex *pindex, F f)
986 template <typename F, typename C, typename AC>
987 void UpdateFlags(CBlockIndex *pindex, CBlockIndex *&pindexReset, F f,
988 C fChild, AC fAncestorWasChanged)
990
992 void UnparkBlockAndChildren(CBlockIndex *pindex)
994
996 void UnparkBlock(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
997
999 bool ReplayBlocks();
1000
1005 bool LoadGenesisBlock();
1006
1007 void TryAddBlockIndexCandidate(CBlockIndex *pindex)
1009
1010 void PruneBlockIndexCandidates();
1011
1012 void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1013
1015 const CBlockIndex *FindForkInGlobalIndex(const CBlockLocator &locator) const
1017
1019 void
1020 LoadMempool(const fs::path &load_path,
1021 fsbridge::FopenFn mockable_fopen_function = fsbridge::fopen);
1022
1025 bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1026
1030 CoinsCacheSizeState GetCoinsCacheSizeState()
1032
1034 GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes,
1035 size_t max_mempool_size_bytes)
1037
1039
1042 RecursiveMutex *MempoolMutex() const LOCK_RETURNED(m_mempool->cs) {
1043 return m_mempool ? &m_mempool->cs : nullptr;
1044 }
1045
1046private:
1047 bool ActivateBestChainStep(
1048 BlockValidationState &state, CBlockIndex *pindexMostWork,
1049 const std::shared_ptr<const CBlock> &pblock, bool &fInvalidFound,
1050 const avalanche::Processor *const avalanche = nullptr,
1053 !cs_avalancheFinalizedBlockIndex);
1054 bool ConnectTip(BlockValidationState &state,
1055 BlockPolicyValidationState &blockPolicyState,
1056 CBlockIndex *pindexNew,
1057 const std::shared_ptr<const CBlock> &pblock,
1058 DisconnectedBlockTransactions &disconnectpool,
1059 const avalanche::Processor *const avalanche = nullptr,
1060 ChainstateRole chainstate_role = ChainstateRole::NORMAL)
1062 !cs_avalancheFinalizedBlockIndex);
1063 void InvalidBlockFound(CBlockIndex *pindex,
1064 const BlockValidationState &state)
1065 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1066 CBlockIndex *
1067 FindMostWorkChain(std::vector<const CBlockIndex *> &blocksToReconcile,
1068 bool fAutoUnpark)
1069 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1070
1071 bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs)
1073
1074 void UnparkBlockImpl(CBlockIndex *pindex, bool fClearChildren)
1076
1077 bool UnwindBlock(BlockValidationState &state, CBlockIndex *pindex,
1078 bool invalidate)
1079 EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex,
1080 !cs_avalancheFinalizedBlockIndex);
1081
1082 void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1083 void CheckForkWarningConditionsOnNewFork(CBlockIndex *pindexNewForkTip)
1085 void InvalidChainFound(CBlockIndex *pindexNew)
1086 EXCLUSIVE_LOCKS_REQUIRED(cs_main, !cs_avalancheFinalizedBlockIndex);
1087
1088 const CBlockIndex *FindBlockToFinalize(CBlockIndex *pindexNew)
1090
1094 void UpdateTip(const CBlockIndex *pindexNew)
1096
1097 std::chrono::microseconds m_last_write{0};
1098 std::chrono::microseconds m_last_flush{0};
1099
1104 [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk()
1106
1108};
1109
1111 SUCCESS,
1112 SKIPPED,
1113
1114 // Expected assumeutxo configuration data is not found for the height of the
1115 // base block.
1117
1118 // Failed to generate UTXO statistics (to check UTXO set hash) for the
1119 // background chainstate.
1121
1122 // The UTXO set hash of the background validation chainstate does not match
1123 // the one expected by assumeutxo chainparams.
1125
1126 // The blockhash of the current tip of the background validation chainstate
1127 // does not match the one expected by the snapshot chainstate.
1129};
1130
1159private:
1175 std::unique_ptr<Chainstate> m_ibd_chainstate GUARDED_BY(::cs_main);
1176
1186 std::unique_ptr<Chainstate> m_snapshot_chainstate GUARDED_BY(::cs_main);
1187
1194 Chainstate *m_active_chainstate GUARDED_BY(::cs_main){nullptr};
1195
1196 CBlockIndex *m_best_invalid GUARDED_BY(::cs_main){nullptr};
1197 CBlockIndex *m_best_parked GUARDED_BY(::cs_main){nullptr};
1198
1206 [[nodiscard]] bool
1207 PopulateAndValidateSnapshot(Chainstate &snapshot_chainstate,
1208 AutoFile &coins_file,
1209 const node::SnapshotMetadata &metadata);
1218 bool AcceptBlockHeader(
1219 const CBlockHeader &block, BlockValidationState &state,
1220 CBlockIndex **ppindex, bool min_pow_checked,
1221 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1224
1230 bool IsUsable(const Chainstate *const pchainstate) const
1232 return pchainstate && !pchainstate->m_disabled;
1233 }
1234
1236 SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main){};
1237
1238public:
1240
1241 explicit ChainstateManager(Options options,
1242 node::BlockManager::Options blockman_options);
1243
1246 std::function<void()> snapshot_download_completed = std::function<void()>();
1247
1248 const Config &GetConfig() const { return m_options.config; }
1249
1250 const CChainParams &GetParams() const {
1251 return m_options.config.GetChainParams();
1252 }
1254 return m_options.config.GetChainParams().GetConsensus();
1255 }
1257 return *Assert(m_options.check_block_index);
1258 }
1260 return *Assert(m_options.minimum_chain_work);
1261 }
1263 return *Assert(m_options.assumed_valid_block);
1264 }
1266 return m_options.notifications;
1267 };
1268
1275 void CheckBlockIndex();
1276
1290 }
1291
1293 std::thread m_thread_load;
1297
1305 mutable std::atomic<bool> m_cached_finished_ibd{false};
1306
1312 std::atomic<int32_t> nBlockSequenceId{1};
1313
1315 int32_t nBlockReverseSequenceId = -1;
1317 arith_uint256 nLastPreciousChainwork = 0;
1318
1319 // Reset the memory-only sequence counters we use to track block arrival
1320 // (used by tests to reset state)
1323 nBlockSequenceId = 1;
1324 nBlockReverseSequenceId = -1;
1325 }
1326
1346 std::set<CBlockIndex *> m_failed_blocks;
1347
1352 CBlockIndex *m_best_header GUARDED_BY(::cs_main){nullptr};
1353
1356 int64_t m_total_coinstip_cache{0};
1357 //
1360 int64_t m_total_coinsdb_cache{0};
1361
1365 // constructor
1366 Chainstate &InitializeChainstate(CTxMemPool *mempool)
1368
1370 std::vector<Chainstate *> GetAll();
1371
1385 [[nodiscard]] util::Result<CBlockIndex *>
1386 ActivateSnapshot(AutoFile &coins_file,
1387 const node::SnapshotMetadata &metadata, bool in_memory);
1388
1396 SnapshotCompletionResult MaybeCompleteSnapshotValidation(
1397 std::function<void(bilingual_str)> shutdown_fnc =
1398 [](bilingual_str msg) { AbortNode(msg.original, msg); })
1400
1402 const CBlockIndex *GetSnapshotBaseBlock() const
1404
1406 Chainstate &ActiveChainstate() const;
1407 CChain &ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1408 return ActiveChainstate().m_chain;
1409 }
1410 int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1411 return ActiveChain().Height();
1412 }
1414 return ActiveChain().Tip();
1415 }
1416
1419 return IsUsable(m_snapshot_chainstate.get()) &&
1420 IsUsable(m_ibd_chainstate.get());
1421 }
1422
1425 EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) {
1426 return BackgroundSyncInProgress() ? m_ibd_chainstate->m_chain.Tip()
1427 : nullptr;
1428 }
1429
1432 return m_blockman.m_block_index;
1433 }
1434
1437 bool IsSnapshotActive() const;
1438
1439 std::optional<BlockHash> SnapshotBlockhash() const;
1440
1443 return m_snapshot_chainstate && m_ibd_chainstate &&
1444 m_ibd_chainstate->m_disabled;
1445 }
1446
1451 bool IsInitialBlockDownload() const;
1452
1484 void LoadExternalBlockFile(FILE *fileIn, FlatFilePos *dbp = nullptr,
1485 std::multimap<BlockHash, FlatFilePos>
1486 *blocks_with_unknown_parent = nullptr,
1487 avalanche::Processor *const avalanche = nullptr);
1488
1516 bool ProcessNewBlock(const std::shared_ptr<const CBlock> &block,
1517 bool force_processing, bool min_pow_checked,
1518 bool *new_block,
1519 avalanche::Processor *const avalanche = nullptr)
1521
1537 bool ProcessNewBlockHeaders(
1538 const std::vector<CBlockHeader> &block, bool min_pow_checked,
1539 BlockValidationState &state, const CBlockIndex **ppindex = nullptr,
1540 const std::optional<CCheckpointData> &test_checkpoints = std::nullopt)
1542
1561 bool AcceptBlock(const std::shared_ptr<const CBlock> &pblock,
1562 BlockValidationState &state, bool fRequested,
1563 const FlatFilePos *dbp, bool *fNewBlock,
1564 bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1565
1566 void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew,
1567 const FlatFilePos &pos)
1569
1578 [[nodiscard]] MempoolAcceptResult
1579 ProcessTransaction(const CTransactionRef &tx, bool test_accept = false)
1581
1584 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1585
1588 void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1589
1596 void ReportHeadersPresync(const arith_uint256 &work, int64_t height,
1597 int64_t timestamp);
1598
1601 bool DetectSnapshotChainstate(CTxMemPool *mempool)
1603
1604 void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1605
1608 [[nodiscard]] bool DeleteSnapshotChainstate()
1610
1613 Chainstate &ActivateExistingSnapshot(BlockHash base_blockhash)
1615
1625 bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1626
1635 Chainstate &GetChainstateForIndexing() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1636
1640 std::pair<int, int> GetPruneRange(const Chainstate &chainstate,
1641 int last_height_can_prune)
1643
1646 std::optional<int> GetSnapshotBaseHeight() const
1648
1652 void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1653
1655 bool DumpRecentHeadersTime(const fs::path &filePath) const
1656 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1658 bool LoadRecentHeadersTime(const fs::path &filePath)
1659 EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1660};
1661
1663template <typename DEP>
1664bool DeploymentActiveAfter(const CBlockIndex *pindexPrev,
1665 const ChainstateManager &chainman, DEP dep) {
1666 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep);
1667}
1668
1669template <typename DEP>
1671 const ChainstateManager &chainman, DEP dep) {
1672 return DeploymentActiveAt(index, chainman.GetConsensus(), dep);
1673}
1674
1675#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:528
uint64_t getExcessiveBlockSize() const
Definition: validation.h:155
BlockValidationOptions withCheckPoW(bool _checkPoW=true) const
Definition: validation.h:140
BlockValidationOptions(uint64_t _excessiveBlockSize, bool _checkPow=true, bool _checkMerkleRoot=true)
Definition: validation.h:134
BlockValidationOptions withCheckMerkleRoot(bool _checkMerkleRoot=true) const
Definition: validation.h:147
BlockValidationOptions(const Config &config)
Definition: validation.cpp:122
bool shouldValidatePoW() const
Definition: validation.h:153
uint64_t excessiveBlockSize
Definition: validation.h:127
bool shouldValidateMerkleRoot() const
Definition: validation.h:154
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:134
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:221
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:65
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:374
Abstract view on the open txout dataset.
Definition: coins.h:163
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
Closure representing one script verification.
Definition: validation.h:526
CScriptCheck & operator=(CScriptCheck &&)=default
bool operator()()
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, uint32_t nFlagsIn, bool cacheIn, const PrecomputedTransactionData &txdataIn, TxSigCheckLimiter *pTxLimitSigChecksIn=nullptr, CheckInputsLimiter *pBlockLimitSigChecksIn=nullptr)
Definition: validation.h:540
ScriptError GetScriptError() const
Definition: validation.h:557
ScriptExecutionMetrics GetScriptExecutionMetrics() const
Definition: validation.h:559
CScriptCheck(const CScriptCheck &)=delete
uint32_t nFlags
Definition: validation.h:531
TxSigCheckLimiter * pTxLimitSigChecks
Definition: validation.h:536
ScriptExecutionMetrics metrics
Definition: validation.h:534
CTxOut m_tx_out
Definition: validation.h:528
CScriptCheck(CScriptCheck &&)=default
bool cacheStore
Definition: validation.h:532
ScriptError error
Definition: validation.h:533
PrecomputedTransactionData txdata
Definition: validation.h:535
const CTransaction * ptxTo
Definition: validation.h:529
unsigned int nIn
Definition: validation.h:530
CheckInputsLimiter * pBlockLimitSigChecks
Definition: validation.h:537
CScriptCheck & operator=(const CScriptCheck &)=delete
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:214
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:310
An output of a transaction.
Definition: transaction.h:128
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:626
VerifyDBResult VerifyDB(Chainstate &chainstate, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:628
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:705
Mutex m_chainstate_mutex
The ChainState Mutex.
Definition: validation.h:711
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:804
bool HasCoinsViews() const
Does this chainstate have a UTXO set attached?
Definition: validation.h:858
CTxMemPool * GetMempool()
Definition: validation.h:844
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:848
Mutex cs_avalancheFinalizedBlockIndex
Definition: validation.h:735
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:715
bool m_disabled GUARDED_BY(::cs_main)
This toggle exists for use when doing background validation for UTXO snapshots.
Definition: validation.h:733
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:838
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:767
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:719
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:855
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:762
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:757
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1158
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:1430
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.h:1352
const Config & GetConfig() const
Definition: validation.h:1248
const CBlockIndex * GetBackgroundSyncTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The tip of the background sync chain.
Definition: validation.h:1424
std::thread m_thread_load
Definition: validation.h:1293
kernel::Notifications & GetNotifications() const
Definition: validation.h:1265
SteadyMilliseconds m_last_presync_update GUARDED_BY(::cs_main)
Most recent headers presync progress update, for rate-limiting.
Definition: validation.h:1236
bool ShouldCheckBlockIndex() const
Definition: validation.h:1256
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1288
bool IsSnapshotValidated() const EXCLUSIVE_LOCKS_REQUIRED(
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:1442
bool IsUsable(const Chainstate *const pchainstate) const EXCLUSIVE_LOCKS_REQUIRED(
Return true if a chainstate is considered usable.
Definition: validation.h:1230
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1413
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:1196
bool BackgroundSyncInProgress() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
The state of a background sync (for net processing)
Definition: validation.h:1418
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1410
const CChainParams & GetParams() const
Definition: validation.h:1250
const Consensus::Params & GetConsensus() const
Definition: validation.h:1253
CBlockIndex *m_best_parked GUARDED_BY(::cs_main)
Definition: validation.h:1197
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1259
const Options m_options
Definition: validation.h:1292
Chainstate *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:1194
const BlockHash & AssumedValidBlock() const
Definition: validation.h:1262
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1370
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:1346
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:1321
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1296
Simple class for regulating resource usage during CheckInputScripts (and CScriptCheck),...
Definition: validation.h:384
bool consume_and_check(int consumed)
Definition: validation.h:391
std::atomic< int64_t > remaining
Definition: validation.h:386
CheckInputsLimiter(int64_t limit)
Definition: validation.h:389
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:655
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
static TxSigCheckLimiter getDisabled()
Definition: validation.h:412
TxSigCheckLimiter & operator=(const TxSigCheckLimiter &rhs)
Definition: validation.h:407
TxSigCheckLimiter(const TxSigCheckLimiter &rhs)
Definition: validation.h:404
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:104
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:30
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:198
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:62
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
@ PERIODIC
Called by RandAddPeriodic()
ScriptError
Definition: script_error.h:11
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
Definition: amount.h:19
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:109
Holds various statistics on transactions within a chain.
Definition: chainparams.h:73
User-controlled performance and debug options.
Definition: txdb.h:56
Parameters that influence chain consensus.
Definition: params.h:34
Application-specific storage settings.
Definition: dbwrapper.h:32
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:208
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigchecks.
Definition: validation.h:228
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:286
const ResultType m_result_type
Result type.
Definition: validation.h:219
const std::optional< std::vector< TxId > > m_txids_fee_calculations
Contains the txids of the transactions used for fee-related checks.
Definition: validation.h:245
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:278
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:222
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:295
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:210
@ VALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:247
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:238
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< TxId > &txids_fee_calculations)
Definition: validation.h:252
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:260
static MempoolAcceptResult MempoolTx(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:270
MempoolAcceptResult(int64_t vsize, Amount fees)
Constructor for already-in-mempool case.
Definition: validation.h:303
const std::optional< Amount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:230
std::chrono::time_point< NodeClock > time_point
Definition: time.h:19
Validation result for package mempool acceptance.
Definition: validation.h:311
PackageMempoolAcceptResult(const TxId &txid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a MempoolAcceptResult.
Definition: validation.h:331
PackageMempoolAcceptResult(PackageValidationState state, std::map< TxId, MempoolAcceptResult > &&results)
Definition: validation.h:322
PackageValidationState m_state
Definition: validation.h:312
std::map< TxId, MempoolAcceptResult > m_tx_results
Map from txid to finished MempoolAcceptResults.
Definition: validation.h:320
Precompute sighash midstate to avoid quadratic hashing.
Definition: transaction.h:325
Struct for holding cumulative results from executing a script or a sequence of scripts.
A TxId is the identifier of a transaction.
Definition: txid.h:14
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
An options struct for 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
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state)
AssertLockHeld(pool.cs)
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
bool ContextualCheckTransactionForCurrentBlock(const CBlockIndex &active_chain_tip, const Consensus::Params &params, const CTransaction &tx, TxValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(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)
This is a variant of ContextualCheckTransaction which computes the contextual check for a transaction...
Definition: validation.h:594
GlobalMutex g_best_block_mutex
Definition: validation.cpp:118
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
std::condition_variable g_best_block_cv
Definition: validation.cpp:119
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:185
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:98
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:112
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:209
bool CheckInputScripts(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &view, const uint32_t flags, bool sigCacheStore, bool scriptCacheStore, const PrecomputedTransactionData &txdata, int &nSigChecksOut, TxSigCheckLimiter &txLimitSigChecks, CheckInputsLimiter *pBlockLimitSigChecks, std::vector< CScriptCheck > *pvChecks) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check whether all of this transaction's input scripts succeed.
static const unsigned int 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:96
const CBlockIndex * g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:120
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:1664
SnapshotCompletionResult
Definition: validation.h:1110
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:84
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:115
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:86
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept=false, unsigned int heightOverride=0) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
VerifyDBResult
Definition: validation.h:614
void SpendCoins(CCoinsViewCache &view, const CTransaction &tx, CTxUndo &txundo, int nHeight)
Mark all the coins corresponding to a given transaction inputs as spent.
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &params, BlockValidationOptions validationOptions)
Functions for validating blocks and updating the block tree.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:100
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:683
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
bool DeploymentActiveAt(const CBlockIndex &index, const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1670
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:97
FlushStateMode
Definition: validation.h:644
static const bool DEFAULT_PEERBLOOMFILTERS
Definition: validation.h:88
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:91