Skip to main content

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

new
fn
Create a new blockchain with the given storage and configuration.
pub fn new(storage: &'a Storage, config: BlockchainConfig) -> Self
storage
&Storage
required
Storage backend for persistent state
config
BlockchainConfig
required
Blockchain configuration including consensus and block limits

Methods

init_genesis

init_genesis
fn
Initialize the blockchain with a genesis block.
pub fn init_genesis(&self, genesis: &Block) -> Result<()>
genesis
&Block
required
The genesis block to initialize the chain with
Result
Result<()>
Returns Ok(()) on success or BlockchainError on failure

height

height
fn
Get the current chain height.
pub fn height(&self) -> Result<u64>
Result
Result<u64>
Returns the current block height (0 for genesis)

get_latest_block

get_latest_block
fn
Get the latest block in the chain.
pub fn get_latest_block(&self) -> Result<Block>
Result
Result<Block>
Returns the most recent block or BlockchainError::InvalidChainState

get_block

get_block
fn
Get a block by its hash.
pub fn get_block(&self, hash: &Hash) -> Result<Option<Block>>
hash
&Hash
required
The hash of the block to retrieve
Result
Result<Option<Block>>
Returns Some(Block) if found, None if not found

get_block_by_height

get_block_by_height
fn
Get a block by its height.
pub fn get_block_by_height(&self, height: u64) -> Result<Option<Block>>
height
u64
required
The height of the block to retrieve
Result
Result<Option<Block>>
Returns Some(Block) if found, None if not found

register_authority

register_authority
fn
Register a public key for an authority.
pub fn register_authority(&mut self, address: Address, public_key: PublicKey)
address
Address
required
The address of the authority
public_key
PublicKey
required
The public key for signature verification

submit_transaction

submit_transaction
fn
Submit a transaction to the mempool.
pub fn submit_transaction(&mut self, tx: Transaction) -> Result<()>
tx
Transaction
required
The signed transaction to submit
Result
Result<()>
Returns Ok(()) on success or validation error

get_pending_transactions

get_pending_transactions
fn
Get pending transactions from the mempool.
pub fn get_pending_transactions(&self, limit: usize) -> Vec<Transaction>
limit
usize
required
Maximum number of transactions to return
Result
Vec<Transaction>
Returns up to limit pending transactions, ordered by gas price

propose_block

propose_block
fn
Propose a new block (for authorities).
pub fn propose_block(&mut self, proposer: &BlockProposer) -> Result<Block>
proposer
&BlockProposer
required
Block proposer with authority keypair
Result
Result<Block>
Returns the proposed block or consensus error if not authority’s turn

validate_and_execute_block

validate_and_execute_block
fn
Validate and execute a block.This performs:
  1. Consensus validation (authority, signature, timestamp)
  2. Block structure validation
  3. Transaction execution
  4. State root update
pub fn validate_and_execute_block(&self, block: &Block) -> Result<BlockExecutionResult>
block
&Block
required
The block to validate and execute
Result
Result<BlockExecutionResult>
Returns execution results including receipts and gas used

import_block

import_block
fn
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>
block
Block
required
The block to import
Result
Result<BlockExecutionResult>
Returns execution results on success

stats

stats
fn
Get blockchain statistics.
pub fn stats(&self) -> Result<BlockchainStats>
Result
Result<BlockchainStats>
Returns current blockchain statistics

BlockchainConfig

Configuration for the blockchain.
pub struct BlockchainConfig {
    pub consensus: PoAConfig,
    pub max_block_size: usize,
}
consensus
PoAConfig
Proof of Authority consensus configuration
max_block_size
usize
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,
}
height
u64
Current chain height
latest_block_hash
Hash
Hash of the latest block
latest_timestamp
u64
Timestamp of the latest block
pending_transactions
usize
Number of pending transactions in mempool
authority_count
usize
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

Build docs developers (and LLMs) love