Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
Public Types | Public Member Functions | Public Attributes | Private Member Functions | Private Attributes | List of all members
ChainstateManager Class Reference

Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate generated by downloading blocks, and an optional snapshot chainstate loaded from a UTXO snapshot. More...

#include <validation.h>

Collaboration diagram for ChainstateManager:
[legend]

Public Types

using Options = kernel::ChainstateManagerOpts
 

Public Member Functions

 ChainstateManager (Options options, node::BlockManager::Options blockman_options)
 
const ConfigGetConfig () const
 
const CChainParamsGetParams () const
 
const Consensus::ParamsGetConsensus () const
 
bool ShouldCheckBlockIndex () const
 
const arith_uint256MinimumChainWork () const
 
const BlockHashAssumedValidBlock () const
 
kernel::NotificationsGetNotifications () const
 
RecursiveMutexGetMutex () const LOCK_RETURNED(
 Alias for cs_main.
 
CBlockIndex *m_best_header GUARDED_BY (::cs_main)
 Best header we've seen so far (used for getheaders queries' starting points).
 
bool ActivateSnapshot (AutoFile &coins_file, const node::SnapshotMetadata &metadata, bool in_memory)
 Construct and activate a Chainstate on the basis of UTXO snapshot data.
 
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(ChainstateActiveChainstate () const
 Once the background validation chainstate has reached the height which is the base of the UTXO snapshot in use, compare its coins to ensure they match those expected by the snapshot.
 
CChainActiveChain () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 
int ActiveHeight () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 
CBlockIndexActiveTip () const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 
node::BlockMapBlockIndex () EXCLUSIVE_LOCKS_REQUIRED(
 
bool IsSnapshotActive () const
 
std::optional< BlockHashSnapshotBlockhash () const
 
bool IsSnapshotValidated () const EXCLUSIVE_LOCKS_REQUIRED(
 Is there a snapshot in use and has it been fully validated?
 
bool ProcessNewBlock (const std::shared_ptr< const CBlock > &block, bool force_processing, bool min_pow_checked, bool *new_block, avalanche::Processor *const avalanche=nullptr) LOCKS_EXCLUDED(cs_main)
 Process an incoming block.
 
bool ProcessNewBlockHeaders (const std::vector< CBlockHeader > &block, bool min_pow_checked, BlockValidationState &state, const CBlockIndex **ppindex=nullptr, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) LOCKS_EXCLUDED(cs_main)
 Process incoming block headers.
 
MempoolAcceptResult ProcessTransaction (const CTransactionRef &tx, bool test_accept=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Try to add a transaction to the memory pool.
 
bool LoadBlockIndex () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Load the block tree and coins database from disk, initializing state if we're running with -reindex.
 
void MaybeRebalanceCaches() EXCLUSIVE_LOCKS_REQUIRED(void ReportHeadersPresync (const arith_uint256 &work, int64_t height, int64_t timestamp)
 Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
 
bool LoadRecentHeadersTime (const fs::path &filePath) EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 Load the recent block headers reception time from a file.
 

Public Attributes

const Options m_options
 
std::thread m_load_block
 
node::BlockManager m_blockman
 A single BlockManager instance is shared across each constructed chainstate to avoid duplicating block metadata.
 
std::set< CBlockIndex * > m_failed_blocks
 In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to connect and found to be invalid here (ie which were set to BLOCK_FAILED_VALID since the last restart).
 
int64_t m_total_coinstip_cache {0}
 The total number of bytes available for us to use across all in-memory coins caches.
 
int64_t m_total_coinsdb_cache {0}
 The total number of bytes available for us to use across all leveldb coins databases.
 
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< ChainstateGetAll )()
 Instantiate a new chainstate.
 
bool DetectSnapshotChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(void ResetChainstates() EXCLUSIVE_LOCKS_REQUIRED(Chainstate &ActivateExistingSnapshot(CTxMemPool *mempool, BlockHash base_blockhash) EXCLUSIVE_LOCKS_REQUIRED(bool ValidatedSnapshotCleanup() EXCLUSIVE_LOCKS_REQUIRED(boo DumpRecentHeadersTime )(const fs::path &filePath) const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
 When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process of being validated.
 

Private Member Functions

std::unique_ptr< Chainstate > m_ibd_chainstate GUARDED_BY (::cs_main)
 The chainstate used under normal operation (i.e.
 
std::unique_ptr< Chainstate > m_snapshot_chainstate GUARDED_BY (::cs_main)
 A chainstate initialized on the basis of a UTXO snapshot.
 
Chainstate *m_active_chainstate GUARDED_BY (::cs_main)
 Points to either the ibd or snapshot chainstate; indicates our most-work chain.
 
CBlockIndex *m_best_invalid GUARDED_BY (::cs_main)
 
CBlockIndex *m_best_parked GUARDED_BY (::cs_main)
 
bool PopulateAndValidateSnapshot (Chainstate &snapshot_chainstate, AutoFile &coins_file, const node::SnapshotMetadata &metadata)
 Internal helper for ActivateSnapshot().
 
bool AcceptBlockHeader (const CBlockHeader &block, BlockValidationState &state, CBlockIndex **ppindex, bool min_pow_checked, const std::optional< CCheckpointData > &test_checkpoints=std::nullopt) 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.
 
const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(std::optional< int > GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(bool IsUsable (const Chainstate *const pchainstate) const EXCLUSIVE_LOCKS_REQUIRED(
 Returns nullptr if no snapshot has been loaded.
 
SteadyMilliseconds m_last_presync_update GUARDED_BY (::cs_main)
 Most recent headers presync progress update, for rate-limiting.
 

Private Attributes

friend Chainstate
 

Detailed Description

Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate generated by downloading blocks, and an optional snapshot chainstate loaded from a UTXO snapshot.

Managed chainstates can be maintained at different heights simultaneously.

This class provides abstractions that allow the retrieval of the current most-work chainstate ("Active") as well as chainstates which may be in background use to validate UTXO snapshots.

Definitions:

IBD chainstate: a chainstate whose current state has been "fully" validated by the initial block download process.

Snapshot chainstate: a chainstate populated by loading in an assumeutxo UTXO snapshot.

Active chainstate: the chainstate containing the current most-work chain. Consulted by most parts of the system (net_processing, wallet) as a reflection of the current chain and UTXO set. This may either be an IBD chainstate or a snapshot chainstate.

Background IBD chainstate: an IBD chainstate for which the IBD process is happening in the background while use of the active (snapshot) chainstate allows the rest of the system to function.

Definition at line 1219 of file validation.h.

Member Typedef Documentation

◆ Options

Definition at line 1306 of file validation.h.

Constructor & Destructor Documentation

◆ ChainstateManager()

ChainstateManager::ChainstateManager ( Options  options,
node::BlockManager::Options  blockman_options 
)
explicit

Definition at line 6938 of file validation.cpp.

Member Function Documentation

◆ AcceptBlockHeader()

bool ChainstateManager::AcceptBlockHeader ( const CBlockHeader block,
BlockValidationState state,
CBlockIndex **  ppindex,
bool  min_pow_checked,
const std::optional< CCheckpointData > &  test_checkpoints = std::nullopt 
)
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.

If the provided block header is valid, add it to the 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).

Returns true if the block is successfully added to the block index.

Definition at line 4472 of file validation.cpp.

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

◆ ActivateSnapshot()

bool ChainstateManager::ActivateSnapshot ( AutoFile coins_file,
const node::SnapshotMetadata metadata,
bool  in_memory 
)

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, faking nTx* block index data along the way.
  • Move the new chainstate to m_snapshot_chainstate and make it our ActiveChainstate().

Definition at line 6355 of file validation.cpp.

Here is the call graph for this function:

◆ ActiveChain()

CChain & ChainstateManager::ActiveChain ( ) const
inline

Definition at line 1429 of file validation.h.

Here is the caller graph for this function:

◆ ActiveChainstate()

Chainstate & ChainstateManager::ActiveChainstate ( ) const

Once the background validation chainstate has reached the height which is the base of the UTXO snapshot in use, compare its coins to ensure they match those expected by the snapshot.

If the coins match (expected), then mark the validation chainstate for deletion and continue using the snapshot chainstate as active. Otherwise, revert to using the ibd chainstate and shutdown. The most-work chain.

Definition at line 6859 of file validation.cpp.

Here is the call graph for this function:

◆ ActiveHeight()

int ChainstateManager::ActiveHeight ( ) const
inline

Definition at line 1432 of file validation.h.

Here is the caller graph for this function:

◆ ActiveTip()

CBlockIndex * ChainstateManager::ActiveTip ( ) const
inline

Definition at line 1435 of file validation.h.

Here is the caller graph for this function:

◆ AssumedValidBlock()

const BlockHash & ChainstateManager::AssumedValidBlock ( ) const
inline

Definition at line 1325 of file validation.h.

Here is the caller graph for this function:

◆ BlockIndex()

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

Definition at line 1439 of file validation.h.

Here is the caller graph for this function:

◆ GetConfig()

const Config & ChainstateManager::GetConfig ( ) const
inline

Definition at line 1311 of file validation.h.

Here is the caller graph for this function:

◆ GetConsensus()

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

Definition at line 1316 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 1343 of file validation.h.

Here is the caller graph for this function:

◆ GetNotifications()

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

Definition at line 1328 of file validation.h.

Here is the caller graph for this function:

◆ GetParams()

const CChainParams & ChainstateManager::GetParams ( ) const
inline

Definition at line 1313 of file validation.h.

Here is the caller graph for this function:

◆ GUARDED_BY() [1/7]

std::unique_ptr< Chainstate > m_ibd_chainstate ChainstateManager::GUARDED_BY ( ::cs_main  )
private

The chainstate used under normal operation (i.e.

"regular" IBD) or, if a snapshot is in use, for background validation.

Its contents (including on-disk data) will be deleted upon shutdown after background validation of the snapshot has completed. We do not free the chainstate contents immediately after it finishes validation to cautiously avoid a case where some other part of the system is still using this pointer (e.g. net_processing).

Once this pointer is set to a corresponding chainstate, it will not be reset until init.cpp:Shutdown().

This is especially important when, e.g., calling ActivateBestChain() on all chainstates because we are not able to hold cs_main going into that call.

◆ GUARDED_BY() [2/7]

std::unique_ptr< Chainstate > m_snapshot_chainstate ChainstateManager::GUARDED_BY ( ::cs_main  )
private

A chainstate initialized on the basis of a UTXO snapshot.

If this is non-null, it is always our active chainstate.

Once this pointer is set to a corresponding chainstate, it will not be reset until init.cpp:Shutdown().

This is especially important when, e.g., calling ActivateBestChain() on all chainstates because we are not able to hold cs_main going into that call.

◆ GUARDED_BY() [3/7]

Chainstate *m_active_chainstate ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Points to either the ibd or snapshot chainstate; indicates our most-work chain.

Once this pointer is set to a corresponding chainstate, it will not be reset until init.cpp:Shutdown().

This is especially important when, e.g., calling ActivateBestChain() on all chainstates because we are not able to hold cs_main going into that call.

Definition at line 1258 of file validation.h.

◆ GUARDED_BY() [4/7]

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

Definition at line 1260 of file validation.h.

◆ GUARDED_BY() [5/7]

CBlockIndex *m_best_parked ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

Definition at line 1261 of file validation.h.

◆ GUARDED_BY() [6/7]

SteadyMilliseconds m_last_presync_update ChainstateManager::GUARDED_BY ( ::cs_main  )
inlineprivate

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

Definition at line 1303 of file validation.h.

◆ GUARDED_BY() [7/7]

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

Best header we've seen so far (used for getheaders queries' starting points).

Definition at line 1378 of file validation.h.

◆ IsSnapshotActive()

bool ChainstateManager::IsSnapshotActive ( ) const
Returns
true if a snapshot-based chainstate is in use. Also implies that a background validation chainstate is also in use.

Definition at line 6865 of file validation.cpp.

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

◆ IsSnapshotValidated()

bool ChainstateManager::IsSnapshotValidated ( ) const
inline

Is there a snapshot in use and has it been fully validated?

Definition at line 1451 of file validation.h.

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

◆ IsUsable()

const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(std::optional< int > GetSnapshotBaseHeight() const EXCLUSIVE_LOCKS_REQUIRED(bool ChainstateManager::IsUsable ( const Chainstate *const  pchainstate) const
inlineprivate

Returns nullptr if no snapshot has been loaded.

Return the height of the base block of the snapshot in use, if one exists, else nullopt. Return true if a chainstate is considered usable.

This is false when a background validation chainstate has completed its validation of an assumed-valid chainstate, or when a snapshot chainstate has been found to be invalid.

Definition at line 1297 of file validation.h.

Here is the call 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 5492 of file validation.cpp.

Here is the call graph for this function:

◆ LoadRecentHeadersTime()

bool ChainstateManager::LoadRecentHeadersTime ( const fs::path filePath)

Load the recent block headers reception time from a file.

Definition at line 5440 of file validation.cpp.

Here is the call graph for this function:

◆ MinimumChainWork()

const arith_uint256 & ChainstateManager::MinimumChainWork ( ) const
inline

Definition at line 1322 of file validation.h.

Here is the caller graph for this function:

◆ PopulateAndValidateSnapshot()

bool ChainstateManager::PopulateAndValidateSnapshot ( Chainstate snapshot_chainstate,
AutoFile coins_file,
const node::SnapshotMetadata metadata 
)
private

Internal helper for ActivateSnapshot().

Definition at line 6496 of file validation.cpp.

Here is the call graph for this function:
Here is the caller 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,
avalanche::Processor *const  avalanche = nullptr 
)

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 4866 of file validation.cpp.

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

◆ ProcessNewBlockHeaders()

bool ChainstateManager::ProcessNewBlockHeaders ( const std::vector< CBlockHeader > &  block,
bool  min_pow_checked,
BlockValidationState state,
const CBlockIndex **  ppindex = nullptr,
const std::optional< CCheckpointData > &  test_checkpoints = std::nullopt 
)

Process incoming block headers.

May not be called in a validationinterface callback.

Parameters
[in]blockThe 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
True if block headers were accepted as valid.

Definition at line 4619 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 4922 of file validation.cpp.

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

◆ ReportHeadersPresync()

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

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

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 4659 of file validation.cpp.

Here is the call graph for this function:

◆ ShouldCheckBlockIndex()

bool ChainstateManager::ShouldCheckBlockIndex ( ) const
inline

Definition at line 1319 of file validation.h.

Here is the caller graph for this function:

◆ SnapshotBlockhash()

std::optional< BlockHash > ChainstateManager::SnapshotBlockhash ( ) const

Definition at line 6269 of file validation.cpp.

Here is the caller graph for this function:

Member Data Documentation

◆ Chainstate

friend ChainstateManager::Chainstate
private

Definition at line 1281 of file validation.h.

◆ DumpRecentHeadersTime

bool ChainstateManager::DumpRecentHeadersTime

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

Switch the active chainstate to one based on a UTXO snapshot that was loaded previously. 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() Dump the recent block headers reception time to a file.

Definition at line 1564 of file validation.h.

◆ GetAll

std::vector< Chainstate * > ChainstateManager::GetAll

Instantiate a new chainstate.

Parameters
[in]mempoolThe mempool to pass to the chainstate Get all chainstates currently being used.

Definition at line 1396 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 1351 of file validation.h.

◆ m_failed_blocks

std::set<CBlockIndex *> ChainstateManager::m_failed_blocks

In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to connect and found to be invalid here (ie which were set to BLOCK_FAILED_VALID since the last restart).

We can then walk this set and check if a new header is a descendant of something in this set, preventing us from having to walk m_block_index when we try to connect a bad block and fail.

While this is more complicated than marking everything which descends from an invalid block as invalid at the time we discover it to be invalid, doing so would require walking all of m_block_index to find all descendants. Since this case should be very rare, keeping track of all BLOCK_FAILED_VALID blocks in a set should be just fine and work just as well.

Because we already walk m_block_index in height-order at startup, we go ahead and mark descendants of invalid blocks as FAILED_CHILD at that time, instead of putting things in this set.

Definition at line 1372 of file validation.h.

◆ m_load_block

std::thread ChainstateManager::m_load_block

Definition at line 1348 of file validation.h.

◆ m_options

const Options ChainstateManager::m_options

Definition at line 1347 of file validation.h.

◆ m_total_coinsdb_cache

int64_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 1386 of file validation.h.

◆ m_total_coinstip_cache

int64_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 1382 of file validation.h.


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