Bitcoin Core 31.99.0
P2P Digital Currency
validation.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-present The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#ifndef BITCOIN_VALIDATION_H
7#define BITCOIN_VALIDATION_H
8
9#include <arith_uint256.h>
10#include <attributes.h>
11#include <chain.h>
12#include <checkqueue.h>
13#include <coins.h>
14#include <consensus/amount.h>
15#include <cuckoocache.h>
16#include <deploymentstatus.h>
17#include <kernel/chain.h>
18#include <kernel/chainparams.h>
20#include <kernel/cs_main.h> // IWYU pragma: export
21#include <node/blockstorage.h>
22#include <policy/feerate.h>
23#include <policy/packages.h>
24#include <policy/policy.h>
25#include <script/script_error.h>
26#include <script/sigcache.h>
27#include <script/verify_flags.h>
28#include <sync.h>
29#include <txdb.h>
30#include <txmempool.h>
31#include <uint256.h>
32#include <util/byte_units.h>
33#include <util/check.h>
34#include <util/fs.h>
35#include <util/hasher.h>
36#include <util/result.h>
37#include <util/time.h>
38#include <util/translation.h>
39#include <versionbits.h>
40
41#include <algorithm>
42#include <atomic>
43#include <cstdint>
44#include <map>
45#include <memory>
46#include <optional>
47#include <set>
48#include <span>
49#include <string>
50#include <type_traits>
51#include <utility>
52#include <vector>
53
54class Chainstate;
55class CTxMemPool;
57struct ChainTxData;
60struct LockPoints;
61struct AssumeutxoData;
62namespace kernel {
63struct ChainstateRole;
64} // namespace kernel
65namespace node {
66class SnapshotMetadata;
67} // namespace node
68namespace Consensus {
69struct Params;
70} // namespace Consensus
71namespace util {
72class SignalInterrupt;
73} // namespace util
74
76static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
77static const signed int DEFAULT_CHECKBLOCKS = 6;
78static constexpr int DEFAULT_CHECKLEVEL{3};
79// Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
80// At 1MB per block, 288 blocks = 288MB.
81// Add 15% for Undo data = 331MB
82// Add 20% for Orphan block rate = 397MB
83// We want the low water mark after pruning to be at least 397 MB and since we prune in
84// full block file chunks, we need the high water mark which triggers the prune to be
85// one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
86// Setting the target to >= 550 MiB will make it likely we can respect the target.
87static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES{550_MiB};
88
90static constexpr int MAX_SCRIPTCHECK_THREADS{15};
91
93static constexpr int32_t MAX_PREVOUTFETCH_THREADS{16};
94
100};
101
103extern const std::vector<std::string> CHECKLEVEL_DOC;
104
105CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
106
107bool FatalError(kernel::Notifications& notifications, BlockValidationState& state, const bilingual_str& message);
108
110void PruneBlockFilesManual(Chainstate& active_chainstate, int nManualPruneHeight);
111
136 enum class ResultType {
137 VALID,
138 INVALID,
139 MEMPOOL_ENTRY,
140 DIFFERENT_WITNESS,
141 };
144
147
149 const std::list<CTransactionRef> m_replaced_transactions;
151 const std::optional<int64_t> m_vsize;
153 const std::optional<CAmount> m_base_fees;
159 const std::optional<CFeeRate> m_effective_feerate;
165 const std::optional<std::vector<Wtxid>> m_wtxids_fee_calculations;
166
168 const std::optional<Wtxid> m_other_wtxid;
169
171 return MempoolAcceptResult(state);
172 }
173
175 CFeeRate effective_feerate,
176 const std::vector<Wtxid>& wtxids_fee_calculations) {
177 return MempoolAcceptResult(state, effective_feerate, wtxids_fee_calculations);
178 }
179
180 static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns,
181 int64_t vsize,
182 CAmount fees,
183 CFeeRate effective_feerate,
184 const std::vector<Wtxid>& wtxids_fee_calculations) {
185 return MempoolAcceptResult(std::move(replaced_txns), vsize, fees,
186 effective_feerate, wtxids_fee_calculations);
187 }
188
189 static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees) {
190 return MempoolAcceptResult(vsize, fees);
191 }
192
194 return MempoolAcceptResult(other_wtxid);
195 }
196
197// Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
198private:
201 : m_result_type(ResultType::INVALID), m_state(state) {
202 Assume(!state.IsValid()); // Can be invalid or error
203 }
204
206 explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns,
207 int64_t vsize,
208 CAmount fees,
209 CFeeRate effective_feerate,
210 const std::vector<Wtxid>& wtxids_fee_calculations)
211 : m_result_type(ResultType::VALID),
212 m_replaced_transactions(std::move(replaced_txns)),
213 m_vsize{vsize},
214 m_base_fees(fees),
215 m_effective_feerate(effective_feerate),
216 m_wtxids_fee_calculations(wtxids_fee_calculations) {}
217
220 CFeeRate effective_feerate,
221 const std::vector<Wtxid>& wtxids_fee_calculations)
222 : m_result_type(ResultType::INVALID),
223 m_state(state),
224 m_effective_feerate(effective_feerate),
225 m_wtxids_fee_calculations(wtxids_fee_calculations) {}
226
228 explicit MempoolAcceptResult(int64_t vsize, CAmount fees)
229 : m_result_type(ResultType::MEMPOOL_ENTRY), m_vsize{vsize}, m_base_fees(fees) {}
230
232 explicit MempoolAcceptResult(const Wtxid& other_wtxid)
233 : m_result_type(ResultType::DIFFERENT_WITNESS), m_other_wtxid(other_wtxid) {}
234};
235
240{
248 std::map<Wtxid, MempoolAcceptResult> m_tx_results;
249
251 std::map<Wtxid, MempoolAcceptResult>&& results)
252 : m_state{state}, m_tx_results(std::move(results)) {}
253
255 std::map<Wtxid, MempoolAcceptResult>&& results)
256 : m_state{state}, m_tx_results(std::move(results)) {}
257
259 explicit PackageMempoolAcceptResult(const Wtxid& wtxid, const MempoolAcceptResult& result)
260 : m_tx_results{ {wtxid, result} } {}
261};
262
278 int64_t accept_time, bool bypass_limits, bool test_accept)
280
292 const Package& txns, bool test_accept, const std::optional<CFeeRate>& client_maxfeerate)
294
295/* Mempool validation helper functions */
296
300bool CheckFinalTxAtTip(const CBlockIndex& active_chain_tip, const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
301
320std::optional<LockPoints> CalculateLockPointsAtTip(
321 CBlockIndex* tip,
322 const CCoinsView& coins_view,
323 const CTransaction& tx);
324
335 const LockPoints& lock_points);
336
342{
343private:
346 unsigned int nIn;
351
352public:
353 CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, SignatureCache& signature_cache, unsigned int nInIn, script_verify_flags flags, bool cacheIn, PrecomputedTransactionData* txdataIn) :
354 m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), m_flags(flags), cacheStore(cacheIn), txdata(txdataIn), m_signature_cache(&signature_cache) { }
355
356 CScriptCheck(const CScriptCheck&) = delete;
360
361 std::optional<std::pair<ScriptError, std::string>> operator()();
362};
363
364// CScriptCheck is used a lot in std::vector, make sure that's efficient
365static_assert(std::is_nothrow_move_assignable_v<CScriptCheck>);
366static_assert(std::is_nothrow_move_constructible_v<CScriptCheck>);
367static_assert(std::is_nothrow_destructible_v<CScriptCheck>);
368
374{
375private:
378
379public:
382
383 ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes);
384
387
390};
391
395bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
396
415 Chainstate& chainstate,
416 const CBlock& block,
417 bool check_pow,
418 bool check_merkle_root) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
419
421bool HasValidProofOfWork(std::span<const CBlockHeader> headers, const Consensus::Params& consensusParams);
422
424bool IsBlockMutated(const CBlock& block, bool check_witness_root);
425
427arith_uint256 CalculateClaimedHeadersWork(std::span<const CBlockHeader> headers);
428
429enum class VerifyDBResult {
430 SUCCESS,
432 INTERRUPTED,
435};
436
439{
440private:
442
443public:
444 explicit CVerifyDB(kernel::Notifications& notifications);
445 ~CVerifyDB();
446 [[nodiscard]] VerifyDBResult VerifyDB(
447 Chainstate& chainstate,
448 const Consensus::Params& consensus_params,
449 CCoinsView& coinsview,
450 int nCheckLevel,
451 int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
452};
453
455{
456 DISCONNECT_OK, // All good.
457 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
458 DISCONNECT_FAILED // Something else went wrong.
460
461struct ConnectedBlock;
462
464inline constexpr std::array FlushStateModeNames{"NONE", "IF_NEEDED", "PERIODIC", "FORCE_FLUSH", "FORCE_SYNC"};
465enum class FlushStateMode: uint8_t {
466 NONE,
467 IF_NEEDED,
468 PERIODIC,
471};
472
483
484public:
488
491
494 std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
495
498 std::unique_ptr<CoinsViewOverlay> m_connect_block_view GUARDED_BY(cs_main);
499
506 CoinsViews(DBParams db_params, CoinsViewOptions options);
507
509 void InitCache(int32_t prevoutfetch_threads) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
510};
511
513{
515 CRITICAL = 2,
517 LARGE = 1,
518 OK = 0
519};
520
521constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept
522{
523 // No periodic flush needed if at least this much space is free
524 constexpr int64_t MAX_BLOCK_COINSDB_USAGE_BYTES{int64_t(10_MiB)};
525 return std::max((total_space * 9) / 10,
526 total_space - MAX_BLOCK_COINSDB_USAGE_BYTES);
527}
528
530enum class Assumeutxo {
532 VALIDATED,
536 INVALID,
537};
538
554{
555protected:
562
566
568 std::unique_ptr<CoinsViews> m_coins_views;
569
571 mutable const CBlockIndex* m_cached_snapshot_base GUARDED_BY(::cs_main){nullptr};
572
574 mutable const CBlockIndex* m_cached_target_block GUARDED_BY(::cs_main){nullptr};
575
576 std::optional<const char*> m_last_script_check_reason_logged GUARDED_BY(::cs_main){};
577
578public:
582
587
588 explicit Chainstate(
589 CTxMemPool* mempool,
590 node::BlockManager& blockman,
591 ChainstateManager& chainman,
592 std::optional<uint256> from_snapshot_blockhash = std::nullopt);
593
595 fs::path StoragePath() const;
596
602
609 void InitCoinsDB(
610 size_t cache_size_bytes,
611 bool in_memory,
612 bool should_wipe);
613
616 void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
617
621 {
623 return m_coins_views && m_coins_views->m_cacheview;
624 }
625
629
634
640 const std::optional<uint256> m_from_snapshot_blockhash;
641
646 std::optional<uint256> m_target_blockhash GUARDED_BY(::cs_main);
647
650 std::optional<AssumeutxoHash> m_target_utxohash GUARDED_BY(::cs_main);
651
657 const CBlockIndex* SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
658
662 const CBlockIndex* TargetBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
666 void SetTargetBlock(CBlockIndex* block) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
669 void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
670
673 {
674 const CBlockIndex* target_block{TargetBlock()};
675 assert(!target_block || target_block->GetAncestor(m_chain.Height()) == m_chain.Tip());
676 return target_block && target_block == m_chain.Tip();
677 }
678
686 std::set<CBlockIndex*, node::CBlockIndexWorkComparator> setBlockIndexCandidates;
687
690 {
693 return *Assert(m_coins_views->m_cacheview);
694 }
695
698 {
700 return Assert(m_coins_views)->m_dbview;
701 }
702
705 {
706 return m_mempool;
707 }
708
712 {
714 return Assert(m_coins_views)->m_catcherview;
715 }
716
718 void ResetCoinsViews() { m_coins_views.reset(); }
719
722
725
728 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
730
742 bool FlushStateToDisk(
744 FlushStateMode mode,
745 int nManualPruneHeight = 0);
746
748 void ForceFlushStateToDisk(bool wipe_cache = true);
749
752 void PruneAndFlush();
753
775 bool ActivateBestChain(
777 std::shared_ptr<const CBlock> pblock = nullptr)
780
781 // Block (dis)connection on a given view:
782 DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
784 bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
785 CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
786
787 // Apply the effects of a block disconnection on the UTXO set.
789
790 // Manual block validity manipulation:
795 bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex)
798
803
805 void SetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
806
809
811 bool ReplayBlocks();
812
814 [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
815
818
820
821 void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
822
824 void PopulateBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
825
828
831
835 CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
836
837 CoinsCacheSizeState GetCoinsCacheSizeState(
838 size_t max_coins_cache_size_bytes,
839 size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
840
842
844 const CBlockIndex* GetLastFlushedBlock() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main) { return m_last_flushed_block; }
845
848 {
849 return m_mempool ? &m_mempool->cs : nullptr;
850 }
851
855 std::pair<int, int> GetPruneRange(int last_height_can_prune) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
856
857protected:
858 bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex& index_most_work, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, std::vector<ConnectedBlock>& connected_blocks) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
859 bool ConnectTip(
861 CBlockIndex* pindexNew,
862 std::shared_ptr<const CBlock> block_to_connect,
863 std::vector<ConnectedBlock>& connected_blocks,
865
868
870
873
888 DisconnectedBlockTransactions& disconnectpool,
890
892 void UpdateTip(const CBlockIndex* pindexNew)
894
895 NodeClock::time_point m_next_write{NodeClock::time_point::max()};
896 const CBlockIndex* m_last_flushed_block GUARDED_BY(::cs_main){nullptr};
897
902 [[nodiscard]] util::Result<void> InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
903
905};
906
908 SUCCESS,
909 SKIPPED,
910
911 // Expected assumeutxo configuration data is not found for the height of the
912 // base block.
914
915 // Failed to generate UTXO statistics (to check UTXO set hash) for the
916 // validated chainstate.
918
919 // The UTXO set hash of the validated chainstate does not match the one
920 // expected by assumeutxo chainparams.
922};
923
945{
946private:
947
949 CBlockIndex* m_last_notified_header GUARDED_BY(GetMutex()){nullptr};
950
951 bool NotifyHeaderTip() LOCKS_EXCLUDED(GetMutex());
952
960 [[nodiscard]] util::Result<void> PopulateAndValidateSnapshot(
961 Chainstate& snapshot_chainstate,
962 AutoFile& coins_file,
963 const node::SnapshotMetadata& metadata);
964
972 bool AcceptBlockHeader(
973 const CBlockHeader& block,
975 CBlockIndex** ppindex,
976 bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
978
980 MockableSteadyClock::time_point m_last_presync_update GUARDED_BY(GetMutex()){};
981
984
987 SteadyClock::duration GUARDED_BY(::cs_main) time_check{};
988 SteadyClock::duration GUARDED_BY(::cs_main) time_forks{};
989 SteadyClock::duration GUARDED_BY(::cs_main) time_connect{};
990 SteadyClock::duration GUARDED_BY(::cs_main) time_verify{};
991 SteadyClock::duration GUARDED_BY(::cs_main) time_undo{};
992 SteadyClock::duration GUARDED_BY(::cs_main) time_index{};
993 SteadyClock::duration GUARDED_BY(::cs_main) time_total{};
994 int64_t GUARDED_BY(::cs_main) num_blocks_total{0};
995 SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total{};
996 SteadyClock::duration GUARDED_BY(::cs_main) time_flush{};
997 SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate{};
998 SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect{};
999
1000protected:
1001 CBlockIndex* m_best_invalid GUARDED_BY(::cs_main){nullptr};
1002
1003public:
1005
1006 explicit ChainstateManager(const util::SignalInterrupt& interrupt, Options options, node::BlockManager::Options blockman_options);
1007
1010 std::function<void()> snapshot_download_completed = std::function<void()>();
1011
1012 const CChainParams& GetParams() const { return m_options.chainparams; }
1013 const Consensus::Params& GetConsensus() const { return m_options.chainparams.GetConsensus(); }
1014 bool ShouldCheckBlockIndex() const;
1015 const arith_uint256& MinimumChainWork() const { return *Assert(m_options.minimum_chain_work); }
1016 const uint256& AssumedValidBlock() const { return *Assert(m_options.assumed_valid_block); }
1017 kernel::Notifications& GetNotifications() const { return m_options.notifications; };
1018
1024 void CheckBlockIndex() const;
1025
1038
1044
1046
1054 std::atomic_bool m_cached_is_ibd{true};
1055
1063 int32_t nBlockSequenceId GUARDED_BY(::cs_main) = SEQ_ID_INIT_FROM_DISK + 1;
1065 int32_t nBlockReverseSequenceId = -1;
1067 arith_uint256 nLastPreciousChainwork = 0;
1068
1069 // Reset the memory-only sequence counters we use to track block arrival
1070 // (used by tests to reset state)
1072 {
1074 nBlockSequenceId = SEQ_ID_INIT_FROM_DISK + 1;
1075 nBlockReverseSequenceId = -1;
1076 }
1077
1078
1083 CBlockIndex* m_best_header GUARDED_BY(::cs_main){nullptr};
1084
1087 size_t m_total_coinstip_cache{0};
1088 //
1091 size_t m_total_coinsdb_cache{0};
1092
1094 [[nodiscard]] bool LoadGenesisBlock();
1095
1099 // constructor
1100 Chainstate& InitializeChainstate(CTxMemPool* mempool) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1101
1114 AutoFile& coins_file, const node::SnapshotMetadata& metadata, bool in_memory);
1115
1124 SnapshotCompletionResult MaybeValidateSnapshot(Chainstate& validated_cs, Chainstate& unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1125
1128 {
1129 for (auto& cs : m_chainstates) {
1130 if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && !cs->m_target_blockhash) return *cs;
1131 }
1132 abort();
1133 }
1134
1137 {
1138 for (auto& cs : m_chainstates) {
1139 if (cs && cs->m_assumeutxo != Assumeutxo::INVALID && cs->m_target_blockhash && !cs->m_target_utxohash) return cs.get();
1140 }
1141 return nullptr;
1142 }
1143
1148 {
1149 for (auto* cs : {&CurrentChainstate(), HistoricalChainstate()}) {
1150 if (cs && cs->m_assumeutxo == Assumeutxo::VALIDATED) return *cs;
1151 }
1152 abort();
1153 }
1154
1156 std::unique_ptr<Chainstate> RemoveChainstate(Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
1157 {
1158 auto it{std::find_if(m_chainstates.begin(), m_chainstates.end(), [&](auto& cs) { return cs.get() == &chainstate; })};
1159 if (it != m_chainstates.end()) {
1160 auto ret{std::move(*it)};
1161 m_chainstates.erase(it);
1162 return ret;
1163 }
1164 return nullptr;
1165 }
1166
1172 Chainstate& ActiveChainstate() const;
1173 CChain& ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChainstate().m_chain; }
1174 int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Height(); }
1175 CBlockIndex* ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex()) { return ActiveChain().Tip(); }
1177
1189 void UpdateIBDStatus() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1190
1192 {
1194 return m_blockman.m_block_index;
1195 }
1196
1201
1203 bool IsInitialBlockDownload() const noexcept;
1204
1209 double GuessVerificationProgress(const CBlockIndex* pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1210
1212 double GetBackgroundVerificationProgress(const CBlockIndex& pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex());
1213
1241 AutoFile& file_in,
1242 FlatFilePos* dbp = nullptr,
1243 std::multimap<uint256, FlatFilePos>* blocks_with_unknown_parent = nullptr);
1244
1269 bool ProcessNewBlock(const std::shared_ptr<const CBlock>& block, bool force_processing, bool min_pow_checked, bool* new_block) LOCKS_EXCLUDED(cs_main);
1270
1283 bool ProcessNewBlockHeaders(std::span<const CBlockHeader> headers, bool min_pow_checked, BlockValidationState& state, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
1284
1304 bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1305
1306 void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1307
1314 [[nodiscard]] MempoolAcceptResult ProcessTransaction(const CTransactionRef& tx, bool test_accept=false)
1316
1318 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
1319
1322 void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1323
1329 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const;
1330
1332 void GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev) const;
1333
1338 void ReportHeadersPresync(int64_t height, int64_t timestamp);
1339
1343 Chainstate* LoadAssumeutxoChainstate() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1344
1346 Chainstate& AddChainstate(std::unique_ptr<Chainstate> chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1347
1348 void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1349
1352 [[nodiscard]] bool DeleteChainstate(Chainstate& chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1353
1363 bool ValidatedSnapshotCleanup(Chainstate& validated_cs, Chainstate& unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1364
1366 std::optional<std::pair<const CBlockIndex*, const CBlockIndex*>> GetHistoricalBlockRange() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1367
1369 util::Result<void> ActivateBestChains() LOCKS_EXCLUDED(::cs_main);
1370
1374 void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1375
1378 std::optional<int> BlocksAheadOfTip() const LOCKS_EXCLUDED(::cs_main);
1379
1380 CCheckQueue<CScriptCheck>& GetCheckQueue() { return m_script_check_queue; }
1381
1383
1391 std::vector<std::unique_ptr<Chainstate>> m_chainstates GUARDED_BY(::cs_main);
1392};
1393
1395template<typename DEP>
1396bool DeploymentActiveAfter(const CBlockIndex* pindexPrev, const ChainstateManager& chainman, DEP dep)
1397{
1398 return DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1399}
1400
1401template<typename DEP>
1402bool DeploymentActiveAt(const CBlockIndex& index, const ChainstateManager& chainman, DEP dep)
1403{
1404 return DeploymentActiveAt(index, chainman.GetConsensus(), dep, chainman.m_versionbitscache);
1405}
1406
1407template<typename DEP>
1408bool DeploymentEnabled(const ChainstateManager& chainman, DEP dep)
1409{
1410 return DeploymentEnabled(chainman.GetConsensus(), dep);
1411}
1412
1414bool IsBIP30Repeat(const CBlockIndex& block_index);
1415
1417bool IsBIP30Unspendable(const uint256& block_hash, int block_height);
1418
1419// Returns the script flags which should be checked for a given block
1420script_verify_flags GetBlockScriptFlags(const CBlockIndex& block_index, const ChainstateManager& chainman);
1421
1422#endif // BITCOIN_VALIDATION_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int ret
int flags
Definition: bitcoin-tx.cpp:530
void InvalidateBlock(ChainstateManager &chainman, const uint256 block_hash)
static constexpr int32_t SEQ_ID_INIT_FROM_DISK
Definition: chain.h:40
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:116
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
static void CheckBlockIndex(benchmark::Bench &bench)
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:395
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:27
Definition: block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
An in-memory indexed chain of blocks.
Definition: chain.h:380
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:396
int Height() const
Return the maximal height in the chain.
Definition: chain.h:425
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:405
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:37
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:770
Pure abstract view on the open txout dataset.
Definition: coins.h:319
Fee rate in satoshis per virtualbyte: CAmount / vB the feerate is represented internally as FeeFrac.
Definition: feerate.h:32
A hasher class for SHA-256.
Definition: sha256.h:14
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:342
CScriptCheck & operator=(CScriptCheck &&)=default
SignatureCache * m_signature_cache
Definition: validation.h:350
CScriptCheck(const CScriptCheck &)=delete
PrecomputedTransactionData * txdata
Definition: validation.h:349
CTxOut m_tx_out
Definition: validation.h:344
script_verify_flags m_flags
Definition: validation.h:347
CScriptCheck(CScriptCheck &&)=default
bool cacheStore
Definition: validation.h:348
std::optional< std::pair< ScriptError, std::string > > operator()()
const CTransaction * ptxTo
Definition: validation.h:345
unsigned int nIn
Definition: validation.h:346
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, SignatureCache &signature_cache, unsigned int nInIn, script_verify_flags flags, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:353
CScriptCheck & operator=(const CScriptCheck &)=delete
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:187
An output of a transaction.
Definition: transaction.h:140
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:439
VerifyDBResult VerifyDB(Chainstate &chainstate, const Consensus::Params &consensus_params, CCoinsView &coinsview, int nCheckLevel, int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
kernel::Notifications & m_notifications
Definition: validation.h:441
CVerifyDB(kernel::Notifications &notifications)
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:554
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
Definition: validation.h:620
Mutex m_chainstate_mutex
The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestCh...
Definition: validation.h:561
std::optional< uint256 > m_target_blockhash GUARDED_BY(::cs_main)
Target block for this chainstate.
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:628
CTxMemPool * GetMempool()
Definition: validation.h:704
bool RollforwardBlock(const CBlockIndex *pindex, CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:724
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(NodeClock::time_poin m_next_write)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:895
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:689
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:721
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(void SetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(voi ResetBlockFailureFlags)(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as precious and reorganize.
Definition: validation.h:808
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, std::shared_ptr< const CBlock > block_to_connect, std::vector< ConnectedBlock > &connected_blocks, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
const CBlockIndex *SnapshotBase() const EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *TargetBlock() const EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlock(CBlockIndex *block) EXCLUSIVE_LOCKS_REQUIRED(void SetTargetBlockHash(uint256 block_hash) EXCLUSIVE_LOCKS_REQUIRED(boo ReachedTarget)() const EXCLUSIVE_LOCKS_REQUIRED(
The base of the snapshot this chainstate was created from.
Definition: validation.h:672
kernel::ChainstateRole GetRole() const EXCLUSIVE_LOCKS_REQUIRED(void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe)
Return the current role of the chainstate.
const std::optional< uint256 > m_from_snapshot_blockhash
The blockhash which is the base of the snapshot this chainstate was created from.
Definition: validation.h:640
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock)(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the best known block, and make it the tip of the block chain.
Definition: validation.h:784
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex &index_most_work, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, std::vector< ConnectedBlock > &connected_blocks) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return the [start, end] (inclusive) of block heights we can prune.
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:565
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:697
std::optional< const char * > m_last_script_check_reason_logged GUARDED_BY(::cs_main)
Definition: validation.h:576
const CBlockIndex *m_cached_target_block GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_target_blockhash)
Definition: validation.h:574
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
CBlockIndex * FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however fa...
std::set< CBlockIndex *, node::CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries that have as much work as our current tip or more,...
Definition: validation.h:686
util::Result< void > InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(friend ChainstateManager
In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for iss...
Definition: validation.h:902
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:586
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:568
bool m_mempool cs
Definition: validation.h:788
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
Assumeutxo m_assumeutxo GUARDED_BY(::cs_main)
Assumeutxo state indicating whether all blocks in the chain were validated, or if the chainstate is b...
std::optional< AssumeutxoHash > m_target_utxohash GUARDED_BY(::cs_main)
Hash of the UTXO set at the target block, computed when the chainstate reaches the target block,...
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:718
void TryAddBlockIndexCandidate(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Add a block to the candidate set if it has as much work as the current tip.
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Resize the CoinsViews caches dynamically and flush state to disk.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:581
void ForceFlushStateToDisk(bool wipe_cache=true)
Flush all changes to disk.
void MaybeUpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transac...
Definition: validation.cpp:303
const CBlockIndex *m_cached_snapshot_base GUARDED_BY(::cs_main)
Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)
Definition: validation.h:571
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:711
void ClearBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(void PopulateBlockIndexCandidates() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * FindForkInGlobalIndex(const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Populate the candidate set by calling TryAddBlockIndexCandidate on all valid block indices.
Definition: validation.cpp:129
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Chainstate(CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex * GetLastFlushedBlock() const EXCLUSIVE_LOCKS_REQUIRED(
Dictates whether we need to flush the cache to disk or not.
Definition: validation.h:844
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
Definition: validation.h:847
const CBlockIndex *m_last_flushed_block GUARDED_BY(::cs_main)
Definition: validation.h:896
fs::path StoragePath() const
Return path to chainstate leveldb directory.
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
Interface for managing multiple Chainstate objects, where each chainstate is associated with chainsta...
Definition: validation.h:945
SteadyClock::duration GUARDED_BY(::cs_main) time_connect_total
Definition: validation.h:995
Chainstate * HistoricalChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return historical chainstate targeting a specific block, if any.
Definition: validation.h:1136
const uint256 & AssumedValidBlock() const
Definition: validation.h:1016
CBlockIndex *m_best_header GUARDED_BY(::cs_main)
Best header we've seen so far for which the block is not known to be invalid (used,...
Definition: validation.h:1083
ValidationCache m_validation_cache
Definition: validation.h:1045
int64_t GUARDED_BY(::cs_main) num_blocks_total
Definition: validation.h:994
SteadyClock::duration GUARDED_BY(::cs_main) time_undo
Definition: validation.h:991
SteadyClock::duration GUARDED_BY(::cs_main) time_index
Definition: validation.h:992
SteadyClock::duration GUARDED_BY(::cs_main) time_post_connect
Definition: validation.h:998
std::unique_ptr< Chainstate > RemoveChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Remove a chainstate.
Definition: validation.h:1156
kernel::Notifications & GetNotifications() const
Definition: validation.h:1017
SteadyClock::duration GUARDED_BY(::cs_main) time_check
Timers and counters used for benchmarking validation in both background and active chainstates.
Definition: validation.h:987
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
Definition: validation.h:1037
SteadyClock::duration GUARDED_BY(::cs_main) time_total
Definition: validation.h:993
SteadyClock::duration GUARDED_BY(::cs_main) time_chainstate
Definition: validation.h:997
CCheckQueue< CScriptCheck > m_script_check_queue
A queue for script verifications that have to be performed by worker threads.
Definition: validation.h:983
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1175
CBlockIndex *m_best_invalid GUARDED_BY(::cs_main)
Definition: validation.h:1001
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the sna...
Definition: validation.h:1127
SteadyClock::duration GUARDED_BY(::cs_main) time_forks
Definition: validation.h:988
CBlockIndex *m_last_notified_header GUARDED_BY(GetMutex())
The last header for which a headerTip notification was issued.
Definition: validation.h:949
std::vector< std::unique_ptr< Chainstate > > m_chainstates GUARDED_BY(::cs_main)
List of chainstates.
const util::SignalInterrupt & m_interrupt
Definition: validation.h:1039
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1174
VersionBitsCache m_versionbitscache
Track versionbit status.
Definition: validation.h:1200
Chainstate & ValidatedChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Return fully validated chainstate that should be used for indexing, to support indexes that need to i...
Definition: validation.h:1147
const CChainParams & GetParams() const
Definition: validation.h:1012
const Consensus::Params & GetConsensus() const
Definition: validation.h:1013
const arith_uint256 & MinimumChainWork() const
Definition: validation.h:1015
const Options m_options
Definition: validation.h:1040
int32_t nBlockSequenceId GUARDED_BY(::cs_main)
Every received block is assigned a unique and increasing identifier, so we know which one to give pri...
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(util::Result< CBlockIndex * ActivateSnapshot)(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
Instantiate a new chainstate.
Definition: validation.h:1113
SteadyClock::duration GUARDED_BY(::cs_main) time_verify
Definition: validation.h:990
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1173
SteadyClock::duration GUARDED_BY(::cs_main) time_connect
Definition: validation.h:989
void ResetBlockSequenceCounters() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:1071
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1043
SteadyClock::duration GUARDED_BY(::cs_main) time_flush
Definition: validation.h:996
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:482
std::unique_ptr< CCoinsViewCache > m_cacheview GUARDED_BY(cs_main)
This is the top layer of the cache hierarchy - it keeps as many coins in memory as can fit per the db...
CCoinsViewErrorCatcher m_catcherview GUARDED_BY(cs_main)
This view wraps access to the leveldb instance and handles read errors gracefully.
std::unique_ptr< CoinsViewOverlay > m_connect_block_view GUARDED_BY(cs_main)
Reused CoinsViewOverlay layered on top of m_cacheview and passed to ConnectBlock().
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
CoinsViews(DBParams db_params, CoinsViewOptions options)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
DisconnectedBlockTransactions.
Valid signature cache, to avoid doing expensive ECDSA signature checking twice for every transaction ...
Definition: sigcache.h:42
Convenience class for initializing and passing the script execution cache and signature cache.
Definition: validation.h:374
ValidationCache(size_t script_execution_cache_bytes, size_t signature_cache_bytes)
CuckooCache::cache< uint256, SignatureCacheHasher > m_script_execution_cache
Definition: validation.h:380
ValidationCache & operator=(const ValidationCache &)=delete
ValidationCache(const ValidationCache &)=delete
CSHA256 ScriptExecutionCacheHasher() const
Return a copy of the pre-initialized hasher.
Definition: validation.h:389
CSHA256 m_script_execution_cache_hasher
Pre-initialized hasher to avoid having to recreate it for every hash calculation.
Definition: validation.h:377
SignatureCache m_signature_cache
Definition: validation.h:381
bool IsValid() const
Definition: validation.h:105
BIP 9 allows multiple softforks to be deployed in parallel.
Definition: versionbits.h:78
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:196
Metadata describing a serialized version of a UTXO set from which an assumeutxo Chainstate can be con...
Definition: utxo_snapshot.h:38
transaction_identifier represents the two canonical transaction identifier types (txid,...
256-bit opaque blob.
Definition: uint256.h:196
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
HTTPHeaders headers
static void LoadExternalBlockFile(benchmark::Bench &bench)
The LoadExternalBlockFile() function is used during -reindex and -loadblock.
unsigned int nHeight
Transaction validation functions.
Definition: messages.h:21
std::unordered_map< uint256, CBlockIndex, BlockHasher > BlockMap
Definition: blockstorage.h:138
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:249
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:45
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
@ OK
The message verification was successful.
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:34
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:117
Holds various statistics on transactions within a chain.
Definition: chainparams.h:57
User-controlled performance and debug options.
Definition: txdb.h:28
Parameters that influence chain consensus.
Definition: params.h:87
Application-specific storage settings.
Definition: dbwrapper.h:41
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:134
const std::optional< int64_t > m_vsize
Virtual size as used by the mempool, calculated using serialized size and sigops.
Definition: validation.h:151
const ResultType m_result_type
Result type.
Definition: validation.h:143
MempoolAcceptResult(int64_t vsize, CAmount fees)
Constructor for already-in-mempool case.
Definition: validation.h:228
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:153
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:200
const TxValidationState m_state
Contains information about why the transaction failed.
Definition: validation.h:146
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:136
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:170
static MempoolAcceptResult FeeFailure(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Definition: validation.h:174
const std::optional< CFeeRate > m_effective_feerate
The feerate at which this transaction was considered.
Definition: validation.h:159
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for success case.
Definition: validation.h:206
const std::optional< Wtxid > m_other_wtxid
The wtxid of the transaction in the mempool which has the same txid but different witness.
Definition: validation.h:168
const std::list< CTransactionRef > m_replaced_transactions
Mempool transactions replaced by the tx.
Definition: validation.h:149
MempoolAcceptResult(const Wtxid &other_wtxid)
Constructor for witness-swapped case.
Definition: validation.h:232
static MempoolAcceptResult MempoolTxDifferentWitness(const Wtxid &other_wtxid)
Definition: validation.h:193
static MempoolAcceptResult MempoolTx(int64_t vsize, CAmount fees)
Definition: validation.h:189
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, int64_t vsize, CAmount fees, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Definition: validation.h:180
MempoolAcceptResult(TxValidationState state, CFeeRate effective_feerate, const std::vector< Wtxid > &wtxids_fee_calculations)
Constructor for fee-related failure case.
Definition: validation.h:219
const std::optional< std::vector< Wtxid > > m_wtxids_fee_calculations
Contains the wtxids of the transactions used for fee-related checks.
Definition: validation.h:165
Version of SteadyClock that is mockable in the context of tests (via FakeSteadyClock,...
Definition: time.h:47
Version of the system clock that is mockable in the context of tests (via FakeNodeClock or SetMockTim...
Definition: time.h:27
Validation result for package mempool acceptance.
Definition: validation.h:240
PackageValidationState m_state
Definition: validation.h:241
PackageMempoolAcceptResult(const Wtxid &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:259
PackageMempoolAcceptResult(PackageValidationState state, CFeeRate feerate, std::map< Wtxid, MempoolAcceptResult > &&results)
Definition: validation.h:254
PackageMempoolAcceptResult(PackageValidationState state, std::map< Wtxid, MempoolAcceptResult > &&results)
Definition: validation.h:250
std::map< Wtxid, MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:248
Bilingual messages:
Definition: translation.h:24
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...
Information about chainstate that notifications are sent from.
Definition: types.h:18
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx)
Definition: validation.cpp:156
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
bool IsBlockMutated(const CBlock &block, bool check_witness_root)
Check if a block has been mutated (with respect to its merkle root and witness commitments).
script_verify_flags GetBlockScriptFlags(const CBlockIndex &block_index, const ChainstateManager &chainman)
static constexpr int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:90
static constexpr int DEFAULT_CHECKLEVEL
Definition: validation.h:78
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:87
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
bool HasValidProofOfWork(std::span< const CBlockHeader > headers, const Consensus::Params &consensusParams)
Check that the proof of work on each blockheader matches the value in nBits.
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:255
bool FatalError(kernel::Notifications &notifications, BlockValidationState &state, const bilingual_str &message)
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:76
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Try to add a transaction to the mempool.
bool DeploymentActiveAfter(const CBlockIndex *pindexPrev, const ChainstateManager &chainman, DEP dep)
Deployment* info via ChainstateManager.
Definition: validation.h:1396
BlockValidationState TestBlockValidity(Chainstate &chainstate, const CBlock &block, bool check_pow, bool check_merkle_root) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Verify a block, including transactions.
SnapshotCompletionResult
Definition: validation.h:907
bool DeploymentEnabled(const ChainstateManager &chainman, DEP dep)
Definition: validation.h:1408
Assumeutxo
Chainstate assumeutxo validity.
Definition: validation.h:530
@ VALIDATED
Every block in the chain has been validated.
@ UNVALIDATED
Blocks after an assumeutxo snapshot have been validated but the snapshot itself has not been validate...
@ INVALID
The assumeutxo snapshot failed validation.
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:96
constexpr std::array FlushStateModeNames
Definition: validation.h:464
bool CheckFinalTxAtTip(const CBlockIndex &active_chain_tip, const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(std::optional< LockPoints > CalculateLockPointsAtTip(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx)
Check if transaction will be final in the next block to be created.
Definition: validation.h:320
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept, const std::optional< CFeeRate > &client_maxfeerate) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Validate (and maybe submit) a package to the mempool.
constexpr int64_t LargeCoinsCacheThreshold(int64_t total_space) noexcept
Definition: validation.h:521
arith_uint256 CalculateClaimedHeadersWork(std::span< const CBlockHeader > headers)
Return the sum of the claimed work on a given set of headers.
VerifyDBResult
Definition: validation.h:429
static constexpr int32_t MAX_PREVOUTFETCH_THREADS
Maximum number of dedicated threads allowed for prefetching block input prevouts.
Definition: validation.h:93
bool CheckBlock(const CBlock &block, BlockValidationState &state, const Consensus::Params &consensusParams, bool fCheckPOW=true, bool fCheckMerkleRoot=true)
Functions for validating blocks and updating the block tree.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:102
void PruneBlockFilesManual(Chainstate &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
FlushStateMode
Definition: validation.h:465
CoinsCacheSizeState
Definition: validation.h:513
@ 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:1402
bool IsBIP30Repeat(const CBlockIndex &block_index)
Identifies blocks that overwrote an existing coinbase output in the UTXO set (see BIP30)
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:77
DisconnectResult
Definition: validation.h:455
@ DISCONNECT_FAILED
Definition: validation.h:458
@ DISCONNECT_UNCLEAN
Definition: validation.h:457
@ DISCONNECT_OK
Definition: validation.h:456
bool IsBIP30Unspendable(const uint256 &block_hash, int block_height)
Identifies blocks which coinbase output was subsequently overwritten in the UTXO set (see BIP30)