P2P File Sharing Library

A high-performance, zero-dependency peer-to-peer file sharing library written in pure Zig. Built for modern distributed systems with focus on performance, security, and reliability.

License: MIT Zig Tests

🚀 Features

  • Zero Dependencies: Pure Zig implementation using only the standard library
  • High Performance: Optimized for low-latency, high-throughput scenarios
  • Memory Safe: Zig's safety features prevent common networking vulnerabilities
  • Type Safe: Strong typing throughout prevents runtime errors
  • Modular Architecture: Flexible design allowing selective feature usage
  • Secure: Built-in cryptographic support with encryption and signatures
  • Scalable: Designed for large-scale distributed networks
  • Cross-Platform: Works on Linux, macOS, and Windows

📦 Modules

Core Networking (src/core/)

  • Address Management: IPv4, IPv6, and custom protocol support
  • Buffer Management: Zero-copy operations with memory pooling
  • Connection Abstraction: State tracking, health checking, and metrics
  • Error Handling: Comprehensive error types and propagation

Network Layer (src/network/)

  • Peer Discovery: Bootstrap node discovery and DHT-based peer finding
  • Topology Management: Graph-based network representation
  • Routing: Kademlia-style distributed hash table routing
  • Node Management: Node identification and reputation system

Protocol Layer (src/protocol/)

  • Message System: Extensible message framework with type safety
  • Message Routing: Destination-based routing with broadcast support
  • Serialization: High-performance binary serialization
  • Handler System: Message dispatching and processing

File Sharing (src/files/)

  • File Hashing: SHA-256, BLAKE2b cryptographic hashing
  • Piece Management: Chunked file transfer with verification
  • Download/Upload: Optimized file transfer protocols
  • Transfer Management: Queue management and progress tracking

🛠️ Installation

Prerequisites

  • Zig 0.11.0 or later
  • Git

Building from Source

# Clone the repository
git clone https://github.com/your-username/p2p-library.git
cd p2p-library

# Build all modules
zig build

# Run tests
zig build test

# Run examples
zig build run-server
zig build run-client

Library Integration

Add to your build.zig:

const p2p = b.addStaticLibrary("p2p", "path/to/p2p-library/src/core.zig");
p2p.addPackagePath("p2p", "path/to/p2p-library/src");

📖 Quick Start

⚠️ Important: This library uses a poll-based architecture. You must call p2p.update() in your main loop for the library to process network I/O. See Event Loop Architecture.

Basic Server Example

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

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

    // Initialize P2P node
    var node = try p2p.P2P.init(allocator, .{
        .listen_port = 8080,
        .max_peers = 100,
    });
    defer node.deinit();

    try node.start();
    std.debug.print("P2P node started on port 8080\n", .{});

    // Main event loop - REQUIRED for the library to function
    while (node.isRunning()) {
        // Process network I/O (incoming messages, connections, etc.)
        try node.update();

        // Your application logic here
        // ...

        // Control loop timing (10ms = ~100 updates/sec)
        std.Thread.sleep(10 * std.time.ns_per_ms);
    }
}

File Sharing Example

const p2p = @import("p2p");

pub fn shareFile(p2p_instance: *p2p.P2PLibrary, file_path: []const u8) !void {
    const allocator = p2p_instance.allocator;
    
    // Load and hash the file
    const file_data = try std.fs.cwd().readFileAlloc(allocator, file_path);
    defer allocator.free(file_data);
    
    const file_hash = try p2p.Hash.computeSHA256(file_data);
    
    // Create file record
    const file_record = try p2p.FileRecord.init(allocator, file_path, file_hash);
    defer file_record.deinit();
    
    // Add to file manager
    try p2p_instance.file_manager.addFile(&file_record);
    
    std.debug.print("File shared: {s} (hash: {})\n", .{ file_path, file_hash });
}

pub fn downloadFile(p2p_instance: *p2p.P2PLibrary, file_hash: p2p.Hash) !void {
    // Find file in network
    const peers = try p2p_instance.discovery.findFilePeers(file_hash);
    
    for (peers) |peer| {
        // Attempt download from peer
        const download = try p2p_instance.transfer_manager.startDownload(file_hash, peer);
        defer download.deinit();
        
        try download.waitForCompletion();
        break;
    }
}

📊 Performance

The library is optimized for high-performance scenarios:

  • Latency: Sub-millisecond message routing
  • Throughput: Gbps-level data transfer rates
  • Memory: Efficient memory usage with pooling
  • CPU: Optimized for modern multi-core processors

See benchmark.zig for performance testing.

🔧 Configuration

Basic Configuration

const config = p2p.Configuration{
    .network = .{
        .listen_address = try p2p.Address.parse("0.0.0.0:8080"),
        .max_connections = 1000,
        .connection_timeout = 30000,
        .keep_alive_interval = 30000,
    },
    .transport = .{
        .tcp_enabled = true,
        .udp_enabled = true,
        .tcp_buffer_size = 65536,
        .enable_nagle = false,
    },
    .security = .{
        .enable_encryption = true,
        .enable_signatures = true,
        .key_rotation_interval = 86400,
    },
};

JSON Configuration File

{
  "network": {
    "listen_address": "0.0.0.0",
    "listen_port": 8080,
    "max_connections": 1000,
    "connection_timeout": 30000,
    "keep_alive_interval": 30000,
    "bootstrap_nodes": ["192.168.1.10:8080"]
  },
  "transport": {
    "tcp_enabled": true,
    "udp_enabled": true,
    "tcp_buffer_size": 65536,
    "enable_nagle": false
  },
  "security": {
    "enable_encryption": true,
    "enable_signatures": true,
    "key_rotation_interval": 86400
  }
}

🔒 Security

  • Encryption: AES-256-GCM for data encryption
  • Signatures: Ed25519 for message authentication
  • Key Management: Automatic key rotation and secure storage
  • Rate Limiting: Connection and message rate limiting
  • Validation: Message validation and integrity checking

🧪 Testing

Run the comprehensive test suite:

# Run all tests
zig build test

# Run specific module tests
zig build test-core
zig build test-network
zig build test-protocol
zig build test-files

# Run with coverage
zig build test --summary all

📈 Examples

The examples/ directory contains working examples:

  • server.zig - Basic P2P server implementation
  • client.zig - P2P client with file sharing
  • protocol_example.zig - Protocol usage examples

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

📚 Documentation

🗺️ Roadmap

  • QUIC transport protocol support
  • IPv6 enhancements
  • Hardware acceleration (SIMD/GPU)
  • Advanced routing algorithms
  • Mobile platform support
  • WebAssembly compilation target

📄 License

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

🙏 Acknowledgments

  • Zig community for the excellent language and tools
  • BitTorrent protocol designers for inspiration
  • Kademlia paper authors for DHT algorithm
  • Contributors and testers

📞 Support


Built with ❤️ in Zig

Description
No description provided
Readme 17 MiB
Languages
Zig 98.9%
Shell 1%