Overview
TheChainStore manages block storage and chain state, including:
- Storing blocks with dual indexing (by hash and height)
- Tracking the chain head and current height
- Genesis block initialization
- Block retrieval and validation
- Chain traversal operations
ChainStore
Manages block storage and chain state.Constructor
Creates a new ChainStore wrapping the given storage.Example:
Reference to the underlying Storage instance
Block Storage
Stores a block with dual indexing (by hash and height).Creates two index entries:Example:
- Primary:
block:hash:{hash}→ full block data (immutable) - Secondary:
block:height:{height}→ hash (pointer, can change during reorgs)
Block to store
Retrieves a block by its height.Performs two lookups:Example:
- height → hash (secondary index)
- hash → block (primary storage)
Block height
Chain Head Tracking
Gets the current chain head hash.Example:
Returns Some(hash) if chain is initialized, None otherwise
Gets the current chain height.Example:
Returns current height, or 0 if chain is not initialized
Gets the latest block (current head).Example:
Returns the head block, or None if chain is not initialized
Genesis Block
Initializes the chain with a genesis block.Validates:Returns:
- Block height must be 0
- Chain must not already be initialized
Genesis block (height must be 0)
Err(StorageError::InvalidGenesis) if validation fails.Example:Checks if the chain is initialized (has a genesis block).Example:
Chain Operations
Appends a new block to the chain with validation.Validates:Note: This does NOT validate transactions or signatures. Full validation should be done before calling this method.Example:
- Block height is exactly
current_height + 1 - Block’s
prev_hashmatches the current head
Block to append
Storage Keys
Internal constants for chain metadata:Complete Example
Block Indexing Strategy
The ChainStore uses a dual-indexing strategy:Primary Index: Hash → Block
- Immutable once written
- Source of truth for block data
- Supports lookups by hash
Secondary Index: Height → Hash
- Pointer to the primary index
- Can be updated during reorganizations
- Supports lookups by height
- Efficient lookups by both hash and height
- Safe handling of chain reorganizations
- Block data deduplication (same block, different forks)
Error Handling
Common errors when working with ChainStore:See Also
- Storage - Low-level database operations
- StateManager - Account and contract state management