[#Chainstate]
= Chainstate
:mrdocs:

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

== Synopsis

Declared in `&lt;validation&period;h&gt;`

[source,cpp,subs="verbatim,replacements,macros,-callouts"]
----
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&sol;write&hyphen;to&hyphen;disk functions (eventually this will also be via callbacks)&period;

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`&period;

== Member Functions

[cols="1,4"]
|===
| Name| Description
| xref:Chainstate/2constructor.adoc[`Chainstate`]         [.small]#[constructor]#
| Construct a chainstate&period;
| xref:Chainstate/ActivateBestChain.adoc[`ActivateBestChain`] 
| Find the best known block, and make it the tip of the block chain&period; The result is either failure or an activated best chain&period; pblock is either nullptr or a pointer to a block that is already loaded (to avoid loading it again from disk)&period;
| xref:Chainstate/CanFlushToDisk.adoc[`CanFlushToDisk`] 
| Whether the coins view can be safely flushed to disk&period;
| xref:Chainstate/ClearBlockIndexCandidates.adoc[`ClearBlockIndexCandidates`] 
| Remove all entries from the block index candidate set&period;
| xref:Chainstate/CoinsDB.adoc[`CoinsDB`] 
| Access the on&hyphen;disk UTXO set database&period;
| xref:Chainstate/CoinsErrorCatcher.adoc[`CoinsErrorCatcher`] 
| Access the error&hyphen;catching wrapper around the UTXO set view&period;
| xref:Chainstate/CoinsTip.adoc[`CoinsTip`] 
| Access the in&hyphen;memory cache of the UTXO set&period;
| xref:Chainstate/ConnectBlock.adoc[`ConnectBlock`] 
| Apply the effects of a block to a given coins view, checking its validity&period;
| xref:Chainstate/DisconnectBlock.adoc[`DisconnectBlock`] 
| Undo the effects of a block on a given coins view&period;
| xref:Chainstate/DisconnectTip.adoc[`DisconnectTip`] 
| Apply the effects of a block disconnection on the UTXO set and update the mempool&period;
| xref:Chainstate/FindForkInGlobalIndex.adoc[`FindForkInGlobalIndex`] 
| Find the last common block of this chain and a locator&period;
| xref:Chainstate/FlushStateToDisk.adoc[`FlushStateToDisk`] 
| Update the on&hyphen;disk chain state&period; The caches and indexes are flushed depending on the mode we&apos;re called with if they&apos;re too large, if it&apos;s been a while since the last write, or always and in all cases if we&apos;re in prune mode and are deleting files&period;
| xref:Chainstate/ForceFlushStateToDisk.adoc[`ForceFlushStateToDisk`] 
| Flush all changes to disk&period;
| xref:Chainstate/GetCoinsCacheSizeState-05.adoc[`GetCoinsCacheSizeState`] 
| `GetCoinsCacheSizeState` overloads
| xref:Chainstate/GetLastFlushedBlock.adoc[`GetLastFlushedBlock`] 
| Get the last block that was flushed to disk&period;
| xref:Chainstate/GetMempool.adoc[`GetMempool`] 
| Access the mempool kept in sync with this chainstate&period;
| xref:Chainstate/GetPruneRange.adoc[`GetPruneRange`] 
| Return the inclusive[start, end] of block heights we can prune&period;
| xref:Chainstate/GetRole.adoc[`GetRole`] 
| Return the current role of the chainstate&period; See `ChainstateManager` documentation for a description of the different types of chainstates&period;
| xref:Chainstate/InitCoinsCache.adoc[`InitCoinsCache`] 
| Initialize the in&hyphen;memory coins cache (to be done after the health of the on&hyphen;disk database is verified)&period;
| xref:Chainstate/InitCoinsDB.adoc[`InitCoinsDB`] 
| Initialize the CoinsViews UTXO set database management data structures&period; The in&hyphen;memory cache is initialized separately&period;
| xref:Chainstate/InvalidateBlock.adoc[`InvalidateBlock`] 
| Mark a block as invalid&period;
| xref:Chainstate/LoadChainTip.adoc[`LoadChainTip`] 
| Update the chain tip based on database information, i&period;e&period; CoinsTip()&apos;s best block&period;
| xref:Chainstate/MempoolMutex.adoc[`MempoolMutex`] 
| Indirection necessary to make lock annotations work with an optional mempool&period;
| xref:Chainstate/NeedsRedownload.adoc[`NeedsRedownload`] 
| Whether the chain state needs to be redownloaded due to lack of witness data&period;
| xref:Chainstate/PopulateBlockIndexCandidates.adoc[`PopulateBlockIndexCandidates`] 
| Populate the candidate set by calling TryAddBlockIndexCandidate on all valid block indices&period;
| xref:Chainstate/PreciousBlock.adoc[`PreciousBlock`] 
| Mark a block as precious and reorganize&period;
| xref:Chainstate/PruneAndFlush.adoc[`PruneAndFlush`] 
| Prune blockfiles from the disk if necessary and then flush chainstate changes if we pruned&period;
| xref:Chainstate/PruneBlockIndexCandidates.adoc[`PruneBlockIndexCandidates`] 
| Remove entries from the candidate set that can no longer become the tip&period;
| xref:Chainstate/ReachedTarget.adoc[`ReachedTarget`] 
| Return true if chainstate reached target block&period;
| xref:Chainstate/ReplayBlocks.adoc[`ReplayBlocks`] 
| Replay blocks that aren&apos;t fully applied to the database&period;
| xref:Chainstate/ResetBlockFailureFlags.adoc[`ResetBlockFailureFlags`] 
| Remove invalidity status from a block, its descendants and ancestors and reconsider them for activation&period;
| xref:Chainstate/ResetCoinsViews.adoc[`ResetCoinsViews`] 
| Destructs all objects related to accessing the UTXO set&period;
| xref:Chainstate/ResizeCoinsCaches.adoc[`ResizeCoinsCaches`] 
| Resize the CoinsViews caches dynamically and flush state to disk&period;
| xref:Chainstate/SetBlockFailureFlags.adoc[`SetBlockFailureFlags`] 
| Set invalidity status to all descendants of a block&period;
| xref:Chainstate/SetTargetBlock.adoc[`SetTargetBlock`] 
| Set target block for this chainstate&period; If null, chainstate will target the most&hyphen;work valid block&period; If non&hyphen;null chainstate will be a historic chainstate and target the specified block&period;
| xref:Chainstate/SetTargetBlockHash.adoc[`SetTargetBlockHash`] 
| Set target block for this chainstate using just a block hash&period; Useful when the block database has not been loaded yet&period;
| xref:Chainstate/SnapshotBase.adoc[`SnapshotBase`] 
| The base of the snapshot this chainstate was created from&period;
| xref:Chainstate/StoragePath.adoc[`StoragePath`] 
| Return path to chainstate leveldb directory&period;
| xref:Chainstate/TargetBlock.adoc[`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&hyphen;work block&period;
| xref:Chainstate/ToString.adoc[`ToString`] 
| Return a human&hyphen;readable description of this chainstate&period;
| xref:Chainstate/TryAddBlockIndexCandidate.adoc[`TryAddBlockIndexCandidate`] 
| Add a block to the candidate set if it has as much work as the current tip&period;
|===


== Data Members

[cols="1,4"]
|===
| Name| Description
| xref:Chainstate/m_assumeutxo.adoc[`m&lowbar;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&period;
| xref:Chainstate/m_blockman.adoc[`m&lowbar;blockman`] 
| Reference to a BlockManager instance which itself is shared across all Chainstate instances&period;
| xref:Chainstate/m_chain.adoc[`m&lowbar;chain`] 
| The current chain of blockheaders we consult and build on&period;
| xref:Chainstate/m_chainman.adoc[`m&lowbar;chainman`] 
| The chainstate manager that owns this chainstate&period; The reference is necessary so that this instance can check whether it is the active chainstate within deeply nested method calls&period;
| xref:Chainstate/m_coinsdb_cache_size_bytes.adoc[`m&lowbar;coinsdb&lowbar;cache&lowbar;size&lowbar;bytes`] 
| The cache size of the on&hyphen;disk coins view&period;
| xref:Chainstate/m_coinstip_cache_size_bytes.adoc[`m&lowbar;coinstip&lowbar;cache&lowbar;size&lowbar;bytes`] 
| The cache size of the in&hyphen;memory coins view&period;
| xref:Chainstate/m_from_snapshot_blockhash.adoc[`m&lowbar;from&lowbar;snapshot&lowbar;blockhash`] 
| The blockhash which is the base of the snapshot this chainstate was created from&period;
| xref:Chainstate/m_target_blockhash.adoc[`m&lowbar;target&lowbar;blockhash`] 
| Target block for this chainstate&period; If this is not set, chainstate will target the most&hyphen;work, valid block&period; If this is set, ChainstateManager considers this a &quot;historical&quot; chainstate since it will only contain old blocks up to the target block, not newer blocks&period;
| xref:Chainstate/m_target_utxohash.adoc[`m&lowbar;target&lowbar;utxohash`] 
| Hash of the UTXO set at the target block, computed when the chainstate reaches the target block, and null before then&period;
| xref:Chainstate/setBlockIndexCandidates.adoc[`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&lowbar;VALID&lowbar;TRANSACTIONS for each block and its parents back to the genesis block or an assumeutxo snapshot block)&period; Entries may be failed, though, and pruning nodes may be missing the data for the block&period;
|===


== Protected Member Functions

[cols="1,4"]
|===
| Name| Description
| xref:Chainstate/ActivateBestChainStep.adoc[`ActivateBestChainStep`] 
| Connect a run of blocks toward the most&hyphen;work chain, one step of ActivateBestChain&period;
| xref:Chainstate/CheckForkWarningConditions.adoc[`CheckForkWarningConditions`] 
| Check for and log conditions that warrant a fork warning to the user&period;
| xref:Chainstate/ConnectTip.adoc[`ConnectTip`] 
| Connect a single block to the tip, updating the mempool and coins view&period;
| xref:Chainstate/FindMostWorkChain.adoc[`FindMostWorkChain`] 
| Find the candidate block index entry with the most work&period;
| xref:Chainstate/InvalidBlockFound.adoc[`InvalidBlockFound`] 
| Record that a block was found to be invalid and update fork&hyphen;warning state&period;
| xref:Chainstate/InvalidChainFound.adoc[`InvalidChainFound`] 
| Record that an invalid chain was found and update the best&hyphen;invalid tracking&period;
| xref:Chainstate/InvalidateCoinsDBOnDisk.adoc[`InvalidateCoinsDBOnDisk`] 
| In case of an invalid snapshot, rename the coins leveldb directory so that it can be examined for issue diagnosis&period;
| xref:Chainstate/MaybeUpdateMempoolForReorg.adoc[`MaybeUpdateMempoolForReorg`] 
| Make mempool consistent after a reorg, by re&hyphen;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&sol;height&period;
| xref:Chainstate/RollforwardBlock.adoc[`RollforwardBlock`] 
| Roll a block&apos;s effects forward onto a coins view during replay&period;
| xref:Chainstate/UpdateTip.adoc[`UpdateTip`] 
| Check warning conditions and do some notifications on new chain tip set&period;
|===


== Protected Data Members

[cols="1,4"]
|===
| Name| Description
| xref:Chainstate/m_cached_snapshot_base.adoc[`m&lowbar;cached&lowbar;snapshot&lowbar;base`] 
| Cached result of LookupBlockIndex(&ast;m&lowbar;from&lowbar;snapshot&lowbar;blockhash)
| xref:Chainstate/m_cached_target_block.adoc[`m&lowbar;cached&lowbar;target&lowbar;block`] 
| Cached result of LookupBlockIndex(&ast;m&lowbar;target&lowbar;blockhash)
| xref:Chainstate/m_chainstate_mutex.adoc[`m&lowbar;chainstate&lowbar;mutex`] 
| The ChainState Mutex A lock that must be held when modifying this ChainState &hyphen; held in ActivateBestChain() and InvalidateBlock()
| xref:Chainstate/m_coins_views.adoc[`m&lowbar;coins&lowbar;views`] 
| Manages the UTXO set, which is a reflection of the contents of `m&lowbar;chain`&period;
| xref:Chainstate/m_last_flushed_block.adoc[`m&lowbar;last&lowbar;flushed&lowbar;block`] 
| Block index entry of the last block flushed to disk&period;
| xref:Chainstate/m_last_script_check_reason_logged.adoc[`m&lowbar;last&lowbar;script&lowbar;check&lowbar;reason&lowbar;logged`] 
| Reason string for the most recently logged script&hyphen;check outcome, used to avoid repeat logging&period;
| xref:Chainstate/m_mempool.adoc[`m&lowbar;mempool`] 
| Optional mempool that is kept in sync with the chain&period; Only the active chainstate has a mempool&period;
| xref:Chainstate/m_next_write.adoc[`m&lowbar;next&lowbar;write`] 
| Earliest time at which the next periodic chainstate flush should occur&period;
|===


== Friends

[cols="1,4"]
|===
| Name| Description
| `xref:ChainstateManager.adoc[ChainstateManager]`
| Interface for managing multiple Chainstate objects, where each chainstate is associated with chainstate&ast; subdirectory in the data directory and contains a database of UTXOs existing at a different point in history&period; (See the Chainstate class for more information&period;)
|===

== Non-Member Functions

[cols="1,4"]
|===
| Name| Description
| xref:AcceptToMemoryPool.adoc[`AcceptToMemoryPool`]
| Try to add a transaction to the mempool&period; This is an internal function and is exposed only for testing&period; Client code should use ChainstateManager&colon;&colon;ProcessTransaction()
| xref:ProcessNewPackage.adoc[`ProcessNewPackage`]
| Validate (and maybe submit) a package to the mempool&period; See doc&sol;policy&sol;packages&period;md for full details on package validation rules&period;
| xref:PruneBlockFilesManual.adoc[`PruneBlockFilesManual`]
| Prune block files up to a given height&period;
| xref:TestBlockValidity.adoc[`TestBlockValidity`]
| Verify a block, including transactions&period;
| xref:node/WriteSnapshotBaseBlockhash.adoc[`node&colon;&colon;WriteSnapshotBaseBlockhash`]
| Write out the blockhash of the snapshot base block that was used to construct this chainstate&period; This value is read in during subsequent initializations and used to reconstruct snapshot&hyphen;based chainstates&period;
|===


[.small]#Created with https://www.mrdocs.com[MrDocs]#
