Skip to content

aarambh-darshan/mini-blockchain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

25 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Rust License Status

โ›“๏ธ Mini-Blockchain

A production-ready blockchain implementation in Rust

Features โ€ข Installation โ€ข Quick Start โ€ข CLI Commands โ€ข Architecture โ€ข API


โœจ Features

Core Blockchain

Feature Description
โ›๏ธ Proof of Work SHA-256 mining with dynamic difficulty adjustment
๐Ÿ” ECDSA Signatures secp256k1 curve for secure transaction signing
๐Ÿ’ฐ UTXO Model Bitcoin-style with locktime, RBF, and chain ID
๐ŸŒณ Merkle Trees Efficient transaction verification and integrity
๐Ÿ”€ Fork Resolution Longest chain rule with orphan block handling
โฑ๏ธ MTP Validation Median Time Past for timestamp security

Wallets & Transactions

Feature Description
๐Ÿ‘› Wallet System Key generation with Base58Check addresses
โœ๏ธ Multi-Signature M-of-N threshold signatures for shared wallets
๐Ÿ”„ Replace-By-Fee BIP-125 transaction replacement
โณ Locktime BIP-65 time-locked transactions
๐Ÿ›ก๏ธ Replay Protection EIP-155 style chain ID

Network & Security

Feature Description
๐ŸŒ P2P Networking TCP with 24-byte header, SHA-256 checksums
๐Ÿ”— API + P2P Integration Run API with embedded P2P node for block broadcasting
๐Ÿ“ก Block Propagation Real-time gossip with relay to all peers
๐Ÿ” Peer Discovery DNS seeds + GetAddr/Addr exchange
๐Ÿ—‚๏ธ Address Manager Bitcoin-style new/tried tables
๐Ÿšซ Peer Scoring Misbehavior detection and banning
๐Ÿ›‘ Rate Limiting DOS protection (1000 msg/min)
๐ŸŒ NAT Traversal UPnP port mapping with auto-renewal
โšก Parallel Sync Download blocks from multiple peers
๐Ÿ›ก๏ธ Eclipse Resistance Subnet diversity for connection selection

Storage & Performance

Feature Description
๐Ÿ“‡ Block Indexing Fast lookups by hash, height, address
๐Ÿ’พ UTXO Cache LRU cache with 100K entries
โœ… Checkpoints Fast sync for known-good blocks
๐Ÿ—‘๏ธ Pruning Configurable block retention

Advanced Features

Feature Description
๐Ÿ” SPV Support Bloom filters (BIP-37) for light clients
๐Ÿ’ต Fee Estimation Smart fee calculation (high/normal/low)
๐Ÿ—œ๏ธ Compression Delta encoding for efficient storage
๐Ÿช™ On-Chain Tokens ERC-20 style fungible tokens via transaction opcodes
โ›ฝ Gas System Real gas payments for contracts
๐Ÿ“œ On-Chain Smart Contracts Stack-based VM with bytecode, deployed via transactions
๐ŸŒ Web UI SvelteKit + shadcn-svelte dashboard
๐Ÿš€ REST API HTTP API with Axum
๐Ÿ”Œ WebSocket Real-time updates

Production-Grade Security (Bitcoin/Ethereum Inspired)

Feature Value Description
๐Ÿ”’ Coinbase Maturity 100 blocks Mining rewards can't be spent until 100 confirmations
๐Ÿ“ฆ Block Size Limit 1 MB Maximum block size (Bitcoin-style)
๐Ÿ“„ Transaction Size 100 KB Maximum transaction size
๐Ÿ“‘ Script System P2PKH, P2SH, MultiSig Bitcoin-like output locking scripts
๐Ÿ” Signature Hash Types ALL, NONE, SINGLE SIGHASH types for flexible signing
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Package Limits 25/25 Max ancestors/descendants per tx chain
๐Ÿ’พ Mempool Size 300 MB Maximum mempool memory usage
๐Ÿ” Call Depth Limit 1024 Prevents stack overflow attacks (EVM-style)
๐Ÿง  Memory Gas Metering Linear Gas charged for VM memory expansion
๐Ÿ›ก๏ธ Reentrancy Protection Automatic Prevents contract reentrancy attacks

๐Ÿ“ฆ Installation

Prerequisites

  • Rust 1.70+ (install via rustup)

Build from Source

# Clone the repository
git clone https://github.com/yourusername/mini-blockchain.git
cd mini-blockchain

# Build release version
cargo build --release

