Bitcoin Core  23.99.0
P2P Digital Currency
Public Member Functions | Public Attributes | Protected Member Functions | Protected Attributes | Private Member Functions | Private Attributes | List of all members
CChainState Class Reference

CChainState stores and provides an API to update our local knowledge of the current best chain. More...

#include <validation.h>

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

Public Member Functions

 CChainState (CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< uint256 > from_snapshot_blockhash=std::nullopt)
 
void InitCoinsDB (size_t cache_size_bytes, bool in_memory, bool should_wipe, fs::path leveldb_name="chainstate")
 Initialize the CoinsViews UTXO set database management data structures. More...
 
bool reliesOnAssumedValid ()
 Return true if this chainstate relies on blocks that are assumed-valid. More...
 
CCoinsViewCacheCoinsTip () EXCLUSIVE_LOCKS_REQUIRED(
 
CCoinsViewDBCoinsDB () EXCLUSIVE_LOCKS_REQUIRED(
 
CTxMemPoolGetMempool ()
 
CCoinsViewErrorCatcherCoinsErrorCatcher () EXCLUSIVE_LOCKS_REQUIRED(
 
void ResetCoinsViews ()
 Destructs all objects related to accessing the UTXO set. More...
 
bool FlushStateToDisk (BlockValidationState &state, FlushStateMode mode, int nManualPruneHeight=0)
 Update the on-disk chain state. More...
 
void ForceFlushStateToDisk ()
 Unconditionally flush all changes to disk. More...
 
void PruneAndFlush ()
 Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned. More...
 
bool DisconnectTip (BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
 Disconnect m_chain's tip. More...
 
bool ReplayBlocks ()
 Replay blocks that aren't fully applied to the database. More...
 
bool NeedsRedownload () const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Whether the chain state needs to be redownloaded due to lack of witness data. More...
 
bool LoadGenesisBlock ()
 Ensures we have a genesis block in the block tree, possibly writing one to disk. More...
 
void PruneBlockIndexCandidates ()
 Delete all entries in setBlockIndexCandidates that are worse than the current tip. More...
 
const CBlockIndexFindForkInGlobalIndex (const CBlockLocator &locator) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Find the last common block of this chain and a locator. More...
 
void CheckBlockIndex ()
 Make various assertions about the state of the block index. More...
 
void LoadMempool (const fs::path &load_path, fsbridge::FopenFn mockable_fopen_function=fsbridge::fopen)
 Load the persisted mempool from disk. More...
 
bool LoadChainTip () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Update the chain tip based on database information, i.e. More...
 

Public Attributes

node::BlockManagerm_blockman
 Reference to a BlockManager instance which itself is shared across all CChainState instances. More...
 
const CChainParamsm_params
 Chain parameters for this chainstate. More...
 
ChainstateManagerm_chainman
 The chainstate manager that owns this chainstate. More...
 
CChain m_chain
 The current chain of blockheaders we consult and build on. More...
 
const std::optional< uint256m_from_snapshot_blockhash
 The blockhash which is the base of the snapshot this chainstate was created from. More...
 
std::set< CBlockIndex *, node::CBlockIndexWorkComparatorsetBlockIndexCandidates
 The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) or BLOCK_ASSUMED_VALID (if using background chainstates) and as good as our current tip or better. More...
 
size_t m_coinsdb_cache_size_bytes {0}
 The cache size of the on-disk coins view. More...
 
size_t m_coinstip_cache_size_bytes {0}
 The cache size of the in-memory coins view. More...
 
bool ActivateBestChain(BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr) LOCKS_EXCLUDED(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)
 Find the best known block, and make it the tip of the block chain. More...
 
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock )(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool fJustCheck=false) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Apply the effects of this block (with given index) on the UTXO set represented by coins. More...
 
bool m_mempool cs
 
bool PreciousBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(bool InvalidateBlock(BlockValidationState &state, CBlockIndex *pindex) LOCKS_EXCLUDED(voi ResetBlockFailureFlags )(CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Mark a block as precious and reorganize. More...
 

Protected Member Functions

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...
 

Protected Attributes

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...
 
Mutex m_chainstate_mutex
 The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestChain() and InvalidateBlock() More...
 
std::atomic< bool > m_cached_finished_ibd {false}
 Whether this chainstate is undergoing initial block download. More...
 
CTxMemPoolm_mempool
 Optional mempool that is kept in sync with the chain. More...
 
std::unique_ptr< CoinsViewsm_coins_views
 Manages the UTXO set, which is a reflection of the contents of m_chain. More...
 

Private Member Functions

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. More...
 
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. More...
 
void InvalidBlockFound (CBlockIndex *pindex, const BlockValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
CBlockIndexFindMostWorkChain () 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 far from certain to be valid). 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...
 
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. More...
 
void CheckForkWarningConditions () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
void InvalidChainFound (CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
RecursiveMutexMempoolMutex () const LOCK_RETURNED(m_mempool -> cs)
 Indirection necessary to make lock annotations work with an optional mempool. More...
 
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 transactions from the mempool, and also removing any other transactions from the mempool that are no longer valid given the new tip/height. More...
 

Private Attributes

void m_mempool cs
 
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(frien ChainstateManager )
 Check warning conditions and do some notifications on new chain tip set. More...
 

Detailed Description

CChainState stores and provides an API to update our local knowledge of the current best chain.

Eventually, the API here is targeted at being exposed externally as a consumable libconsensus library, so any functions added must only call other class member functions, pure functions in other parts of the consensus library, callbacks via the validation interface, or read/write-to-disk functions (eventually this will also be via callbacks).

Anything that is contingent on the current tip of the chain is stored here, whereas block information and metadata independent of the current tip is kept in BlockManager.

Definition at line 431 of file validation.h.

Constructor & Destructor Documentation

◆ CChainState()

CChainState::CChainState ( CTxMemPool mempool,
node::BlockManager blockman,
ChainstateManager chainman,
std::optional< uint256 from_snapshot_blockhash = std::nullopt 
)
explicit

Definition at line 1501 of file validation.cpp.

Member Function Documentation

◆ ActivateBestChainStep()

bool CChainState::ActivateBestChainStep ( BlockValidationState state,
CBlockIndex pindexMostWork,
const std::shared_ptr< const CBlock > &  pblock,
bool &  fInvalidFound,
ConnectTrace connectTrace 
)
private

Dictates whether we need to flush the cache to disk or not.

Try to make some progress towards making pindexMostWork the active block.

Returns
the state of the size of the coins cache.

pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.

Returns
true unless a system error occurred

Definition at line 2839 of file validation.cpp.

Here is the call graph for this function:

◆ CheckBlockIndex()

void CChainState::CheckBlockIndex ( )

Make various assertions about the state of the block index.

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

Definition at line 4393 of file validation.cpp.

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

◆ CheckForkWarningConditions()

void CChainState::CheckForkWarningConditions ( )
private

Definition at line 1581 of file validation.cpp.

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

◆ CoinsDB()

CCoinsViewDB& CChainState::CoinsDB ( )
inline
Returns
A reference to the on-disk UTXO set database.

Definition at line 543 of file validation.h.

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

◆ CoinsErrorCatcher()

CCoinsViewErrorCatcher& CChainState::CoinsErrorCatcher ( )
inline
Returns
A reference to a wrapped view of the in-memory UTXO set that handles disk read errors gracefully.

Definition at line 557 of file validation.h.

Here is the call graph for this function:

◆ CoinsTip()

CCoinsViewCache& CChainState::CoinsTip ( )
inline
Returns
A reference to the in-memory cache of the UTXO set.

Definition at line 535 of file validation.h.

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

◆ ConnectTip()

bool CChainState::ConnectTip ( BlockValidationState state,
CBlockIndex pindexNew,
const std::shared_ptr< const CBlock > &  pblock,
ConnectTrace connectTrace,
DisconnectedBlockTransactions disconnectpool 
)
private

Connect a new block to m_chain.

pblock is either nullptr or a pointer to a CBlock corresponding to pindexNew, to bypass loading it again from disk.

The block is added to connectTrace if connection succeeds.

Definition at line 2695 of file validation.cpp.

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

◆ DisconnectTip()

bool CChainState::DisconnectTip ( BlockValidationState state,
DisconnectedBlockTransactions disconnectpool 
)

Disconnect m_chain's tip.

After calling, the mempool will be in an inconsistent state, with transactions from disconnected blocks being added to disconnectpool. You should make the mempool consistent again by calling MaybeUpdateMempoolForReorg. with cs_main held.

If disconnectpool is nullptr, then no disconnected transactions are added to disconnectpool (note that the caller is responsible for mempool consistency in any case).

Definition at line 2579 of file validation.cpp.

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

◆ FindForkInGlobalIndex()

const CBlockIndex * CChainState::FindForkInGlobalIndex ( const CBlockLocator locator) const

Find the last common block of this chain and a locator.

Definition at line 134 of file validation.cpp.

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

◆ FindMostWorkChain()

CBlockIndex * CChainState::FindMostWorkChain ( )
private

Return the tip of the chain with the most work in it, that isn't known to be invalid (it's however far from certain to be valid).

Definition at line 2763 of file validation.cpp.

Here is the call graph for this function:

◆ FlushStateToDisk()

bool CChainState::FlushStateToDisk ( BlockValidationState state,
FlushStateMode  mode,
int  nManualPruneHeight = 0 
)

Update the on-disk chain state.

The caches and indexes are flushed depending on the mode we're called with if they're too large, if it's been a while since the last write, or always and in all cases if we're in prune mode and are deleting files.

If FlushStateMode::NONE is used, then FlushStateToDisk(...) won't do anything besides checking if we need to prune.

Returns
true unless a system error occurred

Definition at line 2325 of file validation.cpp.

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

◆ ForceFlushStateToDisk()

void CChainState::ForceFlushStateToDisk ( )

Unconditionally flush all changes to disk.

Definition at line 2468 of file validation.cpp.

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

◆ GetMempool()

CTxMemPool* CChainState::GetMempool ( )
inline
Returns
A pointer to the mempool.

Definition at line 550 of file validation.h.

Here is the caller graph for this function:

◆ GUARDED_BY()

int32_t nBlockSequenceId CChainState::GUARDED_BY ( ::cs_main  )
protected

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 0, so start the counter at 1.

◆ InitCoinsDB()

void CChainState::InitCoinsDB ( size_t  cache_size_bytes,
bool  in_memory,
bool  should_wipe,
fs::path  leveldb_name = "chainstate" 
)

Initialize the CoinsViews UTXO set database management data structures.

The in-memory cache is initialized separately.

All parameters forwarded to CoinsViews.

Definition at line 1512 of file validation.cpp.

Here is the caller graph for this function:

◆ InvalidBlockFound()

void CChainState::InvalidBlockFound ( CBlockIndex pindex,
const BlockValidationState state 
)
private

Definition at line 1623 of file validation.cpp.

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

◆ InvalidChainFound()

void CChainState::InvalidChainFound ( CBlockIndex pindexNew)
private

Definition at line 1600 of file validation.cpp.

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

◆ LoadChainTip()

bool CChainState::LoadChainTip ( )

Update the chain tip based on database information, i.e.

CoinsTip()'s best block.

Definition at line 3880 of file validation.cpp.

Here is the call graph for this function:

◆ LoadGenesisBlock()

bool CChainState::LoadGenesisBlock ( )

Ensures we have a genesis block in the block tree, possibly writing one to disk.

Definition at line 4240 of file validation.cpp.

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

◆ LoadMempool()

void CChainState::LoadMempool ( const fs::path load_path,
fsbridge::FopenFn  mockable_fopen_function = fsbridge::fopen 
)

Load the persisted mempool from disk.

Definition at line 3873 of file validation.cpp.

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

◆ MaybeUpdateMempoolForReorg()

void CChainState::MaybeUpdateMempoolForReorg ( DisconnectedBlockTransactions disconnectpool,
bool  fAddToMempool 
)
private

Make mempool consistent after a reorg, by re-adding or recursively erasing disconnected block transactions from the mempool, and also removing any other transactions from the mempool that are no longer valid given the new tip/height.

Note: we assume that disconnectpool only contains transactions that are NOT confirmed in the current chain nor already in the mempool (otherwise, in-mempool descendants of such transactions would be removed).

Passing fAddToMempool=false will skip trying to add the transactions back, and instead just erase from the mempool as needed.

Definition at line 290 of file validation.cpp.

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

◆ MempoolMutex()

RecursiveMutex* CChainState::MempoolMutex ( ) const -> cs)
inlineprivate

Indirection necessary to make lock annotations work with an optional mempool.

Definition at line 737 of file validation.h.

◆ NeedsRedownload()

bool CChainState::NeedsRedownload ( ) const

Whether the chain state needs to be redownloaded due to lack of witness data.

Definition at line 4124 of file validation.cpp.

Here is the call graph for this function:

◆ PruneAndFlush()

void CChainState::PruneAndFlush ( )

Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned.

Definition at line 2476 of file validation.cpp.

Here is the call graph for this function:

◆ PruneBlockIndexCandidates()

void CChainState::PruneBlockIndexCandidates ( )

Delete all entries in setBlockIndexCandidates that are worse than the current tip.

Definition at line 2822 of file validation.cpp.

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

◆ ReceivedBlockTransactions()

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

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

Definition at line 3270 of file validation.cpp.

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

◆ reliesOnAssumedValid()

bool CChainState::reliesOnAssumedValid ( )
inline

Return true if this chainstate relies on blocks that are assumed-valid.

In practice this means it was created based on a UTXO snapshot.

Definition at line 524 of file validation.h.

Here is the caller graph for this function:

◆ ReplayBlocks()

bool CChainState::ReplayBlocks ( )

Replay blocks that aren't fully applied to the database.

Definition at line 4056 of file validation.cpp.

Here is the call graph for this function:

◆ ResetCoinsViews()

void CChainState::ResetCoinsViews ( )
inline

Destructs all objects related to accessing the UTXO set.

Definition at line 564 of file validation.h.

◆ RollforwardBlock()

bool CChainState::RollforwardBlock ( const CBlockIndex pindex,
CCoinsViewCache inputs 
)
private

Apply the effects of a block on the utxo cache, ignoring that it may already have been applied.

Definition at line 4035 of file validation.cpp.

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

Member Data Documentation

◆ AcceptBlock

bool CChainState::AcceptBlock

Find the best known block, and make it the tip of the block chain.

Store block on disk.

The result is either failure or an activated best chain. pblock is either nullptr or a pointer to a block that is already loaded (to avoid loading it again from disk).

ActivateBestChain is split into steps (see ActivateBestChainStep) so that we avoid holding cs_main for an extended period of time; the length of this call may be quite long during reindexing or a substantial reorg.

May not be called with cs_main held. May not be called in a validationinterface callback.

Returns
true unless a system error occurred

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

Definition at line 653 of file validation.h.

◆ ChainstateManager

void UpdateTip (const CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED( frien CChainState::ChainstateManager)
private

Check warning conditions and do some notifications on new chain tip set.

Definition at line 760 of file validation.h.

◆ ConnectBlock

bool CChainState::ConnectBlock

Apply the effects of this block (with given index) on the UTXO set represented by coins.

Validity checks that depend on the UTXO set are also done; ConnectBlock() can fail if those validity checks fail (among other reasons).

Definition at line 658 of file validation.h.

◆ cs [1/2]

bool m_mempool CChainState::cs

Definition at line 662 of file validation.h.

◆ cs [2/2]

void m_mempool CChainState::cs
private

Definition at line 757 of file validation.h.

◆ m_blockman

node::BlockManager& CChainState::m_blockman

Reference to a BlockManager instance which itself is shared across all CChainState instances.

Definition at line 470 of file validation.h.

◆ m_cached_finished_ibd

std::atomic<bool> CChainState::m_cached_finished_ibd {false}
mutableprotected

Whether this chainstate is undergoing initial block download.

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

Definition at line 458 of file validation.h.

◆ m_chain

CChain CChainState::m_chain

The current chain of blockheaders we consult and build on.

See also
CChain, CBlockIndex.

Definition at line 513 of file validation.h.

◆ m_chainman

ChainstateManager& CChainState::m_chainman

The chainstate manager that owns this chainstate.

The reference is necessary so that this instance can check whether it is the active chainstate within deeply nested method calls.

Definition at line 479 of file validation.h.

◆ m_chainstate_mutex

Mutex CChainState::m_chainstate_mutex
protected

The ChainState Mutex A lock that must be held when modifying this ChainState - held in ActivateBestChain() and InvalidateBlock()

Definition at line 450 of file validation.h.

◆ m_coins_views

std::unique_ptr<CoinsViews> CChainState::m_coins_views
protected

Manages the UTXO set, which is a reflection of the contents of m_chain.

Definition at line 465 of file validation.h.

◆ m_coinsdb_cache_size_bytes

size_t CChainState::m_coinsdb_cache_size_bytes {0}

The cache size of the on-disk coins view.

Definition at line 567 of file validation.h.

◆ m_coinstip_cache_size_bytes

size_t CChainState::m_coinstip_cache_size_bytes {0}

The cache size of the in-memory coins view.

Definition at line 570 of file validation.h.

◆ m_from_snapshot_blockhash

const std::optional<uint256> CChainState::m_from_snapshot_blockhash

The blockhash which is the base of the snapshot this chainstate was created from.

std::nullopt if this chainstate was not created from a snapshot.

Definition at line 520 of file validation.h.

◆ m_mempool

CTxMemPool* CChainState::m_mempool
protected

Optional mempool that is kept in sync with the chain.

Only the active chainstate has a mempool.

Definition at line 462 of file validation.h.

◆ m_params

const CChainParams& CChainState::m_params

Chain parameters for this chainstate.

Definition at line 474 of file validation.h.

◆ nBlockReverseSequenceId

int32_t CChainState::nBlockReverseSequenceId = -1
protected

Decreasing counter (used by subsequent preciousblock calls).

Definition at line 441 of file validation.h.

◆ nLastPreciousChainwork

arith_uint256 CChainState::nLastPreciousChainwork = 0
protected

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

Definition at line 443 of file validation.h.

◆ ResetBlockFailureFlags

void CChainState::ResetBlockFailureFlags

Mark a block as precious and reorganize.

May not be called in a validationinterface callback. Mark a block as invalid. Remove invalidity status from a block and its descendants.

Definition at line 679 of file validation.h.

◆ setBlockIndexCandidates

std::set<CBlockIndex*, node::CBlockIndexWorkComparator> CChainState::setBlockIndexCandidates

The set of all CBlockIndex entries with either BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) or BLOCK_ASSUMED_VALID (if using background chainstates) and as good as our current tip or better.

Entries may be failed, though, and pruning nodes may be missing the data for the block.

Definition at line 532 of file validation.h.


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