Skip to main content
The blockchain crate provides the core blockchain functionality with peer-to-peer networking capabilities for the Ubu-Block system.

Overview

This crate implements:
  • Blockchain data structure with P2P networking
  • Peer discovery and connection management
  • Block synchronization and propagation
  • Message-based P2P protocol

Main Types

BlockChain

The main blockchain structure that manages both the database and P2P networking.
pub struct BlockChain {
    pub db: Database,
    // ... internal P2P fields
}

Construction

pub fn new(db: Database, config: Option<P2PConfig>) -> Self
Creates a new blockchain instance with a database and optional P2P configuration. Example:
use blockchain::BlockChain;
use database::Database;

let db = Database::new_in_memory();
let blockchain = BlockChain::new(db, None);
pub async fn from_config(config: Config) -> Self
Creates a blockchain instance from a configuration file. Example:
let config = Config {
    main_db: "chain.db".to_string(),
    private_db: "private.db".to_string(),
    peer_config: None,
    peers: None,
    http_addr: None,
    node_addr: None,
    mode: None,
};

let blockchain = BlockChain::from_config(config).await;

P2P Networking Methods

pub async fn start_p2p_server(&self, bind_addr: SocketAddr) -> Result<(), ChainError>
Starts the P2P server that listens for incoming peer connections. Example:
use std::net::SocketAddr;

let addr: SocketAddr = "127.0.0.1:8333".parse()?;
blockchain.start_p2p_server(addr).await?;
pub async fn connect_to_peer(&self, addr: SocketAddr) -> Result<(), ChainError>
Connects to a remote peer. Example:
let peer_addr: SocketAddr = "127.0.0.1:8334".parse()?;
blockchain.connect_to_peer(peer_addr).await?;
pub async fn broadcast_message(&self, message: P2PMessage) -> Result<(), ChainError>
Broadcasts a message to all connected peers.
pub async fn announce_block(&self, block: Block) -> Result<(), ChainError>
Announces a new block to the network. Example:
let block = Block::new(/* ... */);
blockchain.announce_block(block).await?;

Peer Management

pub async fn get_peers_info(&self) -> Vec<PeerConnection>
Returns information about all connected peers.
pub async fn peer_count(&self) -> usize
Returns the number of connected peers. Example:
let count = blockchain.peer_count().await;
println!("Connected to {} peers", count);
pub async fn stop(&self)
Stops the P2P networking.

Database Operations (via Deref)

The BlockChain struct implements Deref and DerefMut for Database, so all database methods are directly available:
let height = blockchain.get_height().await?;
let block = blockchain.get_block_by_hash("abc123").await?;
let valid = blockchain.is_valid().await?;

Helper Functions

pub async fn start_node(
    blockchain: BlockChain,
    port: u16,
) -> Result<(), Box<dyn std::error::Error>>
Starts a blockchain node on the specified port. Example:
use blockchain::{BlockChain, start_node};
use database::Database;

let db = Database::new_in_memory();
let blockchain = BlockChain::new(db, None);

start_node(blockchain, 8333).await?;

P2P Protocol

The blockchain implements a message-based protocol for peer communication:
  • Handshake: Hello and HelloResponse messages for connection establishment
  • Block Sync: BlockAnnouncement, GetBlocks, BlocksResponse
  • Chain Info: ChainHeightRequest, ChainHeightResponse
  • Peer Discovery: GetPeers, PeersResponse
  • Keep-Alive: Ping and Pong messages

Configuration

The blockchain uses P2PConfig for network configuration:
pub struct P2PConfig {
    pub max_peers: usize,              // Default: 50
    pub ping_interval: Duration,       // Default: 30s
    pub connection_timeout: Duration,  // Default: 10s
    pub sync_batch_size: u32,         // Default: 100
    pub max_message_size: usize,      // Default: 10MB
}

Error Handling

All async methods return Result<T, ChainError> where ChainError can be:
  • DatabaseError
  • SerializationError
  • IoError
  • PeerError
  • TimeoutError

Thread Safety

The BlockChain struct is Clone and uses Arc-based interior mutability for safe concurrent access across async tasks.

Build docs developers (and LLMs) love