# The binary will be at ./target/release/blockchain

๐Ÿš€ Quick Start

# 1. Initialize a new blockchain
./target/release/blockchain init

# 2. Create a wallet
./target/release/blockchain wallet new --label "MyWallet"

# 3. Start mining (replace ADDRESS with your wallet address)
./target/release/blockchain mine --address <ADDRESS> --count 5

# 4. Check your balance
./target/release/blockchain wallet balance --address <ADDRESS>

# 5. View blockchain info
./target/release/blockchain chain

Example Output

โ›๏ธ  Mining 5 block(s) for address: 1FUdbKMd9nfCC6gGmczBXniNDuYw81Zyyg

   Block 1 mined!
   โ”œโ”€ Hash: 00fcfbb82a7dfe25
   โ”œโ”€ Transactions: 1
   โ”œโ”€ Time: 0ms
   โ”œโ”€ Attempts: 577
   โ””โ”€ Hash rate: 577.00 H/s

๐Ÿ’ฐ New balance for miner: 250 coins

๐Ÿ–ฅ๏ธ CLI Commands

Blockchain Management

Command Description
init Initialize a new blockchain
chain Display blockchain information
chain blocks --count N Show last N blocks
validate Verify chain integrity
export --output FILE Export blockchain to JSON
import --input FILE Import blockchain from JSON

Wallet Operations

Command Description
wallet new Create a new wallet
wallet new --label NAME Create wallet with label
wallet list List all wallets
wallet balance --address ADDR Check wallet balance

Mining & Transactions

Command Description
mine --address ADDR Mine a single block
mine --address ADDR --count N Mine N blocks
send --from ADDR --to ADDR --amount N Send coins
mempool Show pending transactions

Examples

# Initialize with custom difficulty (higher = harder)
blockchain init --difficulty 16

# Mine 10 blocks
blockchain mine --address 1ABC123... --count 10

# Send 25 coins
blockchain send --from 1ABC123... --to 1XYZ789... --amount 25

# Export blockchain backup
blockchain export --output backup.json

P2P Networking

Command Description
node start Start P2P node on default port (8333)
node start --port PORT Start node on custom port
node start --peers HOST:PORT Start and connect to peers
node status Show node connection info
# Terminal 1: Start first standalone P2P node
RUST_LOG=info blockchain node start --port 8334

# Terminal 2: Start second node and connect
RUST_LOG=info blockchain node start --port 8335 --peers 127.0.0.1:8334

REST API

Command Description
api start Start REST API on default port (3000)
api start --port PORT Start on custom port
api start --p2p-port PORT NEW: Enable embedded P2P node
api start --peers HOST:PORT Connect to P2P network
# API-only mode (no P2P)
blockchain api start --port 3000

# ๐Ÿ†• API + P2P mode (blocks mined via UI broadcast to network!)
RUST_LOG=info blockchain api start --port 3000 --p2p-port 8333 --peers 127.0.0.1:8334

# Test endpoints with curl
curl http://localhost:3000/api/chain
curl http://localhost:3000/api/wallets/1ABC.../balance
curl -X POST http://localhost:3000/api/mine -H "Content-Type: application/json" -d '{"miner_address": "1ABC..."}'

๐Ÿ’ก Tip: With --p2p-port, blocks mined via the Web UI are automatically broadcast to all connected P2P nodes in real-time!

Web UI

The REST API server includes an embedded Web UI built with SvelteKit + shadcn-svelte.

Page Features
Dashboard Chain stats, recent blocks, real-time updates
Blocks Block explorer with details
Search Global search across blocks, transactions, addresses, tokens
Wallets Create/list wallets, view balances
Mining Mine blocks with reward display
Contracts Deploy, list, and call contracts
Multisig Create M-of-N wallets, view pending transactions
Tokens Create ERC-20 tokens, transfer, check balances
Mempool View pending transactions
# Start the server and open the Web UI
blockchain api start --port 3000
# Visit http://localhost:3000

WebSocket

Connect to /ws for real-time updates. Events are JSON with the following types:

Event Description
Connected Connection established
BlockMined New block mined (includes block info and reward)
TransactionAdded Transaction added to mempool
ChainUpdated Chain state changed
// JavaScript example
const ws = new WebSocket('ws://localhost:3000/ws');
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data.type, data.data);
};

Smart Contracts

See CONTRACT_EXAMPLES.md for detailed examples and assembly code.

