Files
zigp2p/docs/GUIDE.md

31 KiB

User Guide

Comprehensive guide for using the P2P file sharing library. This guide covers tutorials, best practices, and real-world usage patterns.

Table of Contents

Getting Started

Installation and Setup

  1. Install Zig: Ensure you have Zig 0.11.0 or later

    # macOS (using Homebrew)
    brew install zig
    
    # Ubuntu/Debian
    sudo apt install zig
    
    # Windows (using Chocolatey)
    choco install zig
    
  2. Clone the repository:

    git clone https://github.com/your-username/p2p-library.git
    cd p2p-library
    
  3. Build the library:

    zig build
    
  4. Run tests:

    zig build test
    

First Program

Create hello_p2p.zig:

const std = @import("std");
const core = @import("core");
const p2p = @import("p2p");

pub fn main() !void {
    std.debug.print("Hello, P2P World!\n", .{});

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Create a simple address
    const addr = try core.Address.parse("127.0.0.1:8080");
    std.debug.print("Created address: {s}\n", .{try addr.toString()});

    // Create a stream buffer
    var buffer = try core.StreamBuffer.init(allocator, 1024);
    defer buffer.deinit();

    // Write some data
    try buffer.write("Hello, P2P Buffer!");

    std.debug.print("Buffer contains: {s}\n", .{buffer.base.data[0..buffer.base.write_pos]});
}

Build and run:

zig build-exe hello_p2p.zig
./hello_p2p

Basic Concepts

Network Architecture

The P2P library uses a layered architecture:

┌─────────────────────┐
│   Application Layer │
├─────────────────────┤
│   Protocol Layer    │
├─────────────────────┤
│   Network Layer     │
├─────────────────────┤
│   Transport Layer   │
├─────────────────────┤
│   Core Layer        │
└─────────────────────┘

Key Components

  1. Core Layer: Basic networking primitives (Address, Socket, Buffer, Connection)
  2. Network Layer: P2P networking (Node, Discovery, Routing, Topology)
  3. Protocol Layer: Message handling (Message, Handler, Router, Serializer)
  4. Files Layer: File sharing (Hash, File, Transfer, Manager)
  5. Application Layer: Your application code

Data Flow

Application → Handler → Router → Network → Transport → Wire
     ↑                                     ↓
Application ← Handler ← Router ← Network ← Transport ← Wire

Threading Model

The library supports both synchronous and asynchronous operation:

  • Synchronous: Simple, blocking operations
  • Asynchronous: Non-blocking, event-driven operations
  • Thread-Safe: All public APIs are thread-safe

Tutorial: Building a Simple P2P Application

Step 1: Basic Server Setup

Create simple_server.zig:

const std = @import("std");
const core = @import("core");
const p2p = @import("p2p");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    std.debug.print("Starting Simple P2P Server...\n", .{});

    // Configure the server
    var config = p2p.P2PConfig.default();
    config.network.listen_port = 8080;
    config.network.max_connections = 100;
    config.network.connection_timeout = 30000;

    // Initialize P2P library
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();

    std.debug.print("P2P library initialized\n", .{});

    // Start the service
    try p2p_instance.start();
    std.debug.print("P2P service started\n", .{});

    // Start listening for connections
    const listen_addr = try core.Address.parse("0.0.0.0:8080");
    try p2p_instance.startListening(listen_addr);

    // Keep running
    while (p2p_instance.isOperational()) {
        try p2p_instance.update();
        _ = p2p_instance.processAllEvents();
        std.time.sleep(100 * std.time.ns_per_ms);
    }
}

Step 2: Create Configuration

Create server.json:

{
  "network": {
    "listen_address": "0.0.0.0",
    "listen_port": 8080,
    "max_connections": 100,
    "connection_timeout": 30000,
    "keep_alive_interval": 30000,
    "bootstrap_nodes": []
  },
  "transport": {
    "tcp_enabled": true,
    "udp_enabled": true,
    "tcp_buffer_size": 4096,
    "enable_nagle": false,
    "tcp_backlog": 128
  },
  "security": {
    "enable_encryption": true,
    "enable_signatures": true,
    "key_rotation_interval": 86400
  },
  "performance": {
    "worker_threads": 4,
    "max_message_queue": 1000,
    "buffer_pool_size": 256
  }
}

