Bitcoin Core 22.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-2020 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#if defined(HAVE_CONFIG_H)
11#endif
12
13#include <arith_uint256.h>
14#include <attributes.h>
15#include <chain.h>
16#include <consensus/amount.h>
17#include <fs.h>
18#include <policy/feerate.h>
19#include <policy/packages.h>
20#include <script/script_error.h>
21#include <sync.h>
22#include <txdb.h>
23#include <txmempool.h> // For CTxMemPool::cs
24#include <uint256.h>
25#include <util/check.h>
26#include <util/hasher.h>
27#include <util/translation.h>
28
29#include <atomic>
30#include <map>
31#include <memory>
32#include <optional>
33#include <set>
34#include <stdint.h>
35#include <string>
36#include <thread>
37#include <utility>
38#include <vector>
39
40class CChainState;
41class CBlockTreeDB;
42class CChainParams;
43struct CCheckpointData;
44class CTxMemPool;
47struct ChainTxData;
50struct LockPoints;
51struct AssumeutxoData;
52
54static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
56static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
58static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
60static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
62static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
64static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
66static const int MAX_SCRIPTCHECK_THREADS = 15;
68static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
69static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
70static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
71static const bool DEFAULT_TXINDEX = false;
72static constexpr bool DEFAULT_COINSTATSINDEX{false};
73static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
75static const bool DEFAULT_PERSIST_MEMPOOL = true;
77static const int DEFAULT_STOPATHEIGHT = 0;
79static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
80static const signed int DEFAULT_CHECKBLOCKS = 6;
81static const unsigned int DEFAULT_CHECKLEVEL = 3;
82// Require that user allocate at least 550 MiB for block & undo files (blk???.dat and rev???.dat)
83// At 1MB per block, 288 blocks = 288MB.
84// Add 15% for Undo data = 331MB
85// Add 20% for Orphan block rate = 397MB
86// We want the low water mark after pruning to be at least 397 MB and since we prune in
87// full block file chunks, we need the high water mark which triggers the prune to be
88// one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB
89// Setting the target to >= 550 MiB will make it likely we can respect the target.
90static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
91
97};
98
100typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
102extern std::condition_variable g_best_block_cv;
104extern uint256 g_best_block;
108extern bool g_parallel_script_checks;
109extern bool fRequireStandard;
110extern bool fCheckBlockIndex;
111extern bool fCheckpointsEnabled;
115extern int64_t nMaxTipAge;
116
119
122
125
127extern const std::vector<std::string> CHECKLEVEL_DOC;
128
130void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman);
132void StartScriptCheckWorkerThreads(int threads_num);
135
136CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
137
138bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str{});
139
141double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
142
144void PruneBlockFilesManual(CChainState& active_chainstate, int nManualPruneHeight);
145
151 enum class ResultType {
152 VALID,
153 INVALID,
154 };
157
158 // The following fields are only present when m_result_type = ResultType::VALID
160 const std::optional<std::list<CTransactionRef>> m_replaced_transactions;
162 const std::optional<CAmount> m_base_fees;
164 return MempoolAcceptResult(state);
165 }
166
167 static MempoolAcceptResult Success(std::list<CTransactionRef>&& replaced_txns, CAmount fees) {
168 return MempoolAcceptResult(std::move(replaced_txns), fees);
169 }
170
171// Private constructors. Use static methods MempoolAcceptResult::Success, etc. to construct.
172private:
175 : m_result_type(ResultType::INVALID), m_state(state) {
176 Assume(!state.IsValid()); // Can be invalid or error
177 }
178
180 explicit MempoolAcceptResult(std::list<CTransactionRef>&& replaced_txns, CAmount fees)
181 : m_result_type(ResultType::VALID),
182 m_replaced_transactions(std::move(replaced_txns)), m_base_fees(fees) {}
183};
184
189{
197 std::map<const uint256, const MempoolAcceptResult> m_tx_results;
198
200 std::map<const uint256, const MempoolAcceptResult>&& results)
201 : m_state{state}, m_tx_results(std::move(results)) {}
202
204 explicit PackageMempoolAcceptResult(const uint256& wtxid, const MempoolAcceptResult& result)
205 : m_tx_results{ {wtxid, result} } {}
206};
207
214 bool bypass_limits, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
215
229 const Package& txns, bool test_accept)
231
241bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
242
247
268 const CCoinsView& coins_view,
269 const CTransaction& tx,
270 int flags,
271 LockPoints* lp = nullptr,
272 bool useExistingLockPoints = false);
273
279{
280private:
283 unsigned int nIn;
284 unsigned int nFlags;
288
289public:
290 CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
291 CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
292 m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
293
294 bool operator()();
295
296 void swap(CScriptCheck &check) {
297 std::swap(ptxTo, check.ptxTo);
298 std::swap(m_tx_out, check.m_tx_out);
299 std::swap(nIn, check.nIn);
300 std::swap(nFlags, check.nFlags);
301 std::swap(cacheStore, check.cacheStore);
302 std::swap(error, check.error);
303 std::swap(txdata, check.txdata);
304 }
305
306 ScriptError GetScriptError() const { return error; }
307};
308
311
315bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
316
319 const CChainParams& chainparams,
320 CChainState& chainstate,
321 const CBlock& block,
322 CBlockIndex* pindexPrev,
323 bool fCheckPOW = true,
324 bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
325
327void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
328
330std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
331
334public:
335 CVerifyDB();
336 ~CVerifyDB();
337 bool VerifyDB(
338 CChainState& chainstate,
339 const CChainParams& chainparams,
340 CCoinsView& coinsview,
341 int nCheckLevel,
342 int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
343};
344
346{
347 DISCONNECT_OK, // All good.
348 DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
349 DISCONNECT_FAILED // Something else went wrong.
351
352class ConnectTrace;
353
355enum class FlushStateMode {
356 NONE,
357 IF_NEEDED,
358 PERIODIC,
359 ALWAYS
360};
361
363{
364 bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
365};
366
375{
377
378private:
379 /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
380 void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height);
381
397 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd);
398
399public:
401
420 std::set<CBlockIndex*> m_failed_blocks;
421
426 std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
427
428 std::unique_ptr<CBlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
429
430 bool LoadBlockIndexDB(std::set<CBlockIndex*, CBlockIndexWorkComparator>& setBlockIndexCandidates) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
431
441 const Consensus::Params& consensus_params,
442 std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
444
447
451
453 void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
454
460 const CBlockHeader& block,
462 const CChainParams& chainparams,
464
466
469
472
479
481 Unload();
482 }
483};
484
495
496public:
500
503
506 std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
507
514 CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
515
517 void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
518};
519
521{
523 CRITICAL = 2,
525 LARGE = 1,
526 OK = 0
527};
528
544{
545protected:
551 int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
553 int32_t nBlockReverseSequenceId = -1;
555 arith_uint256 nLastPreciousChainwork = 0;
556
562
569 mutable std::atomic<bool> m_cached_finished_ibd{false};
570
574
576
578 std::unique_ptr<CoinsViews> m_coins_views;
579
580public:
584
589
590 explicit CChainState(
591 CTxMemPool* mempool,
592 BlockManager& blockman,
593 ChainstateManager& chainman,
594 std::optional<uint256> from_snapshot_blockhash = std::nullopt);
595
602 void InitCoinsDB(
603 size_t cache_size_bytes,
604 bool in_memory,
605 bool should_wipe,
606 std::string leveldb_name = "chainstate");
607
610 void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
611
615 return m_coins_views && m_coins_views->m_cacheview;
616 }
617
621
627 const std::optional<uint256> m_from_snapshot_blockhash;
628
635 std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
636
639 {
640 assert(m_coins_views->m_cacheview);
641 return *m_coins_views->m_cacheview.get();
642 }
643
646 {
647 return m_coins_views->m_dbview;
648 }
649
653 {
654 return m_coins_views->m_catcherview;
655 }
656
658 void ResetCoinsViews() { m_coins_views.reset(); }
659
661 size_t m_coinsdb_cache_size_bytes{0};
662
664 size_t m_coinstip_cache_size_bytes{0};
665
668 bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
670
672 void LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp = nullptr);
673
685 bool FlushStateToDisk(
687 FlushStateMode mode,
688 int nManualPruneHeight = 0);
689
691 void ForceFlushStateToDisk();
692
695 void PruneAndFlush();
696
712 bool ActivateBestChain(
714 std::shared_ptr<const CBlock> pblock = nullptr) LOCKS_EXCLUDED(cs_main);
715
716 bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, BlockValidationState& state, CBlockIndex** ppindex, bool fRequested, const FlatFilePos* dbp, bool* fNewBlock) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
717
718 // Block (dis)connection on a given view:
719 DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
720 bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
721 CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
722
723 // Apply the effects of a block disconnection on the UTXO set.
724 bool DisconnectTip(BlockValidationState& state, DisconnectedBlockTransactions* disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
725
726 // Manual block validity manipulation:
731 bool PreciousBlock(BlockValidationState& state, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
733 bool InvalidateBlock(BlockValidationState& state, CBlockIndex* pindex) LOCKS_EXCLUDED(cs_main);
735 void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
736
738 bool ReplayBlocks();
739
741 [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
743 bool LoadGenesisBlock();
744
745 void PruneBlockIndexCandidates();
746
748
750 bool IsInitialBlockDownload() const;
751
757 void CheckBlockIndex();
758
760 void LoadMempool(const ArgsManager& args);
761
763 bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
764
768 CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
769
770 CoinsCacheSizeState GetCoinsCacheSizeState(
771 size_t max_coins_cache_size_bytes,
772 size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
773
775
776private:
777 bool ActivateBestChainStep(BlockValidationState& state, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
778 bool ConnectTip(BlockValidationState& state, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions& disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
779
780 void InvalidBlockFound(CBlockIndex* pindex, const BlockValidationState& state) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
781 CBlockIndex* FindMostWorkChain() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
782 void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
783
784 bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
785
786 void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
787 void InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
788
790 RecursiveMutex* MempoolMutex() const LOCK_RETURNED(m_mempool->cs)
791 {
792 return m_mempool ? &m_mempool->cs : nullptr;
793 }
794
808 void MaybeUpdateMempoolForReorg(
809 DisconnectedBlockTransactions& disconnectpool,
810 bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, m_mempool->cs);
811
813 void UpdateTip(const CBlockIndex* pindexNew)
815
817};
818
847{
848private:
864 std::unique_ptr<CChainState> m_ibd_chainstate GUARDED_BY(::cs_main);
865
875 std::unique_ptr<CChainState> m_snapshot_chainstate GUARDED_BY(::cs_main);
876
886 CChainState* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
887
890 bool m_snapshot_validated{false};
891
893 [[nodiscard]] bool PopulateAndValidateSnapshot(
894 CChainState& snapshot_chainstate,
895 CAutoFile& coins_file,
896 const SnapshotMetadata& metadata);
897
898public:
899 std::thread m_load_block;
903
906 int64_t m_total_coinstip_cache{0};
907 //
910 int64_t m_total_coinsdb_cache{0};
911
916 // constructor
919 CChainState& InitializeChainstate(
920 CTxMemPool* mempool,
921 const std::optional<uint256>& snapshot_blockhash = std::nullopt)
923
925 std::vector<CChainState*> GetAll();
926
940 [[nodiscard]] bool ActivateSnapshot(
941 CAutoFile& coins_file, const SnapshotMetadata& metadata, bool in_memory);
942
944 CChainState& ActiveChainstate() const;
945 CChain& ActiveChain() const { return ActiveChainstate().m_chain; }
946 int ActiveHeight() const { return ActiveChain().Height(); }
947 CBlockIndex* ActiveTip() const { return ActiveChain().Tip(); }
948
950 {
951 return m_blockman.m_block_index;
952 }
953
956 bool IsSnapshotActive() const;
957
958 std::optional<uint256> SnapshotBlockhash() const;
959
961 bool IsSnapshotValidated() const { return m_snapshot_validated; }
962
982 bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock>& block, bool force_processing, bool* new_block) LOCKS_EXCLUDED(cs_main);
983
995 bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
996
998 bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
999
1001 void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1002
1004 void Reset();
1005
1008 void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1009
1011 LOCK(::cs_main);
1012 UnloadBlockIndex(/* mempool */ nullptr, *this);
1013 Reset();
1014 }
1015};
1016
1017using FopenFn = std::function<FILE*(const fs::path&, const char*)>;
1018
1020bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function = fsbridge::fopen, bool skip_file_commit = false);
1021
1023bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function = fsbridge::fopen);
1024
1032const AssumeutxoData* ExpectedAssumeutxo(const int height, const CChainParams& params);
1033
1034#endif // BITCOIN_VALIDATION_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define LIFETIMEBOUND
Definition: attributes.h:16
int flags
Definition: bitcoin-tx.cpp:525
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:375
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
CBlockIndex * AddToBlockIndex(const CBlockHeader &block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
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:420
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:150
friend CChainState
Definition: validation.h:376
BlockMap m_block_index GUARDED_BY(cs_main)
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
std::unique_ptr< CBlockTreeDB > m_block_tree_db GUARDED_BY(::cs_main)
bool AcceptBlockHeader(const CBlockHeader &block, BlockValidationState &state, const CChainParams &chainparams, CBlockIndex **ppindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't desce...
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
bool LoadBlockIndexDB(std::set< CBlockIndex *, CBlockIndexWorkComparator > &setBlockIndexCandidates) EXCLUSIVE_LOCKS_REQUIRED(boo LoadBlockIndex)(const Consensus::Params &consensus_params, std::set< CBlockIndex *, CBlockIndexWorkComparator > &block_index_candidates) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
Definition: validation.h:440
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
int GetSpendHeight(const CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the spend height, which is one more than the inputs.GetBestBlock().
std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Definition: validation.h:426
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:157
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:565
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:146
Access to the block database (blocks/index/)
Definition: txdb.h:78
An in-memory indexed chain of blocks.
Definition: chain.h:410
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:70
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:544
const CChainParams & m_params
Definition: validation.h:575
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:645
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:588
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:573
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:561
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:635
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:638
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...
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:627
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:652
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:578
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:658
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
Definition: validation.h:583
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager)
Check warning conditions and do some notifications on new chain tip set.
Definition: validation.h:813
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:620
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified...
Definition: validation.h:614
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:214
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:50
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:344
Abstract view on the open txout dataset.
Definition: coins.h:158
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:30
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:279
ScriptError GetScriptError() const
Definition: validation.h:306
PrecomputedTransactionData * txdata
Definition: validation.h:287
void swap(CScriptCheck &check)
Definition: validation.h:296
CTxOut m_tx_out
Definition: validation.h:281
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:291
bool cacheStore
Definition: validation.h:285
ScriptError error
Definition: validation.h:286
unsigned int nFlags
Definition: validation.h:284
const CTransaction * ptxTo
Definition: validation.h:282
unsigned int nIn
Definition: validation.h:283
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:424
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:511
An output of a transaction.
Definition: transaction.h:129
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:333
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:847
int ActiveHeight() const
Definition: validation.h:946
BlockManager m_blockman GUARDED_BY(::cs_main)
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
CChainState &InitializeChainstate(CTxMemPool *mempool, const std::optional< uint256 > &snapshot_blockhash=std::nullopt) LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(std::vector< CChainState * GetAll)()
Instantiate a new chainstate and assign it based upon whether it is from a snapshot.
Definition: validation.h:925
std::unique_ptr< CChainState > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:949
CChainState *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:886
std::thread m_load_block
Definition: validation.h:899
CChain & ActiveChain() const
Definition: validation.h:945
CBlockIndex * ActiveTip() const
Definition: validation.h:947
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:961
std::unique_ptr< CChainState > m_snapshot_chainstate GUARDED_BY(::cs_main)
A chainstate initialized on the basis of a UTXO snapshot.
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:494
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(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe)
This constructor initializes CCoinsViewDB and CCoinsViewErrorCatcher instances, but it does not creat...
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
Metadata describing a serialized version of a UTXO set from which an assumeutxo CChainState can be co...
Definition: utxo_snapshot.h:15
bool IsValid() const
Definition: validation.h:119
256-bit unsigned big integer.
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:34
256-bit opaque blob.
Definition: uint256.h:124
unsigned int nHeight
LockPoints lp
static void pool cs
Transaction validation functions.
Definition: params.h:12
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:25
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:32
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
@ PERIODIC
Called by RandAddPeriodic()
enum ScriptError_t ScriptError
@ SCRIPT_ERR_UNKNOWN_ERROR
Definition: script_error.h:14
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
Definition: validation.cpp:90
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:115
Holds various statistics on transactions within a chain.
Definition: chainparams.h:59
Parameters that influence chain consensus.
Definition: params.h:70
Validation result for a single transaction mempool acceptance.
Definition: validation.h:149
const ResultType m_result_type
Definition: validation.h:155
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
Definition: validation.h:167
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:162
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx per BIP 125 rules.
Definition: validation.h:160
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:174
const TxValidationState m_state
Definition: validation.h:156
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:151
@ INVALID
Fully validated, valid.
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:163
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
Constructor for success case.
Definition: validation.h:180
Validation result for package mempool acceptance.
Definition: validation.h:189
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:197
PackageMempoolAcceptResult(PackageValidationState state, std::map< const uint256, const MempoolAcceptResult > &&results)
Definition: validation.h:199
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:204
const PackageValidationState m_state
Definition: validation.h:190
Bilingual messages:
Definition: translation.h:16
#define LOCK(cs)
Definition: sync.h:226
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
assert(!tx.IsCoinBase())
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:130
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:131
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:70
bool TestBlockValidity(BlockValidationState &state, const CChainParams &chainparams, CChainState &chainstate, const CBlock &block, CBlockIndex *pindexPrev, bool fCheckPOW=true, bool fCheckMerkleRoot=true) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Check a block is completely valid from start to finish (only works on top of our current best block)
bool CheckSequenceLocks(CBlockIndex *tip, const CCoinsView &coins_view, const CTransaction &tx, int flags, LockPoints *lp=nullptr, bool useExistingLockPoints=false)
Check if transaction will be BIP68 final in the next block to be created on top of tip.
Definition: validation.cpp:233
bool fCheckBlockIndex
Definition: validation.cpp:126
std::condition_variable g_best_block_cv
Definition: validation.cpp:122
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:60
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: validation.h:1017
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:124
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:90
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:62
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:81
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:133
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:79
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:66
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:100
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:93
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:54
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:68
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:73
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
void InitScriptExecutionCache()
Initializes the script-execution cache.
Mutex g_best_block_mutex
Definition: validation.cpp:121
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:64
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:58
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.
static constexpr bool DEFAULT_COINSTATSINDEX
Definition: validation.h:72
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function=fsbridge::fopen, bool skip_file_commit=false)
Dump the mempool to disk.
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:81
CoinsCacheSizeState
Definition: validation.h:521
@ LARGE
The cache is at >= 90% capacity.
@ CRITICAL
The coins cache is in immediate need of a flush.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:56
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:69
bool fCheckpointsEnabled
Definition: validation.cpp:127
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:120
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:80
FlushStateMode
Definition: validation.h:355
bool LoadMempool(CTxMemPool &pool, CChainState &active_chainstate, FopenFn mockable_fopen_function=fsbridge::fopen)
Load the mempool from disk.
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:123
DisconnectResult
Definition: validation.h:346
@ DISCONNECT_FAILED
Definition: validation.h:349
@ DISCONNECT_UNCLEAN
Definition: validation.h:348
@ DISCONNECT_OK
Definition: validation.h:347
bool fRequireStandard
Definition: validation.cpp:125
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:75
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &params)
Return the expected assumeutxo value for a given height, if one exists.
PackageMempoolAcceptResult ProcessNewPackage(CChainState &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Atomically test acceptance of a package.
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:77
bool TestLockPointValidity(CChain &active_chain, const LockPoints *lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Test whether the LockPoints height and time are still valid on the current chain.
Definition: validation.cpp:215
int64_t nMaxTipAge
If the tip is older than this (in seconds), the node is considered to be in initial block download.
Definition: validation.cpp:128
MempoolAcceptResult AcceptToMemoryPool(CChainState &active_chainstate, CTxMemPool &pool, const CTransactionRef &tx, bool bypass_limits, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
(Try to) add a transaction to the memory pool.
std::vector< unsigned char > GenerateCoinbaseCommitment(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks...
static const bool DEFAULT_TXINDEX
Definition: validation.h:71
bool CheckFinalTx(const CBlockIndex *active_chain_tip, const CTransaction &tx, int flags=-1) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Transaction validation functions.
Definition: validation.cpp:182