pub struct ChainState {
Show 15 fields pub inner: ChainStateInner, pub n_block_reverse_sequence_id: i32, pub n_last_precious_chainwork: ArithU256, pub cs_chainstate: Broken, pub cached_finished_ibd: AtomicBool, pub mempool: Amo<Box<dyn ITxMemPool>>, pub params: Arc<ChainParams>, pub coins_views: Box<CoinsViews>, pub blockman: Arc<Mutex<BlockManager>>, pub chainman: Arc<Mutex<ChainstateManager>>, pub chain: Chain, pub from_snapshot_blockhash: Option<u256>, pub set_block_index_candidates: HashSet<*mut BlockIndex, BlockIndexWorkComparator>, pub coinsdb_cache_size_bytes: usize, pub coinstip_cache_size_bytes: usize,
}
Expand 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. |

Fields§

§inner: ChainStateInner§n_block_reverse_sequence_id: i32

| Decreasing counter (used by subsequent | preciousblock calls). |

§n_last_precious_chainwork: ArithU256

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

§cs_chainstate: Broken

| the ChainState CriticalSection | | A lock that must be held when modifying | this ChainState - held in ActivateBestChain() |

§cached_finished_ibd: AtomicBool

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

§mempool: Amo<Box<dyn ITxMemPool>>

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

§params: Arc<ChainParams>§coins_views: Box<CoinsViews>

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

§blockman: Arc<Mutex<BlockManager>>

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

§chainman: Arc<Mutex<ChainstateManager>>

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

§chain: Chain

| The current chain of blockheaders we | consult and build on. @see Chain, CBlockIndex. |

§from_snapshot_blockhash: Option<u256>

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

§set_block_index_candidates: HashSet<*mut BlockIndex, BlockIndexWorkComparator>

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

§coinsdb_cache_size_bytes: usize

| The cache size of the on-disk coins view. |

§coinstip_cache_size_bytes: usize

| The cache size of the in-memory coins | view. |

Implementations§

source§

impl ChainState

source

pub fn maybe_update_mempool_for_reorg( &mut self, disconnectpool: &mut DisconnectedBlockTransactions, add_to_mempool: bool )

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

source

pub fn can_flush_to_disk(&self) -> bool

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

source

pub fn coinsdb(&mut self) -> &mut CoinsViewDB

| @return | | A reference to the on-disk UTXO set database. |

source

pub fn coins_error_catcher(&mut self) -> &mut CoinsViewErrorCatcher

| @return | | A reference to a wrapped view of the in-memory | UTXO set that handles disk read errors | gracefully. |

source

pub fn reset_coins_views(&mut self)

| Destructs all objects related to accessing | the UTXO set. |

source

pub fn mempool_mutex<T>(&self) -> *mut ReentrantMutex<T>

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

source

pub fn new( mempool: Arc<Mutex<dyn ITxMemPool>>, blockman: &mut BlockManager, chainman: &mut ChainstateManager, from_snapshot_blockhash: Option<u256> ) -> Self

source

pub fn init_coinsdb( &mut self, cache_size_bytes: usize, in_memory: bool, should_wipe: bool, leveldb_name: Option<&str> )

| Initialize the CoinsViews UTXO set | database management data structures. | The in-memory cache is initialized | separately. | | All parameters forwarded to CoinsViews. |

source

pub fn init_coins_cache(&mut self, cache_size_bytes: usize)

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

source

pub fn check_fork_warning_conditions(&mut self)

source

pub fn invalid_chain_found(&mut self, pindex_new: *mut BlockIndex)

| Called both upon regular invalid block | discovery and InvalidateBlock |

source

pub fn invalid_block_found( &mut self, pindex: *mut BlockIndex, state: &BlockValidationState )

| Same as InvalidChainFound, above, except | not called directly from InvalidateBlock, | which does its own setBlockIndexCandidates | management.

source

pub fn disconnect_block( &mut self, block: &Block, pindex: *const BlockIndex, view: &mut CoinsViewCache ) -> DisconnectResult

| Block (dis)connection on a given view: | | Undo the effects of this block (with | given index) on the UTXO set represented | by coins. | | When FAILED is returned, view is left | in an indeterminate state. |

source

pub fn connect_block( &mut self, block: &Block, state: &mut BlockValidationState, pindex: *mut BlockIndex, view: &mut CoinsViewCache, just_check: Option<bool> ) -> bool

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

source

pub fn get_coins_cache_size_state(&mut self) -> CoinsCacheSizeState

| Dictates whether we need to flush the | cache to disk or not. | | @return the state of the size of the coins | cache.

source

pub fn flush_state_to_disk( &mut self, state: &mut BlockValidationState, mode: FlushStateMode, n_manual_prune_height: Option<i32> ) -> bool

| 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. | | | ———– | @return | | true unless a system error occurred |

source

pub fn force_flush_state_to_disk(&mut self)