Command Description
contract deploy --file FILE Deploy contract from .asm file
contract call --address ADDR --args ARGS Call contract
contract list List all deployed contracts
contract info --address ADDR Show contract details
# Create a simple add contract (examples/add.asm):
# ARG 0
# ARG 1  
# ADD
# RETURN

# Deploy it
blockchain contract deploy --file examples/add.asm

# Call it with args
blockchain contract call --address 0x... --args "10,25"
# Returns: 35

Multi-Signature Wallets

Create wallets requiring M-of-N signatures to spend funds:

# Create a 2-of-3 multisig wallet via API
curl -X POST http://localhost:3000/api/multisig \
  -H "Content-Type: application/json" \
  -d '{
    "threshold": 2,
    "signers": ["<pubkey1>", "<pubkey2>", "<pubkey3>"],
    "label": "Team Treasury"
  }'

# Response includes the multisig address (starts with '3')
# {"address": "3ABC...", "threshold": 2, "signer_count": 3, ...}

# Propose a transaction
curl -X POST http://localhost:3000/api/multisig/3ABC.../propose \
  -H "Content-Type: application/json" \
  -d '{"to": "1RECIPIENT...", "amount": 100}'

# Sign with each authorized wallet (need M signatures)
curl -X POST http://localhost:3000/api/multisig/3ABC.../sign \
  -H "Content-Type: application/json" \
  -d '{"tx_id": "TX_ID", "signer_pubkey": "<pubkey1>", "signature": "<sig1>"}'

Tokens (ERC-20 Style)

Create and manage fungible tokens with a standard ERC-20 interface:

API Endpoint Description
POST /api/tokens Create new token
GET /api/tokens List all tokens
GET /api/tokens/{addr} Get token info
GET /api/tokens/{addr}/balance/{holder} Get balance
POST /api/tokens/{addr}/transfer Transfer tokens
POST /api/tokens/{addr}/approve Approve spender
GET /api/tokens/{addr}/allowance Check allowance
POST /api/tokens/{addr}/transferFrom Delegated transfer
# Create a new token
curl -X POST http://localhost:3000/api/tokens \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My Token",
    "symbol": "MTK",
    "decimals": 18,
    "total_supply": "1000000",
    "creator": "1ABC..."
  }'

# Check token balance
curl http://localhost:3000/api/tokens/0xTOKEN.../balance/1ABC...

# Transfer tokens
curl -X POST http://localhost:3000/api/tokens/0xTOKEN.../transfer \
  -H "Content-Type: application/json" \
  -d '{"from": "1ABC...", "to": "1DEF...", "amount": "1000"}'

# Approve a spender
curl -X POST http://localhost:3000/api/tokens/0xTOKEN.../approve \
  -H "Content-Type: application/json" \
  -d '{"owner": "1ABC...", "spender": "1DEF...", "amount": "5000"}'

Token vs Coins:

Asset Description
Coins Native blockchain currency (from mining)
Tokens Custom assets created via /api/tokens

๐Ÿ—๏ธ Architecture

src/
โ”œโ”€โ”€ main.rs              # CLI entry point
โ”œโ”€โ”€ lib.rs               # Library exports
โ”‚
โ”œโ”€โ”€ core/                # ๐Ÿงฑ Core Blockchain
โ”‚   โ”œโ”€โ”€ block.rs         # Block structure & PoW mining
โ”‚   โ”œโ”€โ”€ blockchain.rs    # Chain management & validation
โ”‚   โ””โ”€โ”€ transaction.rs   # UTXO transactions, signatures & on-chain ops
โ”‚
โ”œโ”€โ”€ crypto/              # ๐Ÿ” Cryptography
โ”‚   โ”œโ”€โ”€ hash.rs          # SHA-256 hashing utilities
โ”‚   โ”œโ”€โ”€ keys.rs          # ECDSA key management
โ”‚   โ””โ”€โ”€ merkle.rs        # Merkle tree implementation
โ”‚
โ”œโ”€โ”€ wallet/              # ๐Ÿ‘› Wallet
โ”‚   โ””โ”€โ”€ wallet.rs        # Key storage & tx creation
โ”‚
โ”œโ”€โ”€ mining/              # โ›๏ธ Mining
โ”‚   โ”œโ”€โ”€ miner.rs         # Block mining engine
โ”‚   โ””โ”€โ”€ mempool.rs       # Transaction pool
โ”‚
โ”œโ”€โ”€ network/             # ๐ŸŒ P2P Networking
โ”‚   โ”œโ”€โ”€ message.rs       # Protocol messages
โ”‚   โ”œโ”€โ”€ node.rs          # Main P2P node
โ”‚   โ”œโ”€โ”€ peer.rs          # Peer management
โ”‚   โ”œโ”€โ”€ server.rs        # TCP server & codec
โ”‚   โ””โ”€โ”€ sync.rs          # Chain synchronization
โ”‚
โ”œโ”€โ”€ api/                 # ๐Ÿš€ REST API
โ”‚   โ”œโ”€โ”€ handlers.rs      # Endpoint handlers
โ”‚   โ””โ”€โ”€ routes.rs        # Route configuration
โ”‚
โ”œโ”€โ”€ contract/            # ๐Ÿ“œ Smart Contracts
โ”‚   โ”œโ”€โ”€ opcodes.rs       # VM instruction set
โ”‚   โ”œโ”€โ”€ vm.rs            # Stack-based VM
โ”‚   โ”œโ”€โ”€ contract.rs      # Contract management
โ”‚   โ””โ”€โ”€ compiler.rs      # Assembly compiler
โ”‚
โ”œโ”€โ”€ storage/             # ๐Ÿ’พ Storage
โ”‚   โ””โ”€โ”€ persistence.rs   # Save/load blockchain
โ”‚
โ””โ”€โ”€ cli/                 # ๐Ÿ–ฅ๏ธ CLI
    โ””โ”€โ”€ commands.rs      # Command handlers

