Bitcoin ABC 0.30.5
P2P Digital Currency
Public Member Functions | Public Attributes | Protected Member Functions | Protected Attributes | Private Member Functions | Private Attributes | List of all members
Chainstate Class Reference

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

#include <validation.h>

Collaboration diagram for Chainstate:
[legend]

Public Member Functions

 Chainstate (CTxMemPool *mempool, node::BlockManager &blockman, ChainstateManager &chainman, std::optional< BlockHash > from_snapshot_blockhash=std::nullopt)
 
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. More...
 
void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool CanFlushToDisk () const EXCLUSIVE_LOCKS_REQUIRED(
 Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified). 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(cs_main)
 
void ResetCoinsViews ()
 Destructs all objects related to accessing the UTXO set. More...
 
bool HasCoinsViews () const
 Does this chainstate have a UTXO set attached? More...
 
bool ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(void LoadExternalBlockFile (FILE *fileIn, FlatFilePos *dbp=nullptr, std::multimap< BlockHash, FlatFilePos > *blocks_with_unknown_parent=nullptr, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
 Resize the CoinsViews caches dynamically and flush state to disk. 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 ActivateBestChain (BlockValidationState &state, std::shared_ptr< const CBlock > pblock=nullptr, avalanche::Processor *const avalanche=nullptr, bool skip_checkblockindex=false) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
 Find the best known block, and make it the tip of the block chain. More...
 
bool !cs_avalancheFinalizedBlockIndex LOCKS_EXCLUDED (cs_main)
 
bool AcceptBlock (const std::shared_ptr< const CBlock > &pblock, BlockValidationState &state, bool fRequested, const FlatFilePos *dbp, bool *fNewBlock, bool min_pow_checked) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Store a block on disk. More...
 
bool DisconnectTip (BlockValidationState &state, DisconnectedBlockTransactions *disconnectpool) EXCLUSIVE_LOCKS_REQUIRED(cs_main
 Disconnect m_chain's tip. More...
 
bool PreciousBlock (BlockValidationState &state, CBlockIndex *pindex, avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
 Mark a block as precious and reorganize. More...
 
bool !cs_avalancheFinalizedBlockIndex LOCKS_EXCLUDED (cs_main)
 
bool InvalidateBlock (BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
 Mark a block as invalid. More...
 
bool ParkBlock (BlockValidationState &state, CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(!m_chainstate_mutex
 Park a block. More...
 
bool AvalancheFinalizeBlock (CBlockIndex *pindex, avalanche::Processor &avalanche) EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
 Mark a block as finalized by avalanche. More...
 
void ClearAvalancheFinalizedBlock () EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
 Clear avalanche finalization. More...
 
bool IsBlockAvalancheFinalized (const CBlockIndex *pindex) const EXCLUSIVE_LOCKS_REQUIRED(!cs_avalancheFinalizedBlockIndex)
 Checks if a block is finalized by avalanche voting. More...
 
void ResetBlockFailureFlags (CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Remove invalidity status from a block and its descendants. More...
 
template<typename F >
bool UpdateFlagsForBlock (CBlockIndex *pindexBase, CBlockIndex *pindex, F f) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
template<typename F , typename C , typename AC >
void UpdateFlags (CBlockIndex *pindex, CBlockIndex *&pindexReset, F f, C fChild, AC fAncestorWasChanged) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
void UnparkBlockAndChildren (CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Remove parked status from a block and its descendants. More...
 
void UnparkBlock (CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 Remove parked status from a block. More...
 
bool ReplayBlocks ()
 Replay blocks that aren't fully applied to the database. 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...
 
void UnloadBlockIndex () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
bool IsInitialBlockDownload () const
 Check whether we are doing an initial block download (synchronizing from disk or network) 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...
 
CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutexMempoolMutex () const LOCK_RETURNED(m_mempool -> cs)
 Dictates whether we need to flush the cache to disk or not. More...
 

Public Attributes

node::BlockManagerm_blockman
 Reference to a BlockManager instance which itself is shared across all Chainstate instances. 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< BlockHashm_from_snapshot_blockhash {}
 The blockhash which is the base of the snapshot this chainstate was created from. More...
 
std::set< CBlockIndex *, 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 ResizeCoinsCaches(size_t coinstip_size, size_t coinsdb_size) EXCLUSIVE_LOCKS_REQUIRED(void !cs_avalancheFinalizedBlockIndex
 
DisconnectResult DisconnectBlock(const CBlock &block, const CBlockIndex *pindex, CCoinsViewCache &view) EXCLUSIVE_LOCKS_REQUIRED(boo ConnectBlock )(const CBlock &block, BlockValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, BlockValidationOptions options, Amount *blockFees=nullptr, 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 !cs_avalancheFinalizedBlockIndex
 

Protected Member Functions

bool m_disabled GUARDED_BY (::cs_main)
 This toggle exists for use when doing background validation for UTXO snapshots. More...
 
const CBlockIndex *m_avalancheFinalizedBlockIndex GUARDED_BY (cs_avalancheFinalizedBlockIndex)
 The best block via avalanche voting. More...
 

Protected Attributes

Mutex m_chainstate_mutex
 The ChainState Mutex. More...
 
std::atomic< int32_t > nBlockSequenceId {1}
 Every received block is assigned a unique and increasing identifier, so we know which one to give priority in case of a fork. 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...
 
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...
 
Mutex cs_avalancheFinalizedBlockIndex
 
CRollingBloomFilter m_filterParkingPoliciesApplied
 Filter to prevent parking a block due to block policies more than once. More...
 
CBlockIndex const * m_best_fork_tip = nullptr
 
CBlockIndex const * m_best_fork_base = nullptr
 

Private Member Functions

bool ActivateBestChainStep (BlockValidationState &state, CBlockIndex *pindexMostWork, const std::shared_ptr< const CBlock > &pblock, bool &fInvalidFound, const avalanche::Processor *const avalanche=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main
 Try to make some progress towards making pindexMostWork the active block. More...
 
bool ConnectTip (BlockValidationState &state, BlockPolicyValidationState &blockPolicyState, CBlockIndex *pindexNew, const std::shared_ptr< const CBlock > &pblock, DisconnectedBlockTransactions &disconnectpool, const avalanche::Processor *const avalanche=nullptr) 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 (std::vector< const CBlockIndex * > &blocksToReconcile, bool fAutoUnpark) 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 UnparkBlockImpl (CBlockIndex *pindex, bool fClearChildren) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
bool UnwindBlock (BlockValidationState &state, CBlockIndex *pindex, bool invalidate) EXCLUSIVE_LOCKS_REQUIRED(m_chainstate_mutex
 
void CheckForkWarningConditions () EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
void CheckForkWarningConditionsOnNewFork (CBlockIndex *pindexNewForkTip) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 
void InvalidChainFound (CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main
 
const CBlockIndexFindBlockToFinalize (CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
 

Private Attributes

bool m_mempool !cs_avalancheFinalizedBlockIndex
 
void !cs_avalancheFinalizedBlockIndex
 
CBlockIndex !cs_avalancheFinalizedBlockIndex
 
void UpdateTip(const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED(std::chrono::microsecond m_last_write ) {0}
 Check warning conditions and do some notifications on new chain tip set. More...
 
std::chrono::microseconds m_last_flush {0}
 
util::Result< void > InvalidateCoinsDBOnDisk() EXCLUSIVE_LOCKS_REQUIRED(friend ChainstateManager
 In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for issue diagnosis. More...
 

Detailed Description

Chainstate 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 699 of file validation.h.

Constructor & Destructor Documentation

◆ Chainstate()

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

Definition at line 1518 of file validation.cpp.

Member Function Documentation

◆ AcceptBlock()

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

Store a block on disk.

Parameters
[in,out]pblockThe block we want to accept.
[in]fRequestedA boolean to indicate if this block was requested from our peers.
[in]dbpIf non-null, the disk position of the block.
[in,out]fNewBlockTrue if block was first received via this call.
[in]min_pow_checkedTrue if proof-of-work anti-DoS checks have been done by caller for headers chain
Returns
True if the block is accepted as a valid block and written to disk.

Definition at line 4673 of file validation.cpp.

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

◆ ActivateBestChain()

bool Chainstate::ActivateBestChain ( BlockValidationState state,
std::shared_ptr< const CBlock pblock = nullptr,
avalanche::Processor *const  avalanche = nullptr,
bool  skip_checkblockindex = false 
)

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

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.

Note that if this is called while a snapshot chainstate is active, and if it is called on a background chainstate whose tip has reached the base block of the snapshot, its execution will take MINUTES while it hashes the background UTXO set to verify the assumeutxo value the snapshot was activated with. cs_main will be held during this time.

Parameters
[in]skip_checkblockindex(optional) If true, skip calling CheckBlockIndex even if -checkblockindex is true. If false (default behavior), respect the -checkblockindex arg. This is used in tests when we need to skip the checks only temporarily, and resume normal behavior later.
Returns
true unless a system error occurred

Definition at line 3452 of file validation.cpp.

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

◆ ActivateBestChainStep()

bool Chainstate::ActivateBestChainStep ( BlockValidationState state,
CBlockIndex pindexMostWork,
const std::shared_ptr< const CBlock > &  pblock,
bool &  fInvalidFound,
const avalanche::Processor *const  avalanche = nullptr 
)
private

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

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

Returns
true unless a system error occurred

Definition at line 3277 of file validation.cpp.

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

◆ AvalancheFinalizeBlock()

bool Chainstate::AvalancheFinalizeBlock ( CBlockIndex pindex,
avalanche::Processor avalanche 
)

Mark a block as finalized by avalanche.

Definition at line 4017 of file validation.cpp.

Here is the call graph for this function:

◆ CanFlushToDisk()

void InitCoinsCache(size_t cache_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(bool Chainstate::CanFlushToDisk ( ) const
inline

Initialize the in-memory coins cache (to be done after the health of the on-disk database is verified).

Returns
whether or not the CoinsViews object has been fully initialized and we can safely flush this object to disk.

Definition at line 801 of file validation.h.

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

◆ CheckBlockIndex()

void Chainstate::CheckBlockIndex ( )

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

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

◆ CheckForkWarningConditions()

void Chainstate::CheckForkWarningConditions ( )
private

Definition at line 1580 of file validation.cpp.

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

◆ CheckForkWarningConditionsOnNewFork()

void Chainstate::CheckForkWarningConditionsOnNewFork ( CBlockIndex pindexNewForkTip)
private

Definition at line 1631 of file validation.cpp.

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

◆ ClearAvalancheFinalizedBlock()

void Chainstate::ClearAvalancheFinalizedBlock ( )

Clear avalanche finalization.

Definition at line 4047 of file validation.cpp.

Here is the caller graph for this function:

◆ CoinsDB()

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

Definition at line 841 of file validation.h.

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

◆ CoinsErrorCatcher()

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

Definition at line 851 of file validation.h.

Here is the call graph for this function:

◆ CoinsTip()

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

Definition at line 834 of file validation.h.

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

◆ ConnectTip()

bool Chainstate::ConnectTip ( BlockValidationState state,
BlockPolicyValidationState blockPolicyState,
CBlockIndex pindexNew,
const std::shared_ptr< const CBlock > &  pblock,
DisconnectedBlockTransactions disconnectpool,
const avalanche::Processor *const  avalanche = nullptr 
)
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 valid by consensus rules so now we check if the block passes all block policy checks. If not, then park the block and bail.

We check block parking policies before flushing changes to the UTXO set. This allows us to avoid rewinding everything immediately after.

Only check block parking policies the first time the block is connected. Avalanche voting can override the parking decision made by these policies.

Definition at line 2888 of file validation.cpp.

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

◆ DisconnectTip()

bool Chainstate::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 updateMempoolForReorg. 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 2792 of file validation.cpp.

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

◆ FindBlockToFinalize()

const CBlockIndex * Chainstate::FindBlockToFinalize ( CBlockIndex pindexNew)
private

◆ FindForkInGlobalIndex()

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

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

Definition at line 125 of file validation.cpp.

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

◆ FindMostWorkChain()

CBlockIndex * Chainstate::FindMostWorkChain ( std::vector< const CBlockIndex * > &  blocksToReconcile,
bool  fAutoUnpark 
)
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 3093 of file validation.cpp.

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

◆ FlushStateToDisk()

bool Chainstate::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 2533 of file validation.cpp.

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

◆ ForceFlushStateToDisk()

void Chainstate::ForceFlushStateToDisk ( )

Unconditionally flush all changes to disk.

Definition at line 2714 of file validation.cpp.

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

◆ GetMempool()

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

Definition at line 847 of file validation.h.

Here is the caller graph for this function:

◆ GUARDED_BY() [1/2]

bool m_disabled Chainstate::GUARDED_BY ( ::cs_main  )
inlineprotected

This toggle exists for use when doing background validation for UTXO snapshots.

In the expected case, it is set once the background validation chain reaches the same height as the base of the snapshot and its UTXO set is found to hash to the expected assumeutxo value. It signals that we should no longer connect blocks to the background chainstate. When set on the background validation chainstate, it signifies that we have fully validated the snapshot chainstate.

In the unlikely case that the snapshot chainstate is found to be invalid, this is set to true on the snapshot chainstate.

Definition at line 746 of file validation.h.

◆ GUARDED_BY() [2/2]

const CBlockIndex *m_avalancheFinalizedBlockIndex Chainstate::GUARDED_BY ( cs_avalancheFinalizedBlockIndex  )
protected

The best block via avalanche voting.

This block cannot be reorged in any way except by explicit user action.

◆ HasCoinsViews()

bool Chainstate::HasCoinsViews ( ) const
inline

Does this chainstate have a UTXO set attached?

Definition at line 861 of file validation.h.

◆ InitCoinsDB()

void Chainstate::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.

The in-memory cache is initialized separately.

All parameters forwarded to CoinsViews.

Definition at line 1524 of file validation.cpp.

◆ InvalidateBlock()

bool Chainstate::InvalidateBlock ( BlockValidationState state,
CBlockIndex pindex 
)

Mark a block as invalid.

Definition at line 3904 of file validation.cpp.

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

◆ InvalidBlockFound()

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

Definition at line 1694 of file validation.cpp.

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

◆ InvalidChainFound()

void Chainstate::InvalidChainFound ( CBlockIndex pindexNew)
private

Definition at line 1660 of file validation.cpp.

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

◆ IsBlockAvalancheFinalized()

bool Chainstate::IsBlockAvalancheFinalized ( const CBlockIndex pindex) const

Checks if a block is finalized by avalanche voting.

Definition at line 4052 of file validation.cpp.

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

◆ IsInitialBlockDownload()

bool Chainstate::IsInitialBlockDownload ( ) const

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

Definition at line 1552 of file validation.cpp.

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

◆ LoadChainTip()

bool Chainstate::LoadChainTip ( )

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

CoinsTip()'s best block.

Definition at line 4966 of file validation.cpp.

Here is the call graph for this function:

◆ LoadExternalBlockFile()

void Chainstate::LoadExternalBlockFile ( FILE *  fileIn,
FlatFilePos dbp = nullptr,
std::multimap< BlockHash, FlatFilePos > *  blocks_with_unknown_parent = nullptr,
avalanche::Processor *const  avalanche = nullptr 
)

Resize the CoinsViews caches dynamically and flush state to disk.

Returns
true unless an error occurred during the flush. 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]fileInFILE handle to file 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 5610 of file validation.cpp.

Here is the call graph for this function:

◆ LoadGenesisBlock()

bool Chainstate::LoadGenesisBlock ( )

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

Definition at line 5579 of file validation.cpp.

Here is the call graph for this function:

◆ LoadMempool()

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

Load the persisted mempool from disk.

Definition at line 4957 of file validation.cpp.

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

◆ LOCKS_EXCLUDED() [1/2]

bool !cs_avalancheFinalizedBlockIndex Chainstate::LOCKS_EXCLUDED ( cs_main  )

◆ LOCKS_EXCLUDED() [2/2]

bool !cs_avalancheFinalizedBlockIndex Chainstate::LOCKS_EXCLUDED ( cs_main  )

◆ MempoolMutex()

CoinsCacheSizeState GetCoinsCacheSizeState() EXCLUSIVE_LOCKS_REQUIRED(CoinsCacheSizeState GetCoinsCacheSizeState(size_t max_coins_cache_size_bytes, size_t max_mempool_size_bytes) EXCLUSIVE_LOCKS_REQUIRED(std::string ToString() EXCLUSIVE_LOCKS_REQUIRED(RecursiveMutex * Chainstate::MempoolMutex ( ) const -> cs)
inline

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

Returns
the state of the size of the coins cache. Indirection necessary to make lock annotations work with an optional mempool.

Definition at line 1102 of file validation.h.

Here is the caller graph for this function:

◆ ParkBlock()

bool Chainstate::ParkBlock ( BlockValidationState state,
CBlockIndex pindex 
)

Park a block.

Definition at line 3914 of file validation.cpp.

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

◆ PreciousBlock()

bool Chainstate::PreciousBlock ( BlockValidationState state,
CBlockIndex pindex,
avalanche::Processor *const  avalanche = nullptr 
)

Mark a block as precious and reorganize.

May not be called in a validationinterface callback.

Definition at line 3626 of file validation.cpp.

Here is the call graph for this function:

◆ PruneAndFlush()

void Chainstate::PruneAndFlush ( )

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

Definition at line 2722 of file validation.cpp.

Here is the call graph for this function:

◆ PruneBlockIndexCandidates()

void Chainstate::PruneBlockIndexCandidates ( )

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

Definition at line 3256 of file validation.cpp.

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

◆ ReceivedBlockTransactions()

void Chainstate::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 4063 of file validation.cpp.

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

◆ reliesOnAssumedValid()

bool Chainstate::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 820 of file validation.h.

Here is the caller graph for this function:

◆ ReplayBlocks()

bool Chainstate::ReplayBlocks ( )

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

Definition at line 5231 of file validation.cpp.

Here is the call graph for this function:

◆ ResetBlockFailureFlags()

void Chainstate::ResetBlockFailureFlags ( CBlockIndex pindex)

Remove invalidity status from a block and its descendants.

Definition at line 3976 of file validation.cpp.

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

◆ ResetCoinsViews()

void Chainstate::ResetCoinsViews ( )
inline

Destructs all objects related to accessing the UTXO set.

Definition at line 858 of file validation.h.

◆ RollforwardBlock()

bool Chainstate::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 5203 of file validation.cpp.

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

◆ UnloadBlockIndex()

void Chainstate::UnloadBlockIndex ( )

Definition at line 5332 of file validation.cpp.

Here is the call graph for this function:

◆ UnparkBlock()

void Chainstate::UnparkBlock ( CBlockIndex pindex)

Remove parked status from a block.

Definition at line 4013 of file validation.cpp.

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

◆ UnparkBlockAndChildren()

void Chainstate::UnparkBlockAndChildren ( CBlockIndex pindex)

Remove parked status from a block and its descendants.

Definition at line 4009 of file validation.cpp.

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

◆ UnparkBlockImpl()

void Chainstate::UnparkBlockImpl ( CBlockIndex pindex,
bool  fClearChildren 
)
private

Definition at line 3992 of file validation.cpp.

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

◆ UnwindBlock()

bool Chainstate::UnwindBlock ( BlockValidationState state,
CBlockIndex pindex,
bool  invalidate 
)
private

Definition at line 3675 of file validation.cpp.

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

◆ UpdateFlags()

template<typename F , typename C , typename AC >
void Chainstate::UpdateFlags ( CBlockIndex pindex,
CBlockIndex *&  pindexReset,
f,
fChild,
AC  fAncestorWasChanged 
)

Definition at line 3947 of file validation.cpp.

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

◆ UpdateFlagsForBlock()

template<typename F >
bool Chainstate::UpdateFlagsForBlock ( CBlockIndex pindexBase,
CBlockIndex pindex,
f 
)

Definition at line 3924 of file validation.cpp.

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

Member Data Documentation

◆ !cs_avalancheFinalizedBlockIndex [1/5]

void Chainstate::!cs_avalancheFinalizedBlockIndex

Definition at line 910 of file validation.h.

◆ !cs_avalancheFinalizedBlockIndex [2/5]

bool Chainstate::!cs_avalancheFinalizedBlockIndex

Definition at line 1003 of file validation.h.

◆ !cs_avalancheFinalizedBlockIndex [3/5]

bool m_mempool Chainstate::!cs_avalancheFinalizedBlockIndex
private

Definition at line 1112 of file validation.h.

◆ !cs_avalancheFinalizedBlockIndex [4/5]

void Chainstate::!cs_avalancheFinalizedBlockIndex
private

Definition at line 1123 of file validation.h.

◆ !cs_avalancheFinalizedBlockIndex [5/5]

CBlockIndex Chainstate::!cs_avalancheFinalizedBlockIndex
private

Definition at line 1127 of file validation.h.

◆ ChainstateManager

util::Result<void> InvalidateCoinsDBOnDisk () EXCLUSIVE_LOCKS_REQUIRED( friend Chainstate::ChainstateManager
private

In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for issue diagnosis.

Definition at line 1168 of file validation.h.

◆ ConnectBlock

bool Chainstate::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 977 of file validation.h.

◆ cs

bool m_mempool Chainstate::cs

Definition at line 986 of file validation.h.

◆ cs_avalancheFinalizedBlockIndex

Mutex Chainstate::cs_avalancheFinalizedBlockIndex
mutableprotected

Definition at line 748 of file validation.h.

◆ m_best_fork_base

CBlockIndex const* Chainstate::m_best_fork_base = nullptr
protected

Definition at line 767 of file validation.h.

◆ m_best_fork_tip

CBlockIndex const* Chainstate::m_best_fork_tip = nullptr
protected

Definition at line 766 of file validation.h.

◆ m_blockman

node::BlockManager& Chainstate::m_blockman

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

Definition at line 772 of file validation.h.

◆ m_cached_finished_ibd

std::atomic<bool> Chainstate::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 724 of file validation.h.

◆ m_chain

CChain Chainstate::m_chain

The current chain of blockheaders we consult and build on.

See also
CChain, CBlockIndex.

Definition at line 808 of file validation.h.

◆ m_chainman

ChainstateManager& Chainstate::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 777 of file validation.h.

◆ m_chainstate_mutex

Mutex Chainstate::m_chainstate_mutex
protected

The ChainState Mutex.

A lock that must be held when modifying this ChainState.

Definition at line 705 of file validation.h.

◆ m_coins_views

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

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

Definition at line 732 of file validation.h.

◆ m_coinsdb_cache_size_bytes

size_t Chainstate::m_coinsdb_cache_size_bytes {0}

The cache size of the on-disk coins view.

Definition at line 864 of file validation.h.

◆ m_coinstip_cache_size_bytes

size_t Chainstate::m_coinstip_cache_size_bytes {0}

The cache size of the in-memory coins view.

Definition at line 867 of file validation.h.

◆ m_filterParkingPoliciesApplied

CRollingBloomFilter Chainstate::m_filterParkingPoliciesApplied
protected
Initial value:
=
CRollingBloomFilter{1000, 0.000001}
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set.
Definition: bloom.h:115

Filter to prevent parking a block due to block policies more than once.

After first application of block policies, Avalanche voting will determine the final acceptance state. Rare false positives will be reconciled by the network and should not have any negative impact.

Definition at line 763 of file validation.h.

◆ m_from_snapshot_blockhash

const std::optional<BlockHash> Chainstate::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 816 of file validation.h.

◆ m_last_flush

std::chrono::microseconds Chainstate::m_last_flush {0}
private

Definition at line 1159 of file validation.h.

◆ m_last_write

void UpdateTip (const CBlockIndex *pindexNew) EXCLUSIVE_LOCKS_REQUIRED( std::chrono::microsecond Chainstate::m_last_write) {0}
private

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

Definition at line 1158 of file validation.h.

◆ m_mempool

CTxMemPool* Chainstate::m_mempool
protected

Optional mempool that is kept in sync with the chain.

Only the active chainstate has a mempool.

Definition at line 728 of file validation.h.

◆ nBlockReverseSequenceId

int32_t Chainstate::nBlockReverseSequenceId = -1
protected

Decreasing counter (used by subsequent preciousblock calls).

Definition at line 714 of file validation.h.

◆ nBlockSequenceId

std::atomic<int32_t> Chainstate::nBlockSequenceId {1}
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.

Definition at line 712 of file validation.h.

◆ nLastPreciousChainwork

arith_uint256 Chainstate::nLastPreciousChainwork = 0
protected

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

Definition at line 716 of file validation.h.

◆ setBlockIndexCandidates

std::set<CBlockIndex *, CBlockIndexWorkComparator> Chainstate::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 831 of file validation.h.


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