Step 3: Build and Run

zig build-exe simple_server.zig
./simple_server

Step 4: Create Client

Create simple_client.zig:

const std = @import("std");
const core = @import("core");
const protocol = @import("protocol");
const p2p = @import("p2p");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    std.debug.print("Starting Simple P2P Client...\n", .{});

    // Configure client
    var config = p2p.P2PConfig.default();
    config.network.listen_port = 0; // Use any available port

    // Initialize P2P library
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();

    // Start the client
    try p2p_instance.start();

    // Connect to server
    const server_addr = try core.Address.parse("127.0.0.1:8080");
    const peer_id = try p2p_instance.connectToPeer(server_addr);
    std.debug.print("Connected to server, peer ID: {x}\n", .{peer_id.bytes[0..4].*});

    // Send custom message
    const msg_id = try p2p_instance.sendMessage(peer_id, 0x01, "Hello from client!");
    std.debug.print("Sent message, ID: {}\n", .{msg_id});

    // Wait for responses and process events
    var i: u32 = 0;
    while (i < 10) : (i += 1) {
        try p2p_instance.update();
        _ = p2p_instance.processAllEvents();
        std.time.sleep(100 * std.time.ns_per_ms);
    }

    // Disconnect
    try p2p_instance.disconnectPeer(peer_id);
    try p2p_instance.stop();
    std.debug.print("Client stopped\n", .{});
}

Tutorial: File Sharing Application

Step 1: File Sharing Server

Create file_server.zig:

const std = @import("std");
const core = @import("core");
const files = @import("files");
const p2p = @import("p2p");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    std.debug.print("Starting File Sharing P2P Server...\n", .{});

    // Configure the server with file sharing enabled
    var config = p2p.P2PConfig.high_performance();
    config.network.listen_port = 8080;
    config.network.max_connections = 1000;
    config.network.connection_timeout = 60000;
    config.file_sharing.enable_upload = true;
    config.file_sharing.enable_download = true;

    // Initialize P2P library
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();

    // Start the service
    try p2p_instance.start();
    std.debug.print("P2P service started\n", .{});

    // Start listening for connections
    const listen_addr = try core.Address.parse("0.0.0.0:8080");
    try p2p_instance.startListening(listen_addr);

    // Share example files
    try shareFiles(&p2p_instance, allocator);

    std.debug.print("File sharing server started\n", .{});

    // Main event loop
    while (p2p_instance.isOperational()) {
        try p2p_instance.update();
        _ = p2p_instance.processAllEvents();
        std.time.sleep(100 * std.time.ns_per_ms);
    }
}

fn shareFiles(p2p_instance: *p2p.P2P, allocator: std.mem.Allocator) !void {
    // Share example files
    const file_paths = &[_][]const u8{
        "document.pdf",
        "image.jpg",
        "video.mp4",
        "archive.zip",
    };

    for (file_paths) |file_path| {
        // Check if file exists
        const file = std.fs.cwd().openFile(file_path, .{}) catch {
            std.debug.print("File not found: {s}\n", .{file_path});
            continue;
        };
        file.close();

        // Add file for sharing
        const session_id = p2p_instance.addFile(file_path) catch |err| {
            std.debug.print("Failed to add file {s}: {}\n", .{ file_path, err });
            continue;
        };

        // Start sharing the file
        try p2p_instance.startSharing(session_id);

        std.debug.print("Shared file: {s} (session: {})\n", .{ file_path, session_id });
    }
}

Step 2: File Sharing Client

Create file_client.zig:

const std = @import("std");
const core = @import("core");
const files = @import("files");
const p2p = @import("p2p");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    std.debug.print("Starting File Sharing P2P Client...\n", .{});

    // Configure client
    var config = p2p.P2PConfig.default();
    config.network.listen_port = 0; // Use any available port
    config.network.max_connections = 100;
    config.file_sharing.enable_download = true;

    // Initialize P2P library
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();

    // Register event callback to monitor downloads
    try p2p_instance.registerCallback(eventCallback, null);

    // Start service
    try p2p_instance.start();

    // Connect to server
    const server_addr = try core.Address.parse("127.0.0.1:8080");
    const peer_id = try p2p_instance.connectToPeer(server_addr);
    std.debug.print("Connected to server\n", .{});

    // In a real implementation, you would need file metadata
    // For this example, we'll demonstrate the concept
    std.debug.print("Ready to download files\n", .{});

    // Main event loop
    var i: u32 = 0;
    while (i < 100 and p2p_instance.isOperational()) : (i += 1) {
        try p2p_instance.update();
        _ = p2p_instance.processAllEvents();
        std.time.sleep(100 * std.time.ns_per_ms);
    }

    try p2p_instance.disconnectPeer(peer_id);
    try p2p_instance.stop();
}

fn eventCallback(event: p2p.P2PEvent) void {
    switch (event.event_type) {
        .file_download_started => {
            std.debug.print("Download started\n", .{});
        },
        .file_download_completed => {
            std.debug.print("Download completed!\n", .{});
        },
        .file_download_failed => {
            std.debug.print("Download failed\n", .{});
        },
        else => {},
    }
}

Advanced Usage Patterns

Custom Message Types

Define and send custom message types:

const std = @import("std");
const core = @import("core");
const protocol = @import("protocol");
const p2p = @import("p2p");

// Custom message type identifiers
pub const CustomMessageType = enum(u8) {
    chat_message = 0x80,
    file_request = 0x81,
    file_response = 0x82,
    status_update = 0x83,
};

pub fn sendChatMessage(p2p_instance: *p2p.P2P, peer_id: network.PeerId, message: []const u8) !void {
    const msg_id = try p2p_instance.sendMessage(
        peer_id,
        @intFromEnum(CustomMessageType.chat_message),
        message
    );
    std.debug.print("Sent chat message, ID: {}\n", .{msg_id});
}

Event-Driven Message Handling

Handle custom messages using the event system:

const std = @import("std");
const core = @import("core");
const network = @import("network");
const p2p = @import("p2p");

fn messageEventCallback(event: p2p.P2PEvent) void {
    switch (event.event_type) {
        .message_received => {
            const msg_data = event.data.message_received;

            // Handle different message types
            switch (msg_data.message_type) {
                0x80 => { // Chat message
                    std.debug.print("Chat from peer: {s}\n", .{msg_data.data});
                },
                0x81 => { // File request
                    std.debug.print("File request received\n", .{});
                    // Handle file request
                },
                else => {
                    std.debug.print("Unknown message type: {}\n", .{msg_data.message_type});
                },
            }
        },
        .peer_connected => {
            std.debug.print("New peer connected\n", .{});
        },
        .peer_disconnected => {
            std.debug.print("Peer disconnected: {s}\n", .{event.data.peer_disconnected.reason});
        },
        else => {},
    }
}

Complete Event-Driven Application

Build a complete event-driven P2P application:

const std = @import("std");
const core = @import("core");
const network = @import("network");
const p2p = @import("p2p");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Configure P2P instance
    var config = p2p.P2PConfig.default();
    config.network.listen_port = 8080;

    // Initialize P2P
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();

    // Register event callback
    try p2p_instance.registerCallback(comprehensiveEventHandler, null);

    // Start P2P service
    try p2p_instance.start();

    // Start listening
    const listen_addr = try core.Address.parse("0.0.0.0:8080");
    try p2p_instance.startListening(listen_addr);

    std.debug.print("Event-driven P2P application running\n", .{});

    // Main event loop
    while (p2p_instance.isOperational()) {
        // Update network state
        try p2p_instance.update();

        // Process all pending events
        _ = p2p_instance.processAllEvents();

        // Print statistics periodically
        const stats = p2p_instance.getStats();
        if (stats.uptime_seconds % 10 == 0) {
            std.debug.print("Active connections: {}, Messages: {}/{}\n", .{
                stats.active_connections,
                stats.messages_sent,
                stats.messages_received,
            });
        }

        std.time.sleep(100 * std.time.ns_per_ms);
    }
}