๐Ÿ“š API

Library Usage

use mini_blockchain::{Blockchain, Wallet, Miner, BLOCK_REWARD};

fn main() {
    // Create a blockchain with custom difficulty
    let mut blockchain = Blockchain::with_difficulty(8);
    
    // Create wallets
    let alice = Wallet::new();
    let bob = Wallet::new();
    
    println!("Alice: {}", alice.address());
    println!("Bob: {}", bob.address());
    
    // Mine blocks to earn coins
    let miner = Miner::new(&alice.address());
    for _ in 0..3 {
        let (block, stats) = miner.mine_block(&mut blockchain, vec![]).unwrap();
        println!("Mined block {} in {}ms", block.index, stats.time_ms);
    }
    
    // Check balance
    println!("Alice's balance: {} coins", alice.balance(&blockchain));
    
    // Create a transaction
    let tx = alice.create_transaction(&bob.address(), 50, &blockchain).unwrap();
    println!("Transaction: {}", tx.id);
    
    // Validate chain
    assert!(blockchain.is_valid());
}

โš™๏ธ Configuration

Setting Default Description
difficulty 16 Mining difficulty (leading zero bits)
block_reward 50 Coins per mined block
target_block_time 10s Target time between blocks
difficulty_adjustment 10 blocks Blocks between difficulty changes

๐Ÿงช Testing

# Run all tests
cargo test

# Run with output
cargo test -- --nocapture

# Run specific module tests
cargo test crypto::
cargo test core::blockchain::

Test Coverage:

  • โœ… 52 unit tests
  • โœ… Block creation & mining
  • โœ… Chain validation
  • โœ… Transaction signing
  • โœ… UTXO tracking
  • โœ… Wallet operations
  • โœ… Storage persistence
  • โœ… Network message codec
  • โœ… P2P node creation
  • โœ… Smart contract VM
  • โœ… Contract deployment & execution

๐Ÿ“Š Performance

Benchmarks on Intel i7 (single-threaded):

Difficulty Avg. Attempts Avg. Time
8 bits ~256 < 1ms
16 bits ~65,536 ~50ms
20 bits ~1M ~500ms
24 bits ~16M ~8s

๐Ÿ›ฃ๏ธ Roadmap

โœ… Completed

  • Core blockchain with PoW
  • ECDSA transaction signing
  • UTXO model
  • Wallet management
  • CLI interface
  • Persistence layer
  • P2P networking
  • REST API
  • Smart contracts (VM, compiler, storage)
  • Web UI (SvelteKit + shadcn-svelte)
  • Contract deployment via Web UI
  • WebSocket for real-time updates
  • Multi-signature transactions
  • Token standards (ERC-20 style)
  • Block explorer search

๐Ÿ”ฎ Future Ideas

  • Mobile-responsive UI
  • Docker deployment

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


Made with โค๏ธ in Rust

About

A robust, full-stack blockchain engine built in Rust. Features a custom VM for smart contracts with real gas economics, Proof-of-Work consensus, UTXO transactions, multisig wallets, and a real-time SvelteKit block explorer.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors