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)
10 #include <config/bitcoin-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 
40 class CChainState;
41 class CBlockTreeDB;
42 class CChainParams;
43 struct CCheckpointData;
44 class CTxMemPool;
45 class ChainstateManager;
46 class SnapshotMetadata;
47 struct ChainTxData;
50 struct LockPoints;
51 struct AssumeutxoData;
52 
54 static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000;
56 static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25;
58 static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101;
60 static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25;
62 static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101;
64 static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336;
66 static const int MAX_SCRIPTCHECK_THREADS = 15;
68 static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
69 static const int64_t DEFAULT_MAX_TIP_AGE = 24 * 60 * 60;
70 static const bool DEFAULT_CHECKPOINTS_ENABLED = true;
71 static const bool DEFAULT_TXINDEX = false;
72 static constexpr bool DEFAULT_COINSTATSINDEX{false};
73 static const char* const DEFAULT_BLOCKFILTERINDEX = "0";
75 static const bool DEFAULT_PERSIST_MEMPOOL = true;
77 static const int DEFAULT_STOPATHEIGHT = 0;
79 static const unsigned int MIN_BLOCKS_TO_KEEP = 288;
80 static const signed int DEFAULT_CHECKBLOCKS = 6;
81 static 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.
90 static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024;
91 
96  POST_INIT
97 };
98 
99 extern RecursiveMutex cs_main;
100 typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
102 extern std::condition_variable g_best_block_cv;
104 extern uint256 g_best_block;
108 extern bool g_parallel_script_checks;
109 extern bool fRequireStandard;
110 extern bool fCheckBlockIndex;
111 extern bool fCheckpointsEnabled;
113 extern CFeeRate minRelayTxFee;
115 extern int64_t nMaxTipAge;
116 
118 extern uint256 hashAssumeValid;
119 
122 
125 
127 extern const std::vector<std::string> CHECKLEVEL_DOC;
128 
130 void UnloadBlockIndex(CTxMemPool* mempool, ChainstateManager& chainman);
132 void StartScriptCheckWorkerThreads(int threads_num);
135 
136 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams);
137 
138 bool AbortNode(BlockValidationState& state, const std::string& strMessage, const bilingual_str& userMessage = bilingual_str{});
139 
141 double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex* pindex);
142 
144 void 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.
172 private:
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 
233 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight);
234 
244 bool CheckFinalTx(const CBlockIndex* active_chain_tip, const CTransaction &tx, int flags = -1) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
245 
250 
271  const CCoinsView& coins_view,
272  const CTransaction& tx,
273  int flags,
274  LockPoints* lp = nullptr,
275  bool useExistingLockPoints = false);
276 
282 {
283 private:
286  unsigned int nIn;
287  unsigned int nFlags;
291 
292 public:
293  CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
294  CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) :
295  m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { }
296 
297  bool operator()();
298 
299  void swap(CScriptCheck &check) {
300  std::swap(ptxTo, check.ptxTo);
301  std::swap(m_tx_out, check.m_tx_out);
302  std::swap(nIn, check.nIn);
303  std::swap(nFlags, check.nFlags);
304  std::swap(cacheStore, check.cacheStore);
305  std::swap(error, check.error);
306  std::swap(txdata, check.txdata);
307  }
308 
309  ScriptError GetScriptError() const { return error; }
310 };
311 
314 
318 bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
319 
322  const CChainParams& chainparams,
323  CChainState& chainstate,
324  const CBlock& block,
325  CBlockIndex* pindexPrev,
326  bool fCheckPOW = true,
327  bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
328 
330 void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
331 
333 std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams);
334 
336 class CVerifyDB {
337 public:
338  CVerifyDB();
339  ~CVerifyDB();
340  bool VerifyDB(
341  CChainState& chainstate,
342  const CChainParams& chainparams,
343  CCoinsView& coinsview,
344  int nCheckLevel,
345  int nCheckDepth) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
346 };
347 
349 {
350  DISCONNECT_OK, // All good.
351  DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
352  DISCONNECT_FAILED // Something else went wrong.
353 };
354 
355 class ConnectTrace;
356 
358 enum class FlushStateMode {
359  NONE,
360  IF_NEEDED,
361  PERIODIC,
362  ALWAYS
363 };
364 
366 {
367  bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const;
368 };
369 
378 {
379  friend CChainState;
380 
381 private:
382  /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
383  void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight, int chain_tip_height);
384 
400  void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd);
401 
402 public:
403  BlockMap m_block_index GUARDED_BY(cs_main);
404 
423  std::set<CBlockIndex*> m_failed_blocks;
424 
429  std::multimap<CBlockIndex*, CBlockIndex*> m_blocks_unlinked;
430 
431  std::unique_ptr<CBlockTreeDB> m_block_tree_db GUARDED_BY(::cs_main);
432 
433  bool LoadBlockIndexDB(std::set<CBlockIndex*, CBlockIndexWorkComparator>& setBlockIndexCandidates) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
434 
444  const Consensus::Params& consensus_params,
445  std::set<CBlockIndex*, CBlockIndexWorkComparator>& block_index_candidates)
447 
450 
454 
456  void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
457 
462  bool AcceptBlockHeader(
463  const CBlockHeader& block,
464  BlockValidationState& state,
465  const CChainParams& chainparams,
467 
469 
472 
475 
482 
484  Unload();
485  }
486 };
487 
497 class CoinsViews {
498 
499 public:
502  CCoinsViewDB m_dbview GUARDED_BY(cs_main);
503 
506 
509  std::unique_ptr<CCoinsViewCache> m_cacheview GUARDED_BY(cs_main);
510 
517  CoinsViews(std::string ldb_name, size_t cache_size_bytes, bool in_memory, bool should_wipe);
518 
520  void InitCache() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
521 };
522 
524 {
526  CRITICAL = 2,
528  LARGE = 1,
529  OK = 0
530 };
531 
547 {
548 protected:
554  int32_t nBlockSequenceId GUARDED_BY(::cs_main) = 1;
559 
565 
572  mutable std::atomic<bool> m_cached_finished_ibd{false};
573 
577 
579 
581  std::unique_ptr<CoinsViews> m_coins_views;
582 
583 public:
587 
592 
593  explicit CChainState(
594  CTxMemPool* mempool,
595  BlockManager& blockman,
596  ChainstateManager& chainman,
597  std::optional<uint256> from_snapshot_blockhash = std::nullopt);
598 
605  void InitCoinsDB(
606  size_t cache_size_bytes,
607  bool in_memory,
608  bool should_wipe,
609  std::string leveldb_name = "chainstate");
610 
613  void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
614 
617  bool CanFlushToDisk() const EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
618  return m_coins_views && m_coins_views->m_cacheview;
619  }
620 
624 
630  const std::optional<uint256> m_from_snapshot_blockhash;
631 
638  std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
639 
642  {
643  assert(m_coins_views->m_cacheview);
644  return *m_coins_views->m_cacheview.get();
645  }
646 
649  {
650  return m_coins_views->m_dbview;
651  }
652 
656  {
657  return m_coins_views->m_catcherview;
658  }
659 
661  void ResetCoinsViews() { m_coins_views.reset(); }
662 
665 
668 
671  bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size)
673 
675  void LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp = nullptr);
676 
688  bool FlushStateToDisk(
689  BlockValidationState& state,
690  FlushStateMode mode,
691  int nManualPruneHeight = 0);
692 
694  void ForceFlushStateToDisk();
695 
698  void PruneAndFlush();
699 
715  bool ActivateBestChain(
716  BlockValidationState& state,
717  std::shared_ptr<const CBlock> pblock = nullptr) LOCKS_EXCLUDED(cs_main);
718 
719  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);
720 
721  // Block (dis)connection on a given view:
722  DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
723  bool ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,
724  CCoinsViewCache& view, bool fJustCheck = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
725 
726  // Apply the effects of a block disconnection on the UTXO set.
728 
729  // Manual block validity manipulation:
739 
741  bool ReplayBlocks();
742 
744  [[nodiscard]] bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main);
746  bool LoadGenesisBlock();
747 
749 
751 
753  bool IsInitialBlockDownload() const;
754 
760  void CheckBlockIndex();
761 
763  void LoadMempool(const ArgsManager& args);
764 
767 
771  CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
772 
773  CoinsCacheSizeState GetCoinsCacheSizeState(
774  size_t max_coins_cache_size_bytes,
775  size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
776 
777  std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
778 
779 private:
780  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);
781  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);
782 
785  void ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
786 
788 
791 
794  {
795  return m_mempool ? &m_mempool->cs : nullptr;
796  }
797 
812  DisconnectedBlockTransactions& disconnectpool,
814 
816  void UpdateTip(const CBlockIndex* pindexNew)
818 
819  friend ChainstateManager;
820 };
821 
850 {
851 private:
867  std::unique_ptr<CChainState> m_ibd_chainstate GUARDED_BY(::cs_main);
868 
878  std::unique_ptr<CChainState> m_snapshot_chainstate GUARDED_BY(::cs_main);
879 
889  CChainState* m_active_chainstate GUARDED_BY(::cs_main) {nullptr};
890 
893  bool m_snapshot_validated{false};
894 
896  [[nodiscard]] bool PopulateAndValidateSnapshot(
897  CChainState& snapshot_chainstate,
898  CAutoFile& coins_file,
899  const SnapshotMetadata& metadata);
900 
901 public:
902  std::thread m_load_block;
905  BlockManager m_blockman GUARDED_BY(::cs_main);
906 
910  //
914 
919  // constructor
922  CChainState& InitializeChainstate(
923  CTxMemPool* mempool,
924  const std::optional<uint256>& snapshot_blockhash = std::nullopt)
926 
928  std::vector<CChainState*> GetAll();
929 
943  [[nodiscard]] bool ActivateSnapshot(
944  CAutoFile& coins_file, const SnapshotMetadata& metadata, bool in_memory);
945 
947  CChainState& ActiveChainstate() const;
949  int ActiveHeight() const { return ActiveChain().Height(); }
950  CBlockIndex* ActiveTip() const { return ActiveChain().Tip(); }
951 
953  {
954  return m_blockman.m_block_index;
955  }
956 
959  bool IsSnapshotActive() const;
960 
961  std::optional<uint256> SnapshotBlockhash() const;
962 
964  bool IsSnapshotValidated() const { return m_snapshot_validated; }
965 
985  bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock>& block, bool force_processing, bool* new_block) LOCKS_EXCLUDED(cs_main);
986 
998  bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, BlockValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex = nullptr) LOCKS_EXCLUDED(cs_main);
999 
1002 
1004  void Unload() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1005 
1007  void Reset();
1008 
1011  void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
1012 
1014  LOCK(::cs_main);
1015  UnloadBlockIndex(/* mempool */ nullptr, *this);
1016  Reset();
1017  }
1018 };
1019 
1020 using FopenFn = std::function<FILE*(const fs::path&, const char*)>;
1021 
1023 bool DumpMempool(const CTxMemPool& pool, FopenFn mockable_fopen_function = fsbridge::fopen, bool skip_file_commit = false);
1024 
1026 bool LoadMempool(CTxMemPool& pool, CChainState& active_chainstate, FopenFn mockable_fopen_function = fsbridge::fopen);
1027 
1035 const AssumeutxoData* ExpectedAssumeutxo(const int height, const CChainParams& params);
1036 
1037 #endif // BITCOIN_VALIDATION_H
CChainState::CChainState
CChainState(CTxMemPool *mempool, BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
Definition: validation.cpp:1094
MempoolAcceptResult::m_replaced_transactions
const std::optional< std::list< CTransactionRef > > m_replaced_transactions
Mempool transactions replaced by the tx per BIP 125 rules.
Definition: validation.h:160
arith_uint256.h
BlockManager::PruneOneBlockFile
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
Definition: validation.cpp:3469
CChainState::FindMostWorkChain
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...
Definition: validation.cpp:2340
feerate.h
CCoinsViewDB
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:49
ExpectedAssumeutxo
const AssumeutxoData * ExpectedAssumeutxo(const int height, const CChainParams &params)
Return the expected assumeutxo value for a given height, if one exists.
Definition: validation.cpp:4669
ChainstateManager::BlockIndex
BlockMap & BlockIndex() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:952
CChainState::RollforwardBlock
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.
Definition: validation.cpp:3896
ToString
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:87
FlushStateMode::ALWAYS
@ ALWAYS
DEFAULT_CHECKLEVEL
static const unsigned int DEFAULT_CHECKLEVEL
Definition: validation.h:81
fCheckBlockIndex
bool fCheckBlockIndex
Definition: validation.cpp:126
assert
assert(!tx.IsCoinBase())
ChainstateManager::ProcessNewBlockHeaders
bool ProcessNewBlockHeaders(const std::vector< CBlockHeader > &block, BlockValidationState &state, const CChainParams &chainparams, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
Process incoming block headers.
Definition: validation.cpp:3284
DISCONNECT_FAILED
@ DISCONNECT_FAILED
Definition: validation.h:352
CChainState::MempoolMutex
RecursiveMutex * MempoolMutex() const LOCK_RETURNED(m_mempool -> cs)
Indirection necessary to make lock annotations work with an optional mempool.
Definition: validation.h:793
CChainState::ForceFlushStateToDisk
void ForceFlushStateToDisk()
Unconditionally flush all changes to disk.
Definition: validation.cpp:2060
DEFAULT_PERSIST_MEMPOOL
static const bool DEFAULT_PERSIST_MEMPOOL
Default for -persistmempool.
Definition: validation.h:75
check.h
g_parallel_script_checks
bool g_parallel_script_checks
Whether there are dedicated script-checking threads running.
Definition: validation.cpp:124
hashAssumeValid
uint256 hashAssumeValid
Block hash whose ancestors we will assume to have valid scripts without checking them.
Definition: validation.cpp:130
ChainstateManager::m_total_coinstip_cache
int64_t m_total_coinstip_cache
The total number of bytes available for us to use across all in-memory coins caches.
Definition: validation.h:909
CoinsCacheSizeState::OK
@ OK
fs.h
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
MempoolAcceptResult::m_state
const TxValidationState m_state
Definition: validation.h:156
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
DEFAULT_ANCESTOR_SIZE_LIMIT
static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT
Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors.
Definition: validation.h:58
BlockValidationState
Definition: validation.h:140
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
flags
int flags
Definition: bitcoin-tx.cpp:525
FlushStateMode::NONE
@ NONE
CChainState::PreciousBlock
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as precious and reorganize.
Definition: validation.cpp:2635
CoinsCacheSizeState::CRITICAL
@ CRITICAL
The coins cache is in immediate need of a flush.
AssumeutxoData
Holds configuration for use during UTXO snapshot load and validation.
Definition: chainparams.h:40
sync.h
MempoolAcceptResult::m_result_type
const ResultType m_result_type
Definition: validation.h:155
PackageMempoolAcceptResult::m_tx_results
std::map< const uint256, const MempoolAcceptResult > m_tx_results
Map from wtxid to finished MempoolAcceptResults.
Definition: validation.h:197
nMaxTipAge
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
bilingual_str
Bilingual messages:
Definition: translation.h:16
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:475
MAX_SCRIPTCHECK_THREADS
static const int MAX_SCRIPTCHECK_THREADS
Maximum number of dedicated script-checking threads allowed.
Definition: validation.h:66
uint256.h
arith_uint256
256-bit unsigned big integer.
Definition: arith_uint256.h:250
CChainState::CheckBlockIndex
void CheckBlockIndex()
Make various assertions about the state of the block index.
Definition: validation.cpp:4193
BlockManager::GUARDED_BY
BlockMap m_block_index GUARDED_BY(cs_main)
CScriptCheck::ptxTo
const CTransaction * ptxTo
Definition: validation.h:285
CHECKLEVEL_DOC
const std::vector< std::string > CHECKLEVEL_DOC
Documentation for argument 'checklevel'.
Definition: validation.cpp:81
g_best_block_mutex
Mutex g_best_block_mutex
Definition: validation.cpp:121
CBlockIndexWorkComparator::operator()
bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const
Definition: validation.cpp:90
DEFAULT_MEMPOOL_EXPIRY
static const unsigned int DEFAULT_MEMPOOL_EXPIRY
Default for -mempoolexpiry, expiration time for mempool transactions in hours.
Definition: validation.h:64
CChainState::PruneBlockIndexCandidates
void PruneBlockIndexCandidates()
Delete all entries in setBlockIndexCandidates that are worse than the current tip.
Definition: validation.cpp:2396
CoinsCacheSizeState::LARGE
@ LARGE
The cache is at >= 90% capacity.
DEFAULT_STOPATHEIGHT
static const int DEFAULT_STOPATHEIGHT
Default for -stopatheight.
Definition: validation.h:77
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:69
ChainstateManager::m_snapshot_validated
bool m_snapshot_validated
If true, the assumed-valid chainstate has been fully validated by the background validation chainstat...
Definition: validation.h:893
fCheckpointsEnabled
bool fCheckpointsEnabled
Definition: validation.cpp:127
AnnotatedMixin< std::recursive_mutex >
CChainState::InvalidBlockFound
void InvalidBlockFound(CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:1213
FlushStateMode
FlushStateMode
Definition: validation.h:358
MIN_BLOCKS_TO_KEEP
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ::ChainActive()....
Definition: validation.h:79
bitcoin-config.h
BlockManager
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: validation.h:377
ChainstateManager::ActiveChainstate
CChainState & ActiveChainstate() const
The most-work chain.
Definition: validation.cpp:4960
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
GetBlockSubsidy
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
Definition: validation.cpp:1068
CChainState::ActivateBestChain
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(cs_main)
Find the best known block, and make it the tip of the block chain.
Definition: validation.cpp:2535
InitScriptExecutionCache
void InitScriptExecutionCache()
Initializes the script-execution cache.
Definition: validation.cpp:1262
CChainState::m_cs_chainstate
RecursiveMutex m_cs_chainstate
the ChainState CriticalSection A lock that must be held when modifying this ChainState - held in Acti...
Definition: validation.h:564
DEFAULT_DESCENDANT_LIMIT
static const unsigned int DEFAULT_DESCENDANT_LIMIT
Default for -limitdescendantcount, max number of in-mempool descendants.
Definition: validation.h:60
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:421
CFeeRate
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:29
CChainState::m_cached_finished_ibd
std::atomic< bool > m_cached_finished_ibd
Whether this chainstate is undergoing initial block download.
Definition: validation.h:572
CChainState::DisconnectTip
bool DisconnectTip(BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Disconnect m_chain's tip.
Definition: validation.cpp:2170
CChainState::ActivateBestChainStep
bool ActivateBestChainStep(BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, ConnectTrace &connectTrace) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Dictates whether we need to flush the cache to disk or not.
Definition: validation.cpp:2413
MempoolAcceptResult::ResultType
ResultType
Used to indicate the results of mempool validation.
Definition: validation.h:151
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
MempoolAcceptResult::Success
static MempoolAcceptResult Success(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
Definition: validation.h:167
ScriptError
enum ScriptError_t ScriptError
MempoolAcceptResult::m_base_fees
const std::optional< CAmount > m_base_fees
Raw base fees in satoshis.
Definition: validation.h:162
ChainstateManager::ActiveChain
CChain & ActiveChain() const
Definition: validation.h:948
UpdateUncommittedBlockStructures
void UpdateUncommittedBlockStructures(CBlock &block, const CBlockIndex *pindexPrev, const Consensus::Params &consensusParams)
Update uncommitted block structures (currently: only the witness reserved value).
Definition: validation.cpp:3003
CScriptCheck::nIn
unsigned int nIn
Definition: validation.h:286
CChainState::ResetCoinsViews
void ResetCoinsViews()
Destructs all objects related to accessing the UTXO set.
Definition: validation.h:661
txmempool.h
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:157
ValidationState::IsValid
bool IsValid() const
Definition: validation.h:119
PruneBlockFilesManual
void PruneBlockFilesManual(CChainState &active_chainstate, int nManualPruneHeight)
Prune block files up to a given height.
Definition: validation.cpp:3527
CoinsCacheSizeState
CoinsCacheSizeState
Definition: validation.h:523
TxValidationState
Definition: validation.h:139
packages.h
CAutoFile
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:564
Assume
#define Assume(val)
Assume is the identity function.
Definition: check.h:72
Consensus::Params
Parameters that influence chain consensus.
Definition: params.h:70
PackageMempoolAcceptResult::PackageMempoolAcceptResult
PackageMempoolAcceptResult(const uint256 &wtxid, const MempoolAcceptResult &result)
Constructor to create a PackageMempoolAcceptResult from a single MempoolAcceptResult.
Definition: validation.h:204
BlockManager::FindFilesToPruneManual
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
Definition: validation.cpp:3503
CScriptCheck::swap
void swap(CScriptCheck &check)
Definition: validation.h:299
ChainstateManager::IsSnapshotActive
bool IsSnapshotActive() const
Definition: validation.cpp:4967
BlockManager::AcceptBlockHeader
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...
Definition: validation.cpp:3195
CScriptCheck::CScriptCheck
CScriptCheck()
Definition: validation.h:293
PackageMempoolAcceptResult::PackageMempoolAcceptResult
PackageMempoolAcceptResult(PackageValidationState state, std::map< const uint256, const MempoolAcceptResult > &&results)
Definition: validation.h:199
fRequireStandard
bool fRequireStandard
Definition: validation.cpp:125
FopenFn
std::function< FILE *(const fs::path &, const char *)> FopenFn
Definition: validation.h:1020
CTxMemPool::cs
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:563
DEFAULT_ANCESTOR_LIMIT
static const unsigned int DEFAULT_ANCESTOR_LIMIT
Default for -limitancestorcount, max number of in-mempool ancestors.
Definition: validation.h:56
CChainState::PruneAndFlush
void PruneAndFlush()
Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.
Definition: validation.cpp:2068
CScriptCheck::GetScriptError
ScriptError GetScriptError() const
Definition: validation.h:309
CTxOut
An output of a transaction.
Definition: transaction.h:128
Consensus
Transaction validation functions.
Definition: params.h:12
StopScriptCheckWorkerThreads
void StopScriptCheckWorkerThreads()
Stop all of the script checking worker threads.
Definition: validation.cpp:1492
ChainstateManager::ActiveTip
CBlockIndex * ActiveTip() const
Definition: validation.h:950
DEFAULT_COINSTATSINDEX
static constexpr bool DEFAULT_COINSTATSINDEX
Definition: validation.h:72
fs::path
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
AbortNode
bool AbortNode(BlockValidationState &state, const std::string &strMessage, const bilingual_str &userMessage=bilingual_str{})
Definition: validation.cpp:1385
FlatFilePos
Definition: flatfile.h:14
CChainState::NeedsRedownload
bool NeedsRedownload() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Whether the chain state needs to be redownloaded due to lack of witness data.
Definition: validation.cpp:3983
BlockManager::LoadBlockIndex
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:443
ChainstateManager::SnapshotBlockhash
std::optional< uint256 > SnapshotBlockhash() const
Definition: validation.cpp:4620
CChainState::InvalidateBlock
bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(cs_main)
Mark a block as invalid.
Definition: validation.cpp:2664
DEFAULT_CHECKPOINTS_ENABLED
static const bool DEFAULT_CHECKPOINTS_ENABLED
Definition: validation.h:70
PackageValidationState
Definition: packages.h:34
ChainstateManager::ActiveHeight
int ActiveHeight() const
Definition: validation.h:949
CChainState::m_params
const CChainParams & m_params
Definition: validation.h:578
minRelayTxFee
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation)
Definition: validation.cpp:133
MempoolAcceptResult::ResultType::INVALID
@ INVALID
Fully validated, valid.
ChainstateManager::IsSnapshotValidated
bool IsSnapshotValidated() const
Is there a snapshot in use and has it been fully validated?
Definition: validation.h:964
ChainTxData
Holds various statistics on transactions within a chain.
Definition: chainparams.h:59
CChainState::ChainstateManager
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:816
DEFAULT_MAX_TIP_AGE
static const int64_t DEFAULT_MAX_TIP_AGE
Definition: validation.h:69
PackageMempoolAcceptResult
Validation result for package mempool acceptance.
Definition: validation.h:188
CChainState::LoadMempool
void LoadMempool(const ArgsManager &args)
Load the persisted mempool from disk.
Definition: validation.cpp:3738
CChainState::m_from_snapshot_blockhash
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:630
CChainState::nLastPreciousChainwork
arith_uint256 nLastPreciousChainwork
chainwork for the last block that preciousblock has been applied to.
Definition: validation.h:558
DISCONNECT_UNCLEAN
@ DISCONNECT_UNCLEAN
Definition: validation.h:351
CBlockTreeDB
Access to the block database (blocks/index/)
Definition: txdb.h:77
CChainState::MaybeUpdateMempoolForReorg
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:333
CAmount
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
SynchronizationState::INIT_REINDEX
@ INIT_REINDEX
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:118
ConnectTrace
Used to track blocks whose transactions were applied to the UTXO state as a part of a single Activate...
Definition: validation.cpp:2239
CChainState::AcceptBlock
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)
Store block on disk.
Definition: validation.cpp:3312
GuessVerificationProgress
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).
Definition: validation.cpp:4603
CChainState::m_chainman
ChainstateManager & m_chainman
The chainstate manager that owns this chainstate.
Definition: validation.h:591
AcceptToMemoryPool
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.
Definition: validation.cpp:1041
ChainstateManager::ProcessNewBlock
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > &block, bool force_processing, bool *new_block) LOCKS_EXCLUDED(cs_main)
Process an incoming block.
Definition: validation.cpp:3394
PrecomputedTransactionData
Definition: interpreter.h:150
CCheckpointData
Definition: chainparams.h:22
CChainState::m_coins_views
std::unique_ptr< CoinsViews > m_coins_views
Manages the UTXO set, which is a reflection of the contents of m_chain.
Definition: validation.h:581
ChainstateManager::GetAll
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:928
uint256
256-bit opaque blob.
Definition: uint256.h:124
LOCK_RETURNED
#define LOCK_RETURNED(x)
Definition: threadsafety.h:47
BlockManager::FindForkInGlobalIndex
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
PackageMempoolAcceptResult::m_state
const PackageValidationState m_state
Definition: validation.h:190
CScriptCheck::error
ScriptError error
Definition: validation.h:289
CChainState
CChainState stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:546
CChainState::CoinsDB
CCoinsViewDB & CoinsDB() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:648
CChainState::DisconnectBlock
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view)
Undo the effects of this block (with given index) on the UTXO set represented by coins.
Definition: validation.cpp:1428
ChainstateManager::GUARDED_BY
CChainState *m_active_chainstate GUARDED_BY(::cs_main)
Points to either the ibd or snapshot chainstate; indicates our most-work chain.
Definition: validation.h:889
TestBlockValidity
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)
Definition: validation.cpp:3433
CChainState::ReceivedBlockTransactions
void ReceivedBlockTransactions(const CBlock &block, CBlockIndex *pindexNew, const FlatFilePos &pos) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).
Definition: validation.cpp:2877
StartScriptCheckWorkerThreads
void StartScriptCheckWorkerThreads(int threads_num)
Run instances of script checking worker threads.
Definition: validation.cpp:1487
chain.h
CChainState::m_coinsdb_cache_size_bytes
size_t m_coinsdb_cache_size_bytes
The cache size of the on-disk coins view.
Definition: validation.h:664
DISCONNECT_OK
@ DISCONNECT_OK
Definition: validation.h:350
CChainState::ReplayBlocks
bool ReplayBlocks()
Replay blocks that aren't fully applied to the database.
Definition: validation.cpp:3916
TestLockPointValidity
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
DEFAULT_MIN_RELAY_TX_FEE
static const unsigned int DEFAULT_MIN_RELAY_TX_FEE
Default for -minrelaytxfee, minimum relay fee for transactions.
Definition: validation.h:54
CoinsViews::GUARDED_BY
CCoinsViewDB m_dbview GUARDED_BY(cs_main)
The lowest level of the CoinsViews cache hierarchy sits in a leveldb database on disk.
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:446
BlockManager::FindFilesToPrune
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...
Definition: validation.cpp:3536
hasher.h
BlockManager::GetSpendHeight
int GetSpendHeight(const CCoinsViewCache &inputs) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return the spend height, which is one more than the inputs.GetBestBlock().
Definition: validation.cpp:1251
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:849
attributes.h
CVerifyDB
RAII wrapper for VerifyDB: Verify consistency of the block and coin databases.
Definition: validation.h:336
CChainState::cs
bool m_mempool cs
Definition: validation.h:727
CheckBlock
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.
Definition: validation.cpp:2929
CChainState::CheckForkWarningConditions
void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:1173
CScriptCheck::CScriptCheck
CScriptCheck(const CTxOut &outIn, const CTransaction &txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData *txdataIn)
Definition: validation.h:294
MempoolAcceptResult::ResultType::VALID
@ VALID
CBlock
Definition: block.h:62
BlockManager::LookupBlockIndex
CBlockIndex * LookupBlockIndex(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:150
UnloadBlockIndex
void UnloadBlockIndex(CTxMemPool *mempool, ChainstateManager &chainman)
Unload database information.
Definition: validation.cpp:4009
DisconnectedBlockTransactions
Definition: txmempool.h:942
MempoolAcceptResult::MempoolAcceptResult
MempoolAcceptResult(TxValidationState state)
Constructor for failure case.
Definition: validation.h:174
CChain
An in-memory indexed chain of blocks.
Definition: chain.h:410
MIN_DISK_SPACE_FOR_BLOCK_FILES
static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES
Definition: validation.h:90
LOCKS_EXCLUDED
#define LOCKS_EXCLUDED(...)
Definition: threadsafety.h:48
CChainState::nBlockReverseSequenceId
int32_t nBlockReverseSequenceId
Decreasing counter (used by subsequent preciousblock calls).
Definition: validation.h:556
LIFETIMEBOUND
#define LIFETIMEBOUND
Definition: attributes.h:16
BlockManager::AddToBlockIndex
CBlockIndex * AddToBlockIndex(const CBlockHeader &block) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:2840
CBlockIndexWorkComparator
Definition: validation.h:365
BlockManager::m_failed_blocks
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:423
SynchronizationState::INIT_DOWNLOAD
@ INIT_DOWNLOAD
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
ProcessNewPackage
PackageMempoolAcceptResult ProcessNewPackage(CChainState &active_chainstate, CTxMemPool &pool, const Package &txns, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Atomically test acceptance of a package.
Definition: validation.cpp:1047
ArgsManager
Definition: system.h:158
translation.h
EXCLUSIVE_LOCKS_REQUIRED
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
MempoolAcceptResult::Failure
static MempoolAcceptResult Failure(TxValidationState state)
Definition: validation.h:163
LOCK
#define LOCK(cs)
Definition: sync.h:226
script_error.h
ChainstateManager::ActivateSnapshot
bool ActivateSnapshot(CAutoFile &coins_file, const SnapshotMetadata &metadata, bool in_memory)
Construct and activate a Chainstate on the basis of UTXO snapshot data.
Definition: validation.cpp:4681
ChainstateManager::LoadBlockIndex
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the block tree and coins database from disk, initializing state if we're running with -reindex.
Definition: validation.cpp:4027
CChainState::GUARDED_BY
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...
LockPoints
Definition: txmempool.h:40
g_best_block_cv
std::condition_variable g_best_block_cv
Definition: validation.cpp:122
MempoolAcceptResult
Validation result for a single transaction mempool acceptance.
Definition: validation.h:149
CChainState::setBlockIndexCandidates
std::set< CBlockIndex *, CBlockIndexWorkComparator > setBlockIndexCandidates
The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors...
Definition: validation.h:638
CCoinsViewErrorCatcher
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:343
CChainState::m_blockman
BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all CChainState instances.
Definition: validation.h:586
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:561
CScriptCheck
Closure representing one script verification Note that this stores references to the spending transac...
Definition: validation.h:281
CChainState::InitCoinsDB
void InitCoinsDB(size_t cache_size_bytes, bool in_memory, bool should_wipe, std::string leveldb_name="chainstate")
Initialize the CoinsViews UTXO set database management data structures.
Definition: validation.cpp:1105
CScriptCheck::cacheStore
bool cacheStore
Definition: validation.h:288
LoadMempool
bool LoadMempool(CTxMemPool &pool, CChainState &active_chainstate, FopenFn mockable_fopen_function=fsbridge::fopen)
Load the mempool from disk.
Definition: validation.cpp:4456
DEFAULT_BLOCKFILTERINDEX
static const char *const DEFAULT_BLOCKFILTERINDEX
Definition: validation.h:73
Package
std::vector< CTransactionRef > Package
A package is an ordered list of transactions.
Definition: packages.h:32
CChainState::ConnectBlock
bool ConnectBlock(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Apply the effects of this block (with given index) on the UTXO set represented by coins.
Definition: validation.cpp:1582
CChainState::LoadChainTip
bool LoadChainTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Update the chain tip based on database information, i.e.
Definition: validation.cpp:3747
CChainState::ResetBlockFailureFlags
void ResetBlockFailureFlags(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove invalidity status from a block and its descendants.
Definition: validation.cpp:2806
DEFAULT_SCRIPTCHECK_THREADS
static const int DEFAULT_SCRIPTCHECK_THREADS
-par default (number of script-checking threads, 0 = auto)
Definition: validation.h:68
BlockManager::GetLastCheckpoint
CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
Definition: validation.cpp:3042
CScriptCheck::m_tx_out
CTxOut m_tx_out
Definition: validation.h:284
SynchronizationState
SynchronizationState
Current sync state passed to tip changed callbacks.
Definition: validation.h:93
CoinsViews
A convenience class for constructing the CCoinsView* hierarchy used to facilitate access to the UTXO ...
Definition: validation.h:497
pindexBestHeader
CBlockIndex * pindexBestHeader
Best header we've seen so far (used for getheaders queries' starting points).
Definition: validation.cpp:120
BlockManager::m_blocks_unlinked
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:429
ChainstateManager::m_total_coinsdb_cache
int64_t m_total_coinsdb_cache
The total number of bytes available for us to use across all leveldb coins databases.
Definition: validation.h:913
DEFAULT_TXINDEX
static const bool DEFAULT_TXINDEX
Definition: validation.h:71
CScriptCheck::nFlags
unsigned int nFlags
Definition: validation.h:287
lp
LockPoints lp
Definition: mempool_eviction.cpp:17
CChainState::FlushStateToDisk
bool FlushStateToDisk(BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
Update the on-disk chain state.
Definition: validation.cpp:1923
DEFAULT_DESCENDANT_SIZE_LIMIT
static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT
Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants.
Definition: validation.h:62
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
MempoolAcceptResult::MempoolAcceptResult
MempoolAcceptResult(std::list< CTransactionRef > &&replaced_txns, CAmount fees)
Constructor for success case.
Definition: validation.h:180
FlushStateMode::IF_NEEDED
@ IF_NEEDED
CheckFinalTx
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
CBlockLocator
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:114
nMinimumChainWork
arith_uint256 nMinimumChainWork
Minimum work we will assume exists on some valid chain.
Definition: validation.cpp:131
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:145
SCRIPT_ERR_UNKNOWN_ERROR
@ SCRIPT_ERR_UNKNOWN_ERROR
Definition: script_error.h:14
CChainState::ConnectTip
bool ConnectTip(BlockValidationState &state, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, ConnectTrace &connectTrace, DisconnectedBlockTransactions &disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
Connect a new block to m_chain.
Definition: validation.cpp:2273
CChainState::m_coinstip_cache_size_bytes
size_t m_coinstip_cache_size_bytes
The cache size of the in-memory coins view.
Definition: validation.h:667
CChainState::LoadGenesisBlock
bool LoadGenesisBlock()
Ensures we have a genesis block in the block tree, possibly writing one to disk.
Definition: validation.cpp:4050
BlockManager::CChainState
friend CChainState
Definition: validation.h:379
amount.h
CoinsViews::CoinsViews
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...
Definition: validation.cpp:1081
CScriptCheck::txdata
PrecomputedTransactionData * txdata
Definition: validation.h:290
ChainstateManager::GUARDED_BY
std::unique_ptr< CChainState > m_ibd_chainstate GUARDED_BY(::cs_main)
The chainstate used under normal operation (i.e.
DisconnectResult
DisconnectResult
Definition: validation.h:348
CChainState::CoinsErrorCatcher
CCoinsViewErrorCatcher & CoinsErrorCatcher() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:655
CheckSequenceLocks
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
CChainState::CoinsTip
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:641
txdb.h
SnapshotMetadata
Metadata describing a serialized version of a UTXO set from which an assumeutxo CChainState can be co...
Definition: utxo_snapshot.h:14
UpdateCoins
void UpdateCoins(const CTransaction &tx, CCoinsViewCache &inputs, int nHeight)
Apply the effects of this transaction on the UTXO set represented by view.
Definition: validation.cpp:1239
ChainstateManager::m_load_block
std::thread m_load_block
Definition: validation.h:902
BlockManager::InsertBlockIndex
CBlockIndex * InsertBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
Definition: validation.cpp:3595
SynchronizationState::POST_INIT
@ POST_INIT
CChainState::m_chain
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:623
DumpMempool
bool DumpMempool(const CTxMemPool &pool, FopenFn mockable_fopen_function=fsbridge::fopen, bool skip_file_commit=false)
Dump the mempool to disk.
Definition: validation.cpp:4540
CChainState::m_mempool
CTxMemPool * m_mempool
Optional mempool that is kept in sync with the chain.
Definition: validation.h:576
BlockManager::Unload
void Unload() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Clear all data members.
Definition: validation.cpp:3672
g_best_block
uint256 g_best_block
Used to notify getblocktemplate RPC of new tips.
Definition: validation.cpp:123
RNGLevel::PERIODIC
@ PERIODIC
Called by RandAddPeriodic()
BlockMap
std::unordered_map< uint256, CBlockIndex *, BlockHasher > BlockMap
Definition: validation.h:100
DEFAULT_CHECKBLOCKS
static const signed int DEFAULT_CHECKBLOCKS
Definition: validation.h:80
GenerateCoinbaseCommitment
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...
Definition: validation.cpp:3015
CChainState::InvalidChainFound
void InvalidChainFound(CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.cpp:1192
ChainstateManager::PopulateAndValidateSnapshot
bool PopulateAndValidateSnapshot(CChainState &snapshot_chainstate, CAutoFile &coins_file, const SnapshotMetadata &metadata)
Internal helper for ActivateSnapshot().
Definition: validation.cpp:4764