network.rs - P2P Protocol

The network module implements direct TCP-based peer-to-peer communication for Bunkercoin, complementing the HTTP interface with real-time blockchain and transaction synchronization. This dual-protocol approach provides both firewall-friendly HTTP and efficient TCP connectivity.

TCP Server Implementation

// src/network.rs (lines 7-25)
pub async fn start_tcp_server(port: u16, blockchain: Arc<Mutex<Vec<Block>>>) -> anyhow::Result<()> {
    let listener = TcpListener::bind(format!("0.0.0.0:{}", port)).await?;
    println!("TCP P2P server listening on port {}", port);
    
    loop {
        let (socket, addr) = listener.accept().await?;
        println!("New TCP connection from {}", addr);
        
        let blockchain_clone = Arc::clone(&blockchain);
        tokio::spawn(async move {
            if let Err(e) = handle_connection(socket, blockchain_clone).await {
                eprintln!("Connection error with {}: {}", addr, e);
            }
        });
    }
}

Async TCP Handling: The server uses Tokio's async runtime to handle multiple concurrent connections efficiently. Each connection spawns an independent task, enabling simultaneous peer communication without blocking.

Connection Protocol

Message Format

Bidirectional Communication

Peer Connection Management

Outbound Connection Establishment

Connection Lifecycle

Phase
Operation
Purpose

Discovery

Connect to known peer addresses

Establish network topology

Handshake

Exchange protocol version info

Ensure compatibility

Synchronization

Request chain and mempool data

Achieve network consensus

Real-time Updates

Push new blocks/transactions

Maintain network coherence

Message Types and Protocols

Blockchain Synchronization

Transaction Broadcasting

Integration with HTTP Interface

The TCP P2P system complements the HTTP interface:

Protocol Comparison

Feature
TCP P2P
HTTP Interface

Connection Model

Persistent connections

Stateless requests

Firewall Traversal

Requires port forwarding

Works through NAT/firewalls

Real-time Updates

Push notifications

Polling required

Resource Usage

Lower latency

Higher compatibility

Radio Suitability

Requires stable connections

Better for intermittent links

Dual Protocol Benefits

  • HTTP for discovery: Initial peer contact and firewall traversal

  • TCP for streaming: Real-time block and transaction propagation

  • Fallback capability: Either protocol can handle full synchronization

  • Flexibility: Nodes can use optimal protocol for their environment

Error Handling and Resilience

Connection Failure Recovery

Message Validation

Radio Environment Considerations

TCP Challenges in Radio Networks

  • Connection stability: Radio links may have frequent disconnections

  • NAT traversal: Radio networks often use complex routing

  • Bandwidth limitations: TCP overhead may be significant on slow links

  • Latency variation: HF propagation introduces variable delays

Optimization Strategies

Performance and Scalability

Concurrent Connection Handling

The network module uses async/await patterns for efficient resource utilization:

Memory Management

  • Streaming parsing: JSON messages parsed incrementally

  • Connection pooling: Reuse connections when possible

  • Bounded buffers: Prevent memory exhaustion from malicious peers

Future Enhancements

Planned Network Features

  • Peer discovery protocol: Automatic peer finding and topology mapping

  • Connection encryption: TLS/SSL support for secure communication

  • Bandwidth adaptation: Dynamic protocol selection based on link quality

  • Mesh routing: Multi-hop communication for radio networks

Radio-Specific Protocols

  • AX.25 integration: Native packet radio protocol support

  • VARA modem support: Integration with VARA HF/FM modems

  • JS8Call messaging: Direct integration with JS8Call for HF communication

  • APRS gateway: Bridge to amateur radio APRS networks

Last updated