Bitcoin Core 30.99.0
P2P Digital Currency
Public Types | Public Member Functions | Public Attributes | Protected Member Functions | Private Member Functions | Private Attributes | List of all members
ChainstateManager Class Reference

Interface for managing multiple Chainstate objects, where each chainstate is associated with chainstate* subdirectory in the data directory and contains a database of UTXOs existing at a different point in history. More...

#include <validation.h>

Inheritance diagram for ChainstateManager:
[legend]
Collaboration diagram for ChainstateManager:
[legend]

Public Types

using Options = kernel::ChainstateManagerOpts
 

Public Member Functions

 ChainstateManager (const util::SignalInterrupt &interrupt, Options options, node::BlockManager::Options blockman_options)
 
const CChainParamsGetParams () const
 
const Consensus::ParamsGetConsensus () const
 
bool ShouldCheckBlockIndex () const
 
const arith_uint256MinimumChainWork () const
 
const uint256AssumedValidBlock () const
 
kernel::NotificationsGetNotifications () const
 
void CheckBlockIndex () const
 Make various assertions about the state of the block index. More...
 
RecursiveMutexGetMutex () const LOCK_RETURNED(
 Alias for cs_main. More...
 
int32_t nBlockSequenceId GUARDED_BY (::cs_main)
 Every received block is assigned a unique and increasing identifier, so we know which one to give priority in case of a fork. More...
 
void ResetBlockSequenceCounters () EXCLUSIVE_LOCKS_REQUIRED(
 
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, among others, for getheaders queries' starting points). More...
 
ChainstateHistoricalChainstate () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 Return historical chainstate targeting a specific block, if any. More...
 
ChainstateValidatedChainstate () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 Return fully validated chainstate that should be used for indexing, to support indexes that need to index blocks in order and can't start from the snapshot block. More...
 
std::unique_ptr< ChainstateRemoveChainstate (Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 Remove a chainstate. More...
 
node::BlockMapBlockIndex () EXCLUSIVE_LOCKS_REQUIRED(
 
bool IsInitialBlockDownload () const
 Check whether we are doing an initial block download (synchronizing from disk or network) More...
 
double GuessVerificationProgress (const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). More...
 
void LoadExternalBlockFile (AutoFile &file_in, FlatFilePos *dbp=nullptr, std::multimap< uint256, FlatFilePos > *blocks_with_unknown_parent=nullptr)
 Import blocks from an external file. More...
 
bool ProcessNewBlock (const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block) LOCKS_EXCLUDED(cs_main)
 Process an incoming block. More...
 
bool ProcessNewBlockHeaders (std::span< const CBlockHeader > headers, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr) LOCKS_EXCLUDED(cs_main)
 Process incoming block headers. More...
 
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)
 Sufficiently validate a block for disk storage (and store on disk). More...
 
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). More...
 
MempoolAcceptResult ProcessTransaction (const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Try to add a transaction to the memory pool. More...
 
bool LoadBlockIndex () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Load the block tree and coins database from disk, initializing state if we're running with -reindex. More...
 
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void UpdateUncommittedBlockStructures (CBlock &block, const CBlockIndex *pindexPrev) const
 Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed. More...
 
std::vector< unsigned char > GenerateCoinbaseCommitment (CBlock &block, const CBlockIndex *pindexPrev) const
 Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). More...
 
void ReportHeadersPresync (const arith_uint256 &work, int64_t height, int64_t timestamp)
 This is used by net_processing to report pre-synchronization progress of headers, as headers are not yet fed to validation during that time, but validation is (for now) responsible for logging and signalling through NotifyHeaderTip, so it needs this information. More...
 
 ~ChainstateManager ()
 
std::vector< std::unique_ptr< Chainstate > > m_chainstates GUARDED_BY (::cs_main)
 List of chainstates. More...
 
ChainstateActiveChainstate () const
 Alternatives to CurrentChainstate() used by older code to query latest chainstate information without locking cs_main. More...
 
CChainActiveChain () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 
int ActiveHeight () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 
CBlockIndexActiveTip () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 

Public Attributes

std::function< void()> snapshot_download_completed = std::function<void()>()
 Function to restart active indexes; set dynamically to avoid a circular dependency on base/index.cpp. More...
 
const util::SignalInterruptm_interrupt
 
const Options m_options
 
node::BlockManager m_blockman
 A single BlockManager instance is shared across each constructed chainstate to avoid duplicating block metadata. More...
 
ValidationCache m_validation_cache
 
std::atomic< bool > m_cached_finished_ibd {false}
 Whether initial block download has ended and IsInitialBlockDownload should return false from now on. More...
 
int32_t nBlockReverseSequenceId = -1
 Decreasing counter (used by subsequent preciousblock calls). More...
 
arith_uint256 nLastPreciousChainwork = 0
 chainwork for the last block that preciousblock has been applied to. More...
 
size_t m_total_coinstip_cache {0}
 The total number of bytes available for us to use across all in-memory coins caches. More...
 
size_t m_total_coinsdb_cache {0}
 The total number of bytes available for us to use across all leveldb coins databases. More...
 
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(util::Result< CBlockIndexActivateSnapshot )(AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
 Instantiate a new chainstate. More...
 
SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(ChainstateCurrentChainstate () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the snapshot block. More...
 
VersionBitsCache m_versionbitscache
 Track versionbit status. More...
 
Chainstate *LoadAssumeutxoChainstate() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &AddChainstate(std::unique_ptr< Chainstate > chainstate) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(bool DeleteChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(std::optional< std::pair< const CBlockIndex *, const CBlockIndex * > > GetHistoricalBlockRange() const EXCLUSIVE_LOCKS_REQUIRED(util::Result< void > ActivateBestChains() LOCKS_EXCLUDED(void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(CCheckQueue< CScriptCheck > & GetCheckQueue ()
 When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process of being validated and load it if found. More...
 

Protected Member Functions

CBlockIndex *m_best_invalid GUARDED_BY (::cs_main)
 

Private Member Functions

CBlockIndex *m_last_notified_header GUARDED_BY (GetMutex())
 The last header for which a headerTip notification was issued. More...
 
bool NotifyHeaderTip () LOCKS_EXCLUDED(GetMutex())
 
util::Result< void > PopulateAndValidateSnapshot (Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
 Internal helper for ActivateSnapshot(). More...
 
bool AcceptBlockHeader (const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't descend from an invalid block, and then add it to m_block_index. More...
 
MockableSteadyClock::time_point m_last_presync_update GUARDED_BY (GetMutex())
 Most recent headers presync progress update, for rate-limiting. More...
 
SteadyClock::duration GUARDED_BY (::cs_main) time_check
 Timers and counters used for benchmarking validation in both background and active chainstates. More...
 
SteadyClock::duration GUARDED_BY (::cs_main) time_forks
 
SteadyClock::duration GUARDED_BY (::cs_main) time_connect
 
SteadyClock::duration GUARDED_BY (::cs_main) time_verify
 
SteadyClock::duration GUARDED_BY (::cs_main) time_undo
 
SteadyClock::duration GUARDED_BY (::cs_main) time_index
 
SteadyClock::duration GUARDED_BY (::cs_main) time_total
 
int64_t GUARDED_BY (::cs_main) num_blocks_total
 
SteadyClock::duration GUARDED_BY (::cs_main) time_connect_total
 
SteadyClock::duration GUARDED_BY (::cs_main) time_flush
 
SteadyClock::duration GUARDED_BY (::cs_main) time_chainstate
 
SteadyClock::duration GUARDED_BY (::cs_main) time_post_connect
 

Private Attributes

friend Chainstate
 
CCheckQueue< CScriptCheckm_script_check_queue
 A queue for script verifications that have to be performed by worker threads. More...
 

Detailed Description

Interface for managing multiple Chainstate objects, where each chainstate is associated with chainstate* subdirectory in the data directory and contains a database of UTXOs existing at a different point in history.

(See Chainstate class for more information.)

Normally there is exactly one Chainstate, which contains the UTXO set of chain tip if syncing is completed, or the UTXO set the most recent validated block if the initial sync is still in progress.

However, if an assumeutxo snapshot is loaded before syncing is completed, there will be two chainstates. The original fully validated chainstate will continue to exist and download new blocks in the background. But the new snapshot which is loaded will become a second chainstate. The second chainstate will be used as the chain tip for the wallet and RPCs even though it is only assumed to be valid. When the initial chainstate catches up to the snapshot height and confirms that the assumeutxo snapshot is actually valid, the second chainstate will be marked validated and become the only chainstate again.

Definition at line 929 of file validation.h.

Member Typedef Documentation

◆ Options

Definition at line 989 of file validation.h.

Constructor & Destructor Documentation

◆ ChainstateManager()

ChainstateManager::ChainstateManager ( const util::SignalInterrupt interrupt,
Options  options,
node::BlockManager::Options  blockman_options 
)
explicit

Definition at line 6203 of file validation.cpp.

◆ ~ChainstateManager()

ChainstateManager::~ChainstateManager ( )

Definition at line 6212 of file validation.cpp.

Here is the call graph for this function:

Member Function Documentation

◆ AcceptBlock()

bool ChainstateManager::AcceptBlock ( const std::shared_ptr< const CBlock > &  pblock,
BlockValidationState state,
CBlockIndex **  ppindex,
bool  fRequested,
const FlatFilePos dbp,
bool *  fNewBlock,
bool  min_pow_checked 
)

Sufficiently validate a block for disk storage (and store on disk).

Store block on disk.

Parameters
[in]pblockThe block we want to process.
[in]fRequestedWhether we requested this block from a peer.
[in]dbpThe location on disk, if we are importing this block from prior storage.
[in]min_pow_checkedTrue if proof-of-work anti-DoS checks have been done by caller for headers chain
[out]stateThe state of the block validation.
[out]ppindexOptional return parameter to get the CBlockIndex pointer for this block.
[out]fNewBlockOptional return parameter to indicate if the block is new to our storage.
Returns
False if the block or header is invalid, or if saving to disk fails (likely a fatal error); true otherwise.

If dbp is non-nullptr, the file is known to already reside on disk

Definition at line 4381 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ AcceptBlockHeader()

bool ChainstateManager::AcceptBlockHeader ( const CBlockHeader block,
BlockValidationState state,
CBlockIndex **  ppindex,
bool  min_pow_checked 
)
private

If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't descend from an invalid block, and then add it to m_block_index.

Caller must set min_pow_checked=true in order to add a new header to the block index (permanent memory storage), indicating that the header is known to be part of a sufficiently high-work chain (anti-dos check).

Definition at line 4269 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ActiveChain()

CChain & ChainstateManager::ActiveChain ( ) const
inline

Definition at line 1155 of file validation.h.

Here is the caller graph for this function:

◆ ActiveChainstate()

Chainstate & ChainstateManager::ActiveChainstate ( ) const

Alternatives to CurrentChainstate() used by older code to query latest chainstate information without locking cs_main.

Newer code should avoid querying ChainstateManager and use Chainstate objects directly, or should use CurrentChainstate() instead.

Definition at line 6147 of file validation.cpp.

Here is the caller graph for this function:

◆ ActiveHeight()

int ChainstateManager::ActiveHeight ( ) const
inline

Definition at line 1156 of file validation.h.

Here is the caller graph for this function:

◆ ActiveTip()

CBlockIndex * ChainstateManager::ActiveTip ( ) const
inline

Definition at line 1157 of file validation.h.

Here is the caller graph for this function:

◆ AssumedValidBlock()

const uint256 & ChainstateManager::AssumedValidBlock ( ) const
inline

Definition at line 1001 of file validation.h.

Here is the caller graph for this function:

◆ BlockIndex()

node::BlockMap & ChainstateManager::BlockIndex ( )
inline

Definition at line 1160 of file validation.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckBlockIndex()

void ChainstateManager::CheckBlockIndex ( ) const

Make various assertions about the state of the block index.

By default this only executes fully when using the Regtest chain; see: m_options.check_block_index.

Definition at line 5213 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GenerateCoinbaseCommitment()

std::vector< unsigned char > ChainstateManager::GenerateCoinbaseCommitment ( CBlock block,
const CBlockIndex pindexPrev 
) const

Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks).

Definition at line 4076 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetConsensus()

const Consensus::Params & ChainstateManager::GetConsensus ( ) const
inline

Definition at line 998 of file validation.h.

Here is the caller graph for this function:

◆ GetMutex()

RecursiveMutex & ChainstateManager::GetMutex ( ) const
inline

Alias for cs_main.

Should be used in new code to make it easier to make cs_main a member of this class. Generally, methods of this class should be annotated to require this mutex. This will make calling code more verbose, but also help to:

  • Clarify that the method will acquire a mutex that heavily affects overall performance.
  • Force call sites to think how long they need to acquire the mutex to get consistent results.

Definition at line 1022 of file validation.h.

Here is the caller graph for this function:

◆ GetNotifications()

kernel::Notifications & ChainstateManager::GetNotifications ( ) const
inline

Definition at line 1002 of file validation.h.

Here is the caller graph for this function:

◆ GetParams()

const CChainParams & ChainstateManager::GetParams ( ) const
inline

Definition at line 997 of file validation.h.

Here is the caller graph for this function:

◆ GUARDED_BY() [1/18]

CBlockIndex *m_best_invalid ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprotected

Definition at line 986 of file validation.h.

◆ GUARDED_BY() [2/18]

int32_t nBlockSequenceId ChainstateManager::GUARDED_BY ( ::cs_main  )

Every received block is assigned a unique and increasing identifier, so we know which one to give priority in case of a fork.

Blocks loaded from disk are assigned id SEQ_ID_INIT_FROM_DISK{1} (SEQ_ID_BEST_CHAIN_FROM_DISK{0} if they belong to the best chain loaded from disk), so start the counter after that.

◆ GUARDED_BY() [3/18]

CBlockIndex *m_best_header ChainstateManager::GUARDED_BY ( ::cs_main  )
inline

Best header we've seen so far for which the block is not known to be invalid (used, among others, for getheaders queries' starting points).

In case of multiple best headers with the same work, it could point to any because CBlockIndexWorkComparator tiebreaker rules are not applied.

Definition at line 1068 of file validation.h.

◆ GUARDED_BY() [4/18]

std::vector< std::unique_ptr< Chainstate > > m_chainstates ChainstateManager::GUARDED_BY ( ::cs_main  )

List of chainstates.

Note: in general, it is not safe to delete Chainstate objects once they are added to this list because there is no mutex that can be locked to prevent Chainstate pointers from being used while they are deleted. (cs_main doesn't work because it is too narrow and is released in the middle of Chainstate::ActivateBestChain to let notifications be processed. m_chainstate_mutex doesn't work because it is not locked at other times when the chainstate is in use.)

◆ GUARDED_BY() [5/18]

int64_t ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 979 of file validation.h.

◆ GUARDED_BY() [6/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 982 of file validation.h.

◆ GUARDED_BY() [7/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Timers and counters used for benchmarking validation in both background and active chainstates.

Definition at line 972 of file validation.h.

◆ GUARDED_BY() [8/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 974 of file validation.h.

◆ GUARDED_BY() [9/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 980 of file validation.h.

◆ GUARDED_BY() [10/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 981 of file validation.h.

◆ GUARDED_BY() [11/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 973 of file validation.h.

◆ GUARDED_BY() [12/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 977 of file validation.h.

◆ GUARDED_BY() [13/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 983 of file validation.h.

◆ GUARDED_BY() [14/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 978 of file validation.h.

◆ GUARDED_BY() [15/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 976 of file validation.h.

◆ GUARDED_BY() [16/18]

SteadyClock::duration ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 975 of file validation.h.

◆ GUARDED_BY() [17/18]

CBlockIndex *m_last_notified_header ChainstateManager::GUARDED_BY ( GetMutex()  )
inlineprivate

The last header for which a headerTip notification was issued.

Definition at line 934 of file validation.h.

◆ GUARDED_BY() [18/18]

MockableSteadyClock::time_point m_last_presync_update ChainstateManager::GUARDED_BY ( GetMutex()  )
inlineprivate

Most recent headers presync progress update, for rate-limiting.

Definition at line 965 of file validation.h.

◆ GuessVerificationProgress()

double ChainstateManager::GuessVerificationProgress ( const CBlockIndex pindex) const

Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip).

Definition at line 5570 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ HistoricalChainstate()

Chainstate * ChainstateManager::HistoricalChainstate ( ) const
inline

Return historical chainstate targeting a specific block, if any.

Definition at line 1118 of file validation.h.

Here is the caller graph for this function:

◆ IsInitialBlockDownload()

bool ChainstateManager::IsInitialBlockDownload ( ) const

Check whether we are doing an initial block download (synchronizing from disk or network)

Definition at line 1959 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadBlockIndex()

bool ChainstateManager::LoadBlockIndex ( )

Load the block tree and coins database from disk, initializing state if we're running with -reindex.

Definition at line 4967 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadExternalBlockFile()

void ChainstateManager::LoadExternalBlockFile ( AutoFile file_in,
FlatFilePos dbp = nullptr,
std::multimap< uint256, FlatFilePos > *  blocks_with_unknown_parent = nullptr 
)

Import blocks from an external file.

During reindexing, this function is called for each block file (datadir/blocks/blk?????.dat). It reads all blocks contained in the given file and attempts to process them (add them to the block index). The blocks may be out of order within each file and across files. Often this function reads a block but finds that its parent hasn't been read yet, so the block can't be processed yet. The function will add an entry to the blocks_with_unknown_parent map (which is passed as an argument), so that when the block's parent is later read and processed, this function can re-read the child block from disk and process it.

Because a block's parent may be in a later file, not just later in the same file, the blocks_with_unknown_parent map must be passed in and out with each call. It's a multimap, rather than just a map, because multiple blocks may have the same parent (when chain splits or stale blocks exist). It maps from parent-hash to child-disk-position.

This function can also be used to read blocks from user-specified block files using the -loadblock= option. There's no unknown-parent tracking, so the last two arguments are omitted.

Parameters
[in]file_inFile containing blocks to read
[in]dbp(optional) Disk block position (only for reindex)
[in,out]blocks_with_unknown_parent(optional) Map of disk positions for blocks with unknown parent, key is parent block hash (only used for reindex)

Definition at line 5036 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ MinimumChainWork()

const arith_uint256 & ChainstateManager::MinimumChainWork ( ) const
inline

Definition at line 1000 of file validation.h.

Here is the caller graph for this function:

◆ NotifyHeaderTip()

bool ChainstateManager::NotifyHeaderTip ( )
private

Definition at line 3363 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ PopulateAndValidateSnapshot()

util::Result< void > ChainstateManager::PopulateAndValidateSnapshot ( Chainstate snapshot_chainstate,
AutoFile coins_file,
const node::SnapshotMetadata metadata 
)
private

Internal helper for ActivateSnapshot().

De-serialization of a snapshot that is created with the dumptxoutset RPC. To reduce space the serialization format of the snapshot avoids duplication of tx hashes. The code takes advantage of the guarantee by leveldb that keys are lexicographically sorted.

Definition at line 5821 of file validation.cpp.

Here is the call graph for this function:

◆ ProcessNewBlock()

bool ChainstateManager::ProcessNewBlock ( const std::shared_ptr< const CBlock > &  block,
bool  force_processing,
bool  min_pow_checked,
bool *  new_block 
)

Process an incoming block.

This only returns after the best known valid block is made active. Note that it does not, however, guarantee that the specific block passed to it has been checked for validity!

If you want to possibly get feedback on whether block is valid, you must install a CValidationInterface (see validationinterface.h) - this will have its BlockChecked method called whenever any block completes validation.

Note that we guarantee that either the proof-of-work is valid on block, or (and possibly also) BlockChecked will have been called.

May not be called in a validationinterface callback.

Parameters
[in]blockThe block we want to process.
[in]force_processingProcess this block even if unrequested; used for non-network block sources.
[in]min_pow_checkedTrue if proof-of-work anti-DoS checks have been done by caller for headers chain (note: only affects headers acceptance; if block header is already present in block index then this parameter has no effect)
[out]new_blockA boolean which is set to indicate if the block was first received via this call
Returns
If the block was processed, independently of block validity

Definition at line 4481 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProcessNewBlockHeaders()

bool ChainstateManager::ProcessNewBlockHeaders ( std::span< const CBlockHeader headers,
bool  min_pow_checked,
BlockValidationState state,
const CBlockIndex **  ppindex = nullptr 
)

Process incoming block headers.

May not be called in a validationinterface callback.

Parameters
[in]headersThe block headers themselves
[in]min_pow_checkedTrue if proof-of-work anti-DoS checks have been done by caller for headers chain
[out]stateThis may be set to an Error state if any error occurred processing them
[out]ppindexIf set, the pointer will be set to point to the last new block index object for the given headers
Returns
false if AcceptBlockHeader fails on any of the headers, true otherwise (including if headers were already known)

Definition at line 4325 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProcessTransaction()

MempoolAcceptResult ChainstateManager::ProcessTransaction ( const CTransactionRef tx,
bool  test_accept = false 
)

Try to add a transaction to the memory pool.

Parameters
[in]txThe transaction to submit for mempool acceptance.
[in]test_acceptWhen true, run validation checks but don't submit to mempool.

Definition at line 4531 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ReceivedBlockTransactions()

void ChainstateManager::ReceivedBlockTransactions ( const CBlock block,
CBlockIndex pindexNew,
const FlatFilePos pos 
)

Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS).

Definition at line 3844 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ RemoveChainstate()

std::unique_ptr< Chainstate > ChainstateManager::RemoveChainstate ( Chainstate chainstate)
inline

Remove a chainstate.

Definition at line 1138 of file validation.h.

◆ ReportHeadersPresync()

void ChainstateManager::ReportHeadersPresync ( const arith_uint256 work,
int64_t  height,
int64_t  timestamp 
)

This is used by net_processing to report pre-synchronization progress of headers, as headers are not yet fed to validation during that time, but validation is (for now) responsible for logging and signalling through NotifyHeaderTip, so it needs this information.

Definition at line 4355 of file validation.cpp.

Here is the call graph for this function:

◆ ResetBlockSequenceCounters()

void ChainstateManager::ResetBlockSequenceCounters ( )
inline

Definition at line 1056 of file validation.h.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ShouldCheckBlockIndex()

bool ChainstateManager::ShouldCheckBlockIndex ( ) const

Definition at line 5205 of file validation.cpp.

Here is the caller graph for this function:

◆ UpdateUncommittedBlockStructures()

void ChainstateManager::UpdateUncommittedBlockStructures ( CBlock block,
const CBlockIndex pindexPrev 
) const

Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.

Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks as long as they honor default_witness_commitment from the template.

Definition at line 4064 of file validation.cpp.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ValidatedChainstate()

Chainstate & ChainstateManager::ValidatedChainstate ( ) const
inline

Return fully validated chainstate that should be used for indexing, to support indexes that need to index blocks in order and can't start from the snapshot block.

Definition at line 1129 of file validation.h.

Here is the caller graph for this function:

Member Data Documentation

◆ ActivateSnapshot

util::Result< CBlockIndex * > ChainstateManager::ActivateSnapshot

Instantiate a new chainstate.

Parameters
[in]mempoolThe mempool to pass to the chainstate Construct and activate a Chainstate on the basis of UTXO snapshot data.

Steps:

  • Initialize an unused Chainstate.
  • Load its CoinsViews contents from coins_file.
  • Verify that the hash of the resulting coinsdb matches the expected hash per assumeutxo chain parameters.
  • Wait for our headers chain to include the base block of the snapshot.
  • "Fast forward" the tip of the new chainstate to the base of the snapshot.
  • Construct the new Chainstate and add it to m_chainstates.

Definition at line 1095 of file validation.h.

◆ Chainstate

friend ChainstateManager::Chainstate
private

Definition at line 962 of file validation.h.

◆ CurrentChainstate

SnapshotCompletionResult MaybeValidateSnapshot(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ChainstateManager::CurrentChainstate() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
inline

Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the snapshot block.

When the target block is reached, the UTXO hash is computed and saved to validated_cs.m_target_utxohash, and unvalidated_cs.m_assumeutxo will be updated from UNVALIDATED to either VALIDATED or INVALID depending on whether the hash matches. The INVALID case should not happen in practice because the software should refuse to load unrecognized snapshots, but if it does happen, it is a fatal error. Return current chainstate targeting the most-work, network tip.

Definition at line 1109 of file validation.h.

◆ GetCheckQueue

Chainstate *LoadAssumeutxoChainstate() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &AddChainstate(std::unique_ptr< Chainstate > chainstate) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(bool DeleteChainstate(Chainstate &chainstate) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup(Chainstate &validated_cs, Chainstate &unvalidated_cs) EXCLUSIVE_LOCKS_REQUIRED(std::optional< std::pair< const CBlockIndex *, const CBlockIndex * > > GetHistoricalBlockRange() const EXCLUSIVE_LOCKS_REQUIRED(util::Result< void > ActivateBestChains() LOCKS_EXCLUDED(void RecalculateBestHeader() EXCLUSIVE_LOCKS_REQUIRED(CCheckQueue< CScriptCheck > & ChainstateManager::GetCheckQueue()
inline

When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process of being validated and load it if found.

Return pointer to the Chainstate if it is loaded. Add new chainstate. Remove the chainstate and all on-disk artifacts. Used when reindex{-chainstate} is called during snapshot use. If we have validated a snapshot chain during this runtime, copy its chainstate directory over to the main chainstate location, completing validation of the snapshot.

If the cleanup succeeds, the caller will need to ensure chainstates are reinitialized, since ResetChainstates() will be called before leveldb directories are moved or deleted.

See also
node/chainstate:LoadChainstate() Get range of historical blocks to download. Call ActivateBestChain() on every chainstate. If, due to invalidation / reconsideration of blocks, the previous best header is no longer valid / guaranteed to be the most-work header in our block-index not known to be invalid, recalculate it.

Definition at line 1339 of file validation.h.

◆ m_blockman

node::BlockManager ChainstateManager::m_blockman

A single BlockManager instance is shared across each constructed chainstate to avoid duplicating block metadata.

Definition at line 1028 of file validation.h.

◆ m_cached_finished_ibd

std::atomic<bool> ChainstateManager::m_cached_finished_ibd {false}
mutable

Whether initial block download has ended and IsInitialBlockDownload should return false from now on.

Mutable because we need to be able to mark IsInitialBlockDownload() const, which latches this for caching purposes.

Definition at line 1039 of file validation.h.

◆ m_interrupt

const util::SignalInterrupt& ChainstateManager::m_interrupt

Definition at line 1024 of file validation.h.

◆ m_options

const Options ChainstateManager::m_options

Definition at line 1025 of file validation.h.

◆ m_script_check_queue

CCheckQueue<CScriptCheck> ChainstateManager::m_script_check_queue
private

A queue for script verifications that have to be performed by worker threads.

Definition at line 968 of file validation.h.

◆ m_total_coinsdb_cache

size_t ChainstateManager::m_total_coinsdb_cache {0}

The total number of bytes available for us to use across all leveldb coins databases.

This will be split somehow across chainstates.

Definition at line 1076 of file validation.h.

◆ m_total_coinstip_cache

size_t ChainstateManager::m_total_coinstip_cache {0}

The total number of bytes available for us to use across all in-memory coins caches.

This will be split somehow across chainstates.

Definition at line 1072 of file validation.h.

◆ m_validation_cache

ValidationCache ChainstateManager::m_validation_cache

Definition at line 1030 of file validation.h.

◆ m_versionbitscache

VersionBitsCache ChainstateManager::m_versionbitscache
mutable

Track versionbit status.

Definition at line 1169 of file validation.h.

◆ nBlockReverseSequenceId

int32_t ChainstateManager::nBlockReverseSequenceId = -1

Decreasing counter (used by subsequent preciousblock calls).

Definition at line 1050 of file validation.h.

◆ nLastPreciousChainwork

arith_uint256 ChainstateManager::nLastPreciousChainwork = 0

chainwork for the last block that preciousblock has been applied to.

Definition at line 1052 of file validation.h.

◆ snapshot_download_completed

std::function<void()> ChainstateManager::snapshot_download_completed = std::function<void()>()

Function to restart active indexes; set dynamically to avoid a circular dependency on base/index.cpp.

Definition at line 995 of file validation.h.


The documentation for this class was generated from the following files: