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

Synopsis

Declared in <validation.h>

class ChainstateManager;

Description

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

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

Type Aliases

NameDescription
Options Options controlling the behavior of the chainstate manager.

Member Functions

NameDescription
ChainstateManager [constructor]Construct a chainstate manager.
~ChainstateManager [destructor]Destroy the chainstate manager and its chainstates.
AcceptBlock Sufficiently validate a block for disk storage (and store on disk).
ActivateBestChains Call ActivateBestChain() on every chainstate.
ActivateSnapshot Construct and activate a Chainstate on the basis of UTXO snapshot data.
ActiveChain Return the active chain of block headers.
ActiveChainstate Alternatives to CurrentChainstate() used by older code to query latest chainstate information without locking cs_main. Newer code should avoid querying ChainstateManager and use Chainstate objects directly, or should use CurrentChainstate() instead. @{ Return the active chainstate.
ActiveHeight Return the height of the active chain tip.
ActiveTip Return the active chain tip.
AddChainstate Add new chainstate.
AssumedValidBlock Access the assumed-valid block below which script checks may be skipped.
BlockIndex Access the map of all known block index entries.
BlocksAheadOfTip Returns how many blocks the best header is ahead of the current tip, or nullopt if the best header does not extend the tip.
CheckBlockIndex Make various assertions about the state of the block index.
CurrentChainstate Return current chainstate targeting the most-work, network tip.
DeleteChainstate Remove the chainstate and all on-disk artifacts. Used when reindex{-chainstate} is called during snapshot use.
GenerateCoinbaseCommitment Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks).
GetBackgroundVerificationProgress Guess background verification progress in case assume-utxo was used (as a fraction between 0.0=genesis and 1.0=snapshot blocks).
GetCheckQueue Access the queue of pending script verifications.
GetConsensus Access the consensus parameters in use.
GetHistoricalBlockRange Get range of historical blocks to download.
GetMutex 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.
GetNotifications Access the notifications sink used to surface validation events.
GetParams Access the chain parameters in use.
GuessVerificationProgress Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). This is also the case in the assumeutxo context, meaning that the progress reported for the snapshot chainstate may suggest that all historical blocks have already been verified even though that may not actually be the case.
HistoricalChainstate Return historical chainstate targeting a specific block, if any.
InitializeChainstate Instantiate a new chainstate.
IsInitialBlockDownload Check whether we are doing an initial block download (synchronizing from disk or network).
LoadAssumeutxoChainstate When starting up, search the datadir for a chainstate based on a UTXO snapshot that is in the process of being validated and load it if found. Return pointer to the Chainstate if it is loaded.
LoadBlockIndex Load the block tree and coins database from disk, initializing state if we're running with -reindex
LoadExternalBlockFile Import blocks from an external file
LoadGenesisBlock Ensures a genesis block is in the block tree, possibly writing one to disk.
MaybeRebalanceCaches Check to see if caches are out of balance and if so, call ResizeCoinsCaches() as needed.
MaybeValidateSnapshot Try to validate an assumeutxo snapshot by using a validated historical chainstate targeted at the snapshot block. When the target block is reached, the UTXO hash is computed and saved to validated_cs.m_target_utxohash, and unvalidated_cs.m_assumeutxo will be updated from UNVALIDATED to either VALIDATED or INVALID depending on whether the hash matches. The INVALID case should not happen in practice because the software should refuse to load unrecognized snapshots, but if it does happen, it is a fatal error.
MinimumChainWork Access the minimum chain work required to consider syncing complete.
ProcessNewBlock 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!
ProcessNewBlockHeaders Process incoming block headers.
ProcessTransaction Try to add a transaction to the memory pool.
RecalculateBestHeader If, due to invalidation / reconsideration of blocks, the previous best header is no longer valid / guaranteed to be the most-work header in our block-index not known to be invalid, recalculate it.
ReceivedBlockTransactions Mark that the transaction data for a block has been received and stored.
RemoveChainstate Remove a chainstate.
ReportHeadersPresync 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.
ResetBlockSequenceCounters Reset the memory-only sequence counters used to track block arrival (used by tests).
ResetChainstates Destroy all chainstates managed by this instance.
ShouldCheckBlockIndex Whether expensive block-index consistency checks should run.
UpdateIBDStatus Update and possibly latch the IBD status.
UpdateUncommittedBlockStructures Update uncommitted block structures (currently: only the witness reserved value). This is safe for submitted blocks as long as they honor default_witness_commitment from the template.
ValidatedChainstate Return fully validated chainstate that should be used for indexing, to support indexes that need to index blocks in order and can't start from the snapshot block.
ValidatedSnapshotCleanup 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.

Data Members

NameDescription
m_best_header Best header we've seen so far for which the block is not known to be invalid (used, among others, for getheaders queries' starting points). In case of multiple best headers with the same work, it could point to any because CBlockIndexWorkComparator tiebreaker rules are not applied.
m_blockman A single BlockManager instance is shared across each constructed chainstate to avoid duplicating block metadata.
m_cached_is_ibd Whether initial block download (IBD) is ongoing.
m_chainstates List of chainstates. Note: in general, it is not safe to delete Chainstate objects once they are added to this list because there is no mutex that can be locked to prevent Chainstate pointers from being used while they are deleted. (cs_main doesn't work because it is too narrow and is released in the middle of Chainstate::ActivateBestChain to let notifications be processed. m_chainstate_mutex doesn't work because it is not locked at other times when the chainstate is in use.)
m_interrupt Signal used to observe shutdown requests during long-running operations.
m_options Options controlling the behavior of this chainstate manager.
m_total_coinsdb_cache The total number of bytes available for us to use across all leveldb coins databases. This will be split somehow across chainstates.
m_total_coinstip_cache The total number of bytes available for us to use across all in-memory coins caches. This will be split somehow across chainstates.
m_validation_cache Caches for script execution and signature verification results.
m_versionbitscache Track versionbit status
nBlockReverseSequenceId Decreasing counter (used by subsequent preciousblock calls).
nBlockSequenceId Every received block is assigned a unique and increasing identifier, so we know which one to give priority in case of a fork.
nLastPreciousChainwork chainwork for the last block that preciousblock has been applied to.
snapshot_download_completed Function to restart active indexes; set dynamically to avoid a circular dependency on base/index.cpp.

Protected Data Members

NameDescription
m_best_invalid Best known invalid block, tracked to detect a longer invalid chain than the valid one.

Friends

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

Non-Member Functions

NameDescription
DeploymentEnabledWhether a deployment is enabled in the consensus rules, resolved via ChainstateManager.
EnsureAnyChainmanGet the chainstate manager from an opaque RPC context, asserting it is present.
EnsureChainmanGet the chainstate manager from a node context, asserting it is present.
node::CooldownIfHeadersAheadWait while the best known header extends the current chain tip AND at least one block is being added to the tip every 3 seconds. If the tip is sufficiently far behind, allow up to 20 seconds for the next tip update.
node::GetTipReturn the hash and height of the active chain tip.
node::ImportBlocksLoad blocks from the given files and activate the best chain, even if none are imported.
node::LoadChainstateThis sequence can have 4 types of outcomes:
node::SubmitBlockSubmit a block and capture the validation state via the BlockChecked callback. Returns whether the block was accepted as a new valid block.
node::VerifyLoadedChainstateVerify a chainstate that has already been loaded.
node::WaitAndCreateNewBlockReturn a new block template when fees rise to a certain threshold or after a new tip; return nullopt if timeout is reached.
node::WaitTipChangedWaits for the connected tip to change until timeout has elapsed. During node initialization, this will wait until the tip is connected (regardless of timeout). Returns the current tip, or nullopt if the node is shutting down or interrupt() is called.