fn comprehensiveEventHandler(event: p2p.P2PEvent) void {
    switch (event.event_type) {
        .library_started => {
            std.debug.print("P2P library started\n", .{});
        },
        .peer_connected => {
            const data = event.data.peer_connected;
            std.debug.print("Peer connected: {x}\n", .{data.peer_id.bytes[0..4].*});
        },
        .message_received => {
            const data = event.data.message_received;
            std.debug.print("Message received (type {}): {s}\n", .{
                data.message_type,
                data.data,
            });
        },
        .file_shared => {
            const data = event.data.file_shared;
            std.debug.print("File shared: {s}\n", .{data.file_path});
        },
        .file_download_completed => {
            const data = event.data.file_download_completed;
            std.debug.print("Download completed: {s}\n", .{data.file_path});
        },
        else => {},
    }
}

Statistics and Monitoring

Monitor P2P library performance and health:

const std = @import("std");
const p2p = @import("p2p");

pub fn monitorP2P(p2p_instance: *p2p.P2P, allocator: std.mem.Allocator) !void {
    while (p2p_instance.isOperational()) {
        const stats = p2p_instance.getStats();

        // Print formatted statistics
        const stats_str = try stats.formatString(allocator);
        defer allocator.free(stats_str);
        std.debug.print("{s}\n", .{stats_str});

        // Check for errors
        if (stats.errors_total > 0 and stats.last_error != null) {
            std.debug.print("Last error: {}\n", .{stats.last_error.?});
        }

        // Monitor bandwidth
        const download_mb_s = @as(f64, @floatFromInt(stats.current_download_rate)) / (1024.0 * 1024.0);
        const upload_mb_s = @as(f64, @floatFromInt(stats.current_upload_rate)) / (1024.0 * 1024.0);

        if (download_mb_s > 50.0 or upload_mb_s > 50.0) {
            std.debug.print("High bandwidth usage detected!\n", .{});
        }

        std.time.sleep(5 * std.time.ns_per_sec);
    }
}

Best Practices

Memory Management

  1. Always use proper allocators:

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();
    
  2. Release resources properly:

    const core = @import("core");
    
    var connection = try core.Connection.init(.tcp, config, allocator);
    defer connection.deinit();
    
    var buffer = try core.StreamBuffer.init(allocator, 1024);
    defer buffer.deinit();
    
  3. Free allocated memory:

    const data = try allocator.alloc(u8, size);
    defer allocator.free(data);
    

Error Handling

  1. Handle all errors explicitly:

    const core = @import("core");
    
    const addr = core.Address.parse("127.0.0.1:8080") catch |err| {
        switch (err) {
            core.Error.InvalidAddress => {
                std.debug.print("Invalid address format\n", .{});
                return err;
            },
            else => return err,
        }
    };
    
  2. Use proper error propagation:

    const core = @import("core");
    
    fn connectToPeer(addr: core.Address, config: core.ConnectionConfig, allocator: std.mem.Allocator) !core.Connection {
        const connection = try core.Connection.init(.tcp, config, allocator);
        errdefer connection.deinit(); // Cleanup on error
    
        try connection.connect(addr);
        return connection;
    }
    
  3. Implement retry logic:

    const core = @import("core");
    const network = @import("network");
    const p2p = @import("p2p");
    
    fn connectWithRetry(
        p2p_instance: *p2p.P2P,
        addr: core.Address,
        max_retries: u32
    ) !network.PeerId {
        var retries: u32 = 0;
    
        while (retries < max_retries) : (retries += 1) {
            const peer_id = p2p_instance.connectToPeer(addr) catch |err| {
                if (retries == max_retries - 1) return err;
                std.debug.print("Retry {}/{} after error\n", .{retries + 1, max_retries});
                std.time.sleep(std.time.ns_per_sec * @as(u64, retries + 1));
                continue;
            };
    
            return peer_id;
        }
    
        return error.MaxRetriesExceeded;
    }
    