| Unconditionally flush all changes | to disk. |

source

pub fn prune_and_flush(&mut self)

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

source

pub fn update_tip(&mut self, pindex_new: *const BlockIndex)

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

source

pub fn disconnect_tip( &mut self, state: &mut BlockValidationState, disconnectpool: *mut DisconnectedBlockTransactions ) -> bool

| Apply the effects of a block disconnection | on the UTXO set. | | 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). |

source

pub fn connect_tip( &mut self, state: &mut BlockValidationState, pindex_new: *mut BlockIndex, pblock: &Arc<Block>, connect_trace: &mut ConnectTrace, disconnectpool: &mut DisconnectedBlockTransactions ) -> bool

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

source

pub fn find_most_work_chain(&mut self) -> *mut BlockIndex

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

source

pub fn prune_block_index_candidates(&mut self)

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

source

pub fn activate_best_chain_step( &mut self, state: &mut BlockValidationState, pindex_most_work: *mut BlockIndex, pblock: &Arc<Block>, invalid_found: &mut bool, connect_trace: &mut ConnectTrace ) -> bool

| Try to make some progress towards making | pindexMostWork the active block. pblock | is either nullptr or a pointer to a CBlock | corresponding to pindexMostWork. | | | ———– | @return | | true unless a system error occurred |

source

pub fn precious_block( &mut self, state: &mut BlockValidationState, pindex: *mut BlockIndex ) -> bool

| Mark a block as precious and reorganize. | | May not be called in a validationinterface | callback. |

source

pub fn invalidate_block( &mut self, state: &mut BlockValidationState, pindex: *mut BlockIndex ) -> bool

| Mark a block as invalid. |

source

pub fn reset_block_failure_flags(&mut self, pindex: *mut BlockIndex)

| Remove invalidity status from a block | and its descendants. |

source

pub fn received_block_transactions( &mut self, block: &Block, pindex_new: *mut BlockIndex, pos: &FlatFilePos )

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

source

pub fn accept_block( &mut self, pblock: &Arc<Block>, state: &mut BlockValidationState, ppindex: *mut *mut BlockIndex, requested: bool, dbp: *const FlatFilePos, new_block: *mut bool ) -> bool

| Store block on disk. If dbp is non-nullptr, | the file is known to already reside on | disk |

source

pub fn load_mempool(&mut self, args: &ArgsManager)

| Load the persisted mempool from disk |

source

pub fn load_chain_tip(&mut self) -> bool

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

source

pub fn rollforward_block( &mut self, pindex: *const BlockIndex, inputs: &mut CoinsViewCache ) -> bool

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

source

pub fn replay_blocks(&mut self) -> bool

| Replay blocks that aren’t fully applied | to the database. |

source

pub fn needs_redownload(&self) -> bool

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

source

pub fn unload_block_index(&mut self)

source

pub fn load_genesis_block(&mut self) -> bool

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

source

pub fn load_external_block_file( &mut self, file_in: *mut FILE, dbp: Option<*mut FlatFilePos> )

| Import blocks from an external file |

source

pub fn check_block_index(&mut self)

| Make various assertions about the state | of the block index. | | By default this only executes fully | when using the Regtest chain; see: fCheckBlockIndex. |

source

pub fn to_string(&mut self) -> String

source

pub fn resize_coins_caches( &mut self, coinstip_size: usize, coinsdb_size: usize ) -> bool

| Resize the CoinsViews caches dynamically | and flush state to disk. | | @returns true unless an error occurred | during the flush.

Trait Implementations§

source§

impl ActivateBestChain for ChainState

source§

fn activate_best_chain( &mut self, state: &mut BlockValidationState, pblock: Amo<Block> ) -> bool

| 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. | | | ———– | @return | | true unless a system error occurred |

source§

impl ChainHeight for ChainState

source§

fn height(&self) -> Option<usize>

| Get current chain height, not including | genesis block (returns 0 if chain only | contains genesis block, nullopt if chain | does not contain any blocks)
source§

impl CoinsTip for ChainState

source§

fn coins_tip(&mut self) -> &mut CoinsViewCache

| @return | | A reference to the in-memory cache of | the UTXO set. |

source§

impl IsInitialBlockDownload for ChainState

source§

fn is_initial_block_download(&self) -> bool

| Check whether we are doing an initial | block download (synchronizing from | disk or network) | | NOTE: though this is marked const, we may | end up modifying m_cached_finished_ibd, which | is a performance-related implementation | detail. This function must be marked const so | that CValidationInterface clients (which are | given a const ChainState*) can call it. |

source§

impl ChainStateInterface for ChainState

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T, U> CastInto<U> for Twhere U: CastFrom<T>,

§

unsafe fn cast_into(self) -> U

Performs the conversion. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> StaticUpcast<T> for T

§

unsafe fn static_upcast(ptr: Ptr<T>) -> Ptr<T>

Convert type of a const pointer. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V