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

Synopsis

Declared in <validation.h>

class Chainstate;

Description

Eventually, the API here is targeted at being exposed externally as a consumable 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.

Member Functions

Name

Description

Chainstate [constructor]

Construct a chainstate.

ActivateBestChain

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

CanFlushToDisk

Whether the coins view can be safely flushed to disk.

ClearBlockIndexCandidates

Remove all entries from the block index candidate set.

CoinsDB

Access the on‐disk UTXO set database.

CoinsErrorCatcher

Access the error‐catching wrapper around the UTXO set view.

CoinsTip

Access the in‐memory cache of the UTXO set.

ConnectBlock

Apply the effects of a block to a given coins view, checking its validity.

DisconnectBlock

Undo the effects of a block on a given coins view.

DisconnectTip

Apply the effects of a block disconnection on the UTXO set and update the mempool.

FindForkInGlobalIndex

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

FlushStateToDisk

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.

ForceFlushStateToDisk

Flush all changes to disk.

GetCoinsCacheSizeState

GetCoinsCacheSizeState overloads

GetLastFlushedBlock

Get the last block that was flushed to disk.

GetMempool

Access the mempool kept in sync with this chainstate.

GetPruneRange

Return the inclusive[start, end] of block heights we can prune.

GetRole

Return the current role of the chainstate. See ChainstateManager documentation for a description of the different types of chainstates.

InitCoinsCache

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

InitCoinsDB

Initialize the CoinsViews UTXO set database management data structures. The in‐memory cache is initialized separately.

InvalidateBlock

Mark a block as invalid.

LoadChainTip

Update the chain tip based on database information, i.e. CoinsTip()'s best block.

MempoolMutex

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

NeedsRedownload

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

PopulateBlockIndexCandidates

Populate the candidate set by calling TryAddBlockIndexCandidate on all valid block indices.

PreciousBlock

Mark a block as precious and reorganize.

PruneAndFlush

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

PruneBlockIndexCandidates

Remove entries from the candidate set that can no longer become the tip.

ReachedTarget

Return true if chainstate reached target block.

ReplayBlocks

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

ResetBlockFailureFlags

Remove invalidity status from a block, its descendants and ancestors and reconsider them for activation.

ResetCoinsViews

Destructs all objects related to accessing the UTXO set.

ResizeCoinsCaches

Resize the CoinsViews caches dynamically and flush state to disk.

SetBlockFailureFlags

Set invalidity status to all descendants of a block.

SetTargetBlock

Set target block for this chainstate. If null, chainstate will target the most‐work valid block. If non‐null chainstate will be a historic chainstate and target the specified block.

SetTargetBlockHash

Set target block for this chainstate using just a block hash. Useful when the block database has not been loaded yet.

SnapshotBase

The base of the snapshot this chainstate was created from.

StoragePath

Return path to chainstate leveldb directory.

TargetBlock

Return target block which chainstate tip is expected to reach, if this is a historic chainstate being used to validate a snapshot, or null if chainstate targets the most‐work block.

ToString

Return a human‐readable description of this chainstate.

TryAddBlockIndexCandidate

Add a block to the candidate set if it has as much work as the current tip.

Data Members

Name

Description

m_assumeutxo

Assumeutxo state indicating whether all blocks in the chain were validated, or if the chainstate is based on an assumeutxo snapshot and the snapshot has not been validated.

m_blockman

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

m_chain

The current chain of blockheaders we consult and build on.

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.

m_coinsdb_cache_size_bytes

The cache size of the on‐disk coins view.

m_coinstip_cache_size_bytes

The cache size of the in‐memory coins view.

m_from_snapshot_blockhash

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

m_target_blockhash

Target block for this chainstate. If this is not set, chainstate will target the most‐work, valid block. If this is set, ChainstateManager considers this a "historical" chainstate since it will only contain old blocks up to the target block, not newer blocks.

m_target_utxohash

Hash of the UTXO set at the target block, computed when the chainstate reaches the target block, and null before then.

setBlockIndexCandidates

The set of all CBlockIndex entries that have as much work as our current tip or more, and transaction data needed to be validated (with BLOCK_VALID_TRANSACTIONS for each block and its parents back to the genesis block or an assumeutxo snapshot block). Entries may be failed, though, and pruning nodes may be missing the data for the block.

Protected Member Functions

Name

Description

ActivateBestChainStep

Connect a run of blocks toward the most‐work chain, one step of ActivateBestChain.

CheckForkWarningConditions

Check for and log conditions that warrant a fork warning to the user.

ConnectTip

Connect a single block to the tip, updating the mempool and coins view.

FindMostWorkChain

Find the candidate block index entry with the most work.

InvalidBlockFound

Record that a block was found to be invalid and update fork‐warning state.

InvalidChainFound

Record that an invalid chain was found and update the best‐invalid tracking.

InvalidateCoinsDBOnDisk

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

MaybeUpdateMempoolForReorg

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.

RollforwardBlock

Roll a block's effects forward onto a coins view during replay.

UpdateTip

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

Protected Data Members

Name

Description

m_cached_snapshot_base

Cached result of LookupBlockIndex(*m_from_snapshot_blockhash)

m_cached_target_block

Cached result of LookupBlockIndex(*m_target_blockhash)

m_chainstate_mutex

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

m_coins_views

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

m_last_flushed_block

Block index entry of the last block flushed to disk.

m_last_script_check_reason_logged

Reason string for the most recently logged script‐check outcome, used to avoid repeat logging.

m_mempool

Optional mempool that is kept in sync with the chain. Only the active chainstate has a mempool.

m_next_write

Earliest time at which the next periodic chainstate flush should occur.

Friends

Name

Description

ChainstateManager

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 the Chainstate class for more information.)

Non-Member Functions

Name

Description

AcceptToMemoryPool

Try to add a transaction to the mempool. This is an internal function and is exposed only for testing. Client code should use ChainstateManager::ProcessTransaction()

ProcessNewPackage

Validate (and maybe submit) a package to the mempool. See doc/policy/packages.md for full details on package validation rules.

PruneBlockFilesManual

Prune block files up to a given height.

TestBlockValidity

Verify a block, including transactions.

node::WriteSnapshotBaseBlockhash

Write out the blockhash of the snapshot base block that was used to construct this chainstate. This value is read in during subsequent initializations and used to reconstruct snapshot‐based chainstates.

Created with MrDocs