Connection Management

  1. Monitor connections:

    const core = @import("core");
    const network = @import("network");
    const p2p = @import("p2p");
    
    pub fn monitorConnections(p2p_instance: *p2p.P2P) void {
        const stats = p2p_instance.getStats();
    
        std.debug.print("Connection Statistics:\n", .{});
        std.debug.print("  Active: {}\n", .{stats.active_connections});
        std.debug.print("  Total: {}\n", .{stats.total_connections});
        std.debug.print("  Messages sent: {}\n", .{stats.messages_sent});
        std.debug.print("  Messages received: {}\n", .{stats.messages_received});
    }
    
  2. Graceful disconnect:

    const network = @import("network");
    const p2p = @import("p2p");
    
    pub fn disconnectPeerGracefully(p2p_instance: *p2p.P2P, peer_id: network.PeerId) !void {
        std.debug.print("Disconnecting peer: {x}\n", .{peer_id.bytes[0..4].*});
    
        // Disconnect the peer
        try p2p_instance.disconnectPeer(peer_id);
    
        std.debug.print("Peer disconnected successfully\n", .{});
    }
    

Performance Optimization

  1. Configure for performance:

    const p2p = @import("p2p");
    
    // Use high-performance configuration
    const config = p2p.P2PConfig.high_performance();
    
    // Or customize specific settings
    var custom_config = p2p.P2PConfig.default();
    custom_config.network.max_connections = 1000;
    custom_config.network.max_bandwidth = 100 * 1024 * 1024; // 100 MB/s
    custom_config.file_sharing.piece_size = 256 * 1024; // 256 KB pieces
    
  2. Monitor performance:

    const p2p = @import("p2p");
    
    pub fn checkPerformance(p2p_instance: *p2p.P2P) void {
        const stats = p2p_instance.getStats();
    
        // Calculate bandwidth in MB/s
        const download_mbps = @as(f64, @floatFromInt(stats.current_download_rate)) / (1024.0 * 1024.0);
        const upload_mbps = @as(f64, @floatFromInt(stats.current_upload_rate)) / (1024.0 * 1024.0);
    
        std.debug.print("Bandwidth: {d:.2} MB/s down, {d:.2} MB/s up\n", .{
            download_mbps, upload_mbps
        });
    }
    

Security Best Practices

  1. Enable encryption:

    const p2p = @import("p2p");
    
    var config = p2p.P2PConfig.default();
    config.protocol.enable_encryption = true;
    
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();
    
  2. Validate message sizes:

    const p2p = @import("p2p");
    
    // Configure message size limits
    var config = p2p.P2PConfig.default();
    config.protocol.max_message_size = 64 * 1024; // 64 KB max
    
    // The library will automatically reject oversized messages
    
  3. Monitor for anomalies:

    const p2p = @import("p2p");
    
    pub fn detectAnomalies(p2p_instance: *p2p.P2P) void {
        const stats = p2p_instance.getStats();
    
        // Check for excessive errors
        if (stats.errors_total > 100) {
            std.debug.print("Warning: High error count detected\n", .{});
        }
    
        // Check for abnormal bandwidth
        const bandwidth = stats.current_download_rate + stats.current_upload_rate;
        if (bandwidth > 1024 * 1024 * 1024) { // > 1 GB/s
            std.debug.print("Warning: Abnormal bandwidth usage\n", .{});
        }
    }
    

Performance Optimization

Configuration Tuning

  1. Choose the right configuration preset:

    const p2p = @import("p2p");
    
    // Default configuration (balanced)
    const default_config = p2p.P2PConfig.default();
    
    // High performance (for servers with good resources)
    const high_perf = p2p.P2PConfig.high_performance();
    
    // Low resource (for embedded or resource-constrained devices)
    const low_res = p2p.P2PConfig.low_resource();
    
  2. Customize for your use case:

    const p2p = @import("p2p");
    
    var config = p2p.P2PConfig.default();
    
    // For file sharing server
    config.network.max_connections = 1000;
    config.network.connection_timeout = 60000; // 60 seconds
    config.file_sharing.piece_size = 256 * 1024; // 256 KB pieces
    config.file_sharing.max_bandwidth_upload = 50 * 1024 * 1024; // 50 MB/s
    
    // For file sharing client
    config.file_sharing.max_bandwidth_download = 100 * 1024 * 1024; // 100 MB/s
    config.file_sharing.enable_upload = true;
    config.file_sharing.enable_download = true;
    

