# 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](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Zig](https://img.shields.io/badge/Zig-0.11.0+-blue.svg)](https://ziglang.org/) [![Tests](https://img.shields.io/badge/Tests-Passing-green.svg)](#testing) ## πŸš€ 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 ```bash # 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`: ```zig const p2p = b.addStaticLibrary("p2p", "path/to/p2p-library/src/core.zig"); p2p.addPackagePath("p2p", "path/to/p2p-library/src"); ``` ## πŸ“– Quick Start ### Basic Server Example ```zig 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 library const config = p2p.Configuration{ .network = .{ .listen_address = try p2p.Address.parse("0.0.0.0:8080"), .max_connections = 1000, .connection_timeout = 30000, }, .transport = .{ .tcp_enabled = true, .udp_enabled = true, }, }; var p2p_instance = try p2p.P2PLibrary.init(config); defer p2p_instance.deinit(); // Start the service try p2p_instance.start(); // Join the network const bootstrap_nodes = &[_]p2p.Address{ try p2p.Address.parse("192.168.1.10:8080"), try p2p.Address.parse("192.168.1.11:8080"), }; try p2p_instance.join(bootstrap_nodes); std.debug.print("P2P server started successfully\n", .{}); // Keep running while (true) { std.time.sleep(std.time.ns_per_min); } } ``` ### File Sharing Example ```zig 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 ```zig 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 ```json { "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: ```bash # 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](CONTRIBUTING.md) for guidelines. ## πŸ“š Documentation - [API Reference](API.md) - Complete API documentation - [User Guide](GUIDE.md) - Detailed usage guide and tutorials - [Architecture](ARCHITECTURE.md) - Technical architecture details - [Contributing Guide](CONTRIBUTING.md) - Development guidelines ## πŸ—ΊοΈ 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](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 - GitHub Issues: [Create an issue](https://github.com/your-username/p2p-library/issues) - Discussions: [GitHub Discussions](https://github.com/your-username/p2p-library/discussions) - Documentation: [Online docs](https://p2p-library.readthedocs.io) --- **Built with ❀️ in Zig**