Overview
The Blockchain struct orchestrates all components of the minichain blockchain: consensus, storage, mempool, and execution. It provides high-level APIs for initializing the chain, submitting transactions, proposing blocks, and importing validated blocks.
Blockchain
Main blockchain struct that coordinates all components.
Constructor
Create a new blockchain with the given storage and configuration.pub fn new(storage: &'a Storage, config: BlockchainConfig) -> Self
Storage backend for persistent state
Blockchain configuration including consensus and block limits
Methods
init_genesis
Initialize the blockchain with a genesis block.pub fn init_genesis(&self, genesis: &Block) -> Result<()>
The genesis block to initialize the chain with
Returns Ok(()) on success or BlockchainError on failure
height
Get the current chain height.pub fn height(&self) -> Result<u64>
Returns the current block height (0 for genesis)
get_latest_block
Get the latest block in the chain.pub fn get_latest_block(&self) -> Result<Block>
Returns the most recent block or BlockchainError::InvalidChainState
get_block
Get a block by its hash.pub fn get_block(&self, hash: &Hash) -> Result<Option<Block>>
The hash of the block to retrieve
Returns Some(Block) if found, None if not found
get_block_by_height
Get a block by its height.pub fn get_block_by_height(&self, height: u64) -> Result<Option<Block>>
The height of the block to retrieve
Returns Some(Block) if found, None if not found
register_authority
Register a public key for an authority.pub fn register_authority(&mut self, address: Address, public_key: PublicKey)
The address of the authority
The public key for signature verification
submit_transaction
Submit a transaction to the mempool.pub fn submit_transaction(&mut self, tx: Transaction) -> Result<()>
The signed transaction to submit
Returns Ok(()) on success or validation error
get_pending_transactions
Get pending transactions from the mempool.pub fn get_pending_transactions(&self, limit: usize) -> Vec<Transaction>
Maximum number of transactions to return
Returns up to limit pending transactions, ordered by gas price
propose_block
Propose a new block (for authorities).pub fn propose_block(&mut self, proposer: &BlockProposer) -> Result<Block>
Block proposer with authority keypair
Returns the proposed block or consensus error if not authority’s turn
validate_and_execute_block
validate_and_execute_block
Validate and execute a block.This performs:
- Consensus validation (authority, signature, timestamp)
- Block structure validation
- Transaction execution
- State root update
pub fn validate_and_execute_block(&self, block: &Block) -> Result<BlockExecutionResult>
The block to validate and execute
Result
Result<BlockExecutionResult>
Returns execution results including receipts and gas used
import_block
Import a block into the chain.This validates, executes, and stores the block, then updates the chain head and removes included transactions from the mempool.pub fn import_block(&mut self, block: Block) -> Result<BlockExecutionResult>
Result
Result<BlockExecutionResult>
Returns execution results on success
stats
Get blockchain statistics.pub fn stats(&self) -> Result<BlockchainStats>
Returns current blockchain statistics
BlockchainConfig
Configuration for the blockchain.
pub struct BlockchainConfig {
pub consensus: PoAConfig,
pub max_block_size: usize,
}
Proof of Authority consensus configuration
Maximum number of transactions per block (default: 1000)
BlockchainStats
Statistics about the current blockchain state.
pub struct BlockchainStats {
pub height: u64,
pub latest_block_hash: Hash,
pub latest_timestamp: u64,
pub pending_transactions: usize,
pub authority_count: usize,
}
Timestamp of the latest block
Number of pending transactions in mempool
Number of registered authorities
BlockchainError
Errors that can occur during blockchain operations.
pub enum BlockchainError {
Storage(StorageError),
Consensus(ConsensusError),
Validation(ValidationError),
Execution(ExecutionError),
Mempool(MempoolError),
MissingGenesis,
BlockNotFound(Hash),
InvalidChainState,
}
Usage Example
use minichain_chain::{Blockchain, BlockchainConfig};
use minichain_consensus::{PoAConfig, BlockProposer};
use minichain_core::{Keypair, Block};
use minichain_storage::Storage;
// Setup storage
let storage = Storage::open("./blockchain_data").unwrap();
// Configure blockchain with PoA
let keypair = Keypair::generate();
let config = BlockchainConfig {
consensus: PoAConfig::new(vec![keypair.address()], 5),
max_block_size: 1000,
};
// Create blockchain
let mut blockchain = Blockchain::new(&storage, config);
blockchain.register_authority(keypair.address(), keypair.public_key.clone());
// Initialize with genesis
let genesis = Block::genesis(keypair.address()).signed(&keypair);
blockchain.init_genesis(&genesis).unwrap();
// Submit a transaction
let from = keypair.address();
let to = Address::from_bytes([2u8; 20]);
let tx = Transaction::transfer(from, to, 1000, 0, 1).signed(&keypair);
blockchain.submit_transaction(tx).unwrap();
// Propose a block
let proposer = BlockProposer::new(keypair, config.consensus);
let block = blockchain.propose_block(&proposer).unwrap();
// Import the block
let result = blockchain.import_block(block).unwrap();
println!("Block imported with {} transactions", result.receipts.len());
// Get stats
let stats = blockchain.stats().unwrap();
println!("Chain height: {}", stats.height);
println!("Pending transactions: {}", stats.pending_transactions);
See Also