Monitoring and Profiling

  1. Track performance metrics:
    const p2p = @import("p2p");
    
    pub fn profilePerformance(p2p_instance: *p2p.P2P) void {
        const stats = p2p_instance.getStats();
    
        std.debug.print("Performance Metrics:\n", .{});
        std.debug.print("  Uptime: {} seconds\n", .{stats.uptime_seconds});
        std.debug.print("  Active connections: {}\n", .{stats.active_connections});
        std.debug.print("  Messages/sec: {d:.2}\n", .{
            @as(f64, @floatFromInt(stats.messages_sent + stats.messages_received)) /
            @as(f64, @floatFromInt(@max(stats.uptime_seconds, 1)))
        });
        std.debug.print("  Bandwidth: {d:.2} MB/s\n", .{
            @as(f64, @floatFromInt(stats.current_download_rate + stats.current_upload_rate)) /
            (1024.0 * 1024.0)
        });
    }
    

Security Considerations

Encryption

Enable encryption in configuration:

const p2p = @import("p2p");

var config = p2p.P2PConfig.default();
config.protocol.enable_encryption = true;

var p2p_instance = try p2p.P2P.init(allocator, config);
defer p2p_instance.deinit();

Message Validation

Set appropriate size limits:

const p2p = @import("p2p");

var config = p2p.P2PConfig.default();
// Limit message size to prevent DoS attacks
config.protocol.max_message_size = 64 * 1024; // 64 KB
// Set reasonable timeout
config.protocol.message_timeout = 10000; // 10 seconds

var p2p_instance = try p2p.P2P.init(allocator, config);
defer p2p_instance.deinit();

Connection Limits

Limit connections to prevent resource exhaustion:

const p2p = @import("p2p");

var config = p2p.P2PConfig.default();
config.network.max_connections = 500; // Limit total connections
config.network.connection_timeout = 30000; // 30 second timeout

var p2p_instance = try p2p.P2P.init(allocator, config);
defer p2p_instance.deinit();

NAT Traversal

The library automatically discovers your public address and maps ports through NAT gateways. No manual configuration is needed for most networks — the system tries multiple strategies in order and uses the first one that succeeds.

Address Discovery Priority

Priority Method Protocol How It Works
1 Explicit IP Manual --public-ip flag (for known static IPs or Docker)
2 NAT-PMP RFC 6886 2-packet UDP exchange with the gateway on port 5351
3 UPnP IGD SSDP + SOAP Multicast discovery (239.255.255.250:1900), then HTTP/SOAP for port mapping
4 IP Reflection DHT-bundled Every DHT response includes the requester's observed address (zero-infrastructure STUN)

Each method both discovers the external IP and requests a port mapping (where applicable). If a method fails (e.g., router doesn't support NAT-PMP), the next one is tried automatically.

What Happens Automatically

When a P2P node starts and needs to advertise a reachable address (e.g., for MWP hole punching):

  1. NAT-PMP — Sends a UDP request to the default gateway. If the router supports NAT-PMP (Apple AirPort, many consumer routers), the external IP and port mapping are returned in ~10ms.

  2. UPnP IGD — If NAT-PMP fails, sends an SSDP M-SEARCH multicast to find UPnP-enabled routers, fetches the XML device description, then uses SOAP to query the external IP and request a port mapping. Works on most consumer routers.

  3. IP Reflection — If both NAT-PMP and UPnP fail (e.g., on a VPS or network without gateway support), the node learns its public IP from DHT peers. Every DHT response includes an observed_addr field containing the sender's view of the requester's IP. Multiple observers build consensus for reliability.

When You Might Need Manual Configuration

  • Carrier-grade NAT (CGNAT): Double-NAT scenarios where your router's "external" IP is still private. Port mapping succeeds but the mapped address isn't publicly reachable.
  • Strict corporate firewalls: UDP may be blocked entirely. The library is UDP-only (no TCP fallback).
  • Symmetric NAT: Port mapping works, but hole punching may fail because the NAT assigns different external ports per destination.

In these cases, use --public-ip with a known reachable address, or set up a relay node on a public server.

Implementation Details

Component Source File
NAT-PMP client src/network/nat_pmp.zig
UPnP IGD client src/network/upnp.zig
IP Reflection Built into DHT responses (src/p2p/dht.zig)
Address discovery orchestration src/p2p/p2p.zig (tryNatPmpDiscovery, tryUpnpDiscovery)
Docker E2E tests docker-tests/nat-pmp/, docker-tests/upnp/

Troubleshooting

Common Issues

  1. Connection timeouts:

    • Check firewall settings
    • Verify network connectivity
    • Increase timeout values
    • Check if bootstrap nodes are reachable
  2. High memory usage:

    • Reduce buffer pool sizes
    • Implement proper cleanup
    • Use smaller message sizes
    • Check for memory leaks
  3. Low performance:

    • Increase buffer sizes
    • Enable zero-copy operations
    • Use multiple worker threads
    • Optimize network settings

Debugging Tools

  1. Enable debug logging:

    const p2p = @import("p2p");
    
    var config = p2p.P2PConfig.default();
    config.library.debug_logging = true;
    config.events.enable_logging = true;
    
  2. Use built-in diagnostics:

    const p2p = @import("p2p");
    
    pub fn diagnoseP2P(p2p_instance: *p2p.P2P, allocator: std.mem.Allocator) !void {
        // Get comprehensive statistics
        const stats = p2p_instance.getStats();
    
        // Print formatted statistics
        const stats_str = try stats.formatString(allocator);
        defer allocator.free(stats_str);
        std.debug.print("{s}\n", .{stats_str});
    
        // Check operational state
        std.debug.print("Operational: {}\n", .{p2p_instance.isOperational()});
        std.debug.print("State: {s}\n", .{@tagName(p2p_instance.getState())});
    }
    
  3. Monitor file transfers:

    const p2p = @import("p2p");
    
    pub fn monitorTransfers(p2p_instance: *p2p.P2P) void {
        const stats = p2p_instance.getStats();
    
        std.debug.print("File Transfer Statistics:\n", .{});
        std.debug.print("  Active downloads: {}\n", .{stats.active_downloads});
        std.debug.print("  Active uploads: {}\n", .{stats.active_uploads});
        std.debug.print("  Total downloaded: {} bytes\n", .{stats.total_downloaded});
        std.debug.print("  Total uploaded: {} bytes\n", .{stats.total_uploaded});
    }
    

Migration Guide

From BitTorrent

  1. Replace torrent-specific concepts:

    const files = @import("files");
    const p2p = @import("p2p");
    
    // P2P library style - add file for sharing
    const session_id = try p2p_instance.addFile("file.txt");
    try p2p_instance.startSharing(session_id);
    
  2. Update network communication:

    const core = @import("core");
    const network = @import("network");
    const p2p = @import("p2p");
    
    // P2P library style - connect to peers
    const peer_addr = try core.Address.parse("192.168.1.10:8080");
    const peer_id = try p2p_instance.connectToPeer(peer_addr);
    
    // Send message to peer
    const msg_id = try p2p_instance.sendMessage(peer_id, 0x01, "Hello!");
    

From Client-Server

  1. Replace central server concepts:

    const core = @import("core");
    const p2p = @import("p2p");
    
    // P2P style - connect to bootstrap nodes
    var config = p2p.P2PConfig.default();
    config.network.bootstrap_nodes = &[_][]const u8{
        "192.168.1.10:8080",
        "192.168.1.11:8080",
    };
    
    var p2p_instance = try p2p.P2P.init(allocator, config);
    defer p2p_instance.deinit();
    
    try p2p_instance.start();
    
  2. Update file sharing approach:

    const p2p = @import("p2p");
    
    // P2P approach - distributed file sharing
    const session_id = try p2p_instance.addFile("myfile.txt");
    try p2p_instance.startSharing(session_id);
    

This guide provides comprehensive coverage of the P2P library usage. For API reference, see API.md. For architecture details, see ARCHITECTURE.md.