|
|
|
|
@@ -1,294 +1,292 @@
|
|
|
|
|
# P2P File Sharing Library
|
|
|
|
|
# zig-p2p
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
A high-performance, zero-dependency peer-to-peer networking library written in pure Zig. Supports encrypted messaging, file sharing, and agent-to-agent communication. Features Kademlia DHT, Noise Protocol encryption, NAT traversal, and the Mutual Witness Protocol for trustless hole punching without external infrastructure.
|
|
|
|
|
|
|
|
|
|
[](https://opensource.org/licenses/MIT)
|
|
|
|
|
[](https://ziglang.org/)
|
|
|
|
|
[](#testing)
|
|
|
|
|
[](https://ziglang.org/)
|
|
|
|
|
[](#testing)
|
|
|
|
|
|
|
|
|
|
## 🚀 Features
|
|
|
|
|
## 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
|
|
|
|
|
- **Zero Dependencies** — Pure Zig, standard library only
|
|
|
|
|
- **Noise Protocol Encryption** — Noise_XX_25519_ChaChaPoly_BLAKE2b (same primitives as WireGuard)
|
|
|
|
|
- **Kademlia DHT** — Decentralized peer discovery with Sybil/impersonation protection
|
|
|
|
|
- **NAT Traversal** — STUN, TURN, UPnP, NAT-PMP, and UDP hole punching
|
|
|
|
|
- **Mutual Witness Protocol** — Trustless NAT traversal using only the DHT as rendezvous
|
|
|
|
|
- **Messaging** — Typed message routing with broadcast, unicast, and custom handlers
|
|
|
|
|
- **File Transfer** — BitTorrent-style piece-based, multi-peer parallel downloads with resume
|
|
|
|
|
- **Poll-based Architecture** — Single-threaded event loop, WASM-compatible by design
|
|
|
|
|
- **Cross-Platform** — Linux, macOS (aarch64 + x86_64)
|
|
|
|
|
|
|
|
|
|
## 📦 Modules
|
|
|
|
|
## Architecture
|
|
|
|
|
|
|
|
|
|
### 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
|
|
|
|
|
```
|
|
|
|
|
┌─────────────────────────────────────────────────┐
|
|
|
|
|
│ Application │
|
|
|
|
|
├─────────────────────────────────────────────────┤
|
|
|
|
|
│ P2P API (src/p2p/) │
|
|
|
|
|
│ - Lifecycle, config, events, stats │
|
|
|
|
|
│ - Circuit breaker, maintenance │
|
|
|
|
|
├──────────┬──────────┬───────────┬───────────────┤
|
|
|
|
|
│ Files │ MWP │ Protocol │ Network │
|
|
|
|
|
│ src/ │ src/mwp/ │ src/ │ src/network/ │
|
|
|
|
|
│ files/ │ │ protocol/ │ │
|
|
|
|
|
│ │ │ │ │
|
|
|
|
|
│ Download │ Witness │ Crypto │ DHT │
|
|
|
|
|
│ Upload │ Hole │ Noise │ NAT │
|
|
|
|
|
│ Resume │ Punch │ HMAC │ UPnP/NAT-PMP │
|
|
|
|
|
│ Pieces │ Meeting │ Replay │ STUN/TURN │
|
|
|
|
|
│ Hashing │ Point │ Encrypt │ Topology │
|
|
|
|
|
├──────────┴──────────┴───────────┴───────────────┤
|
|
|
|
|
│ Core (src/core/) │
|
|
|
|
|
│ - Sockets, buffers, connections, addresses │
|
|
|
|
|
│ - Rate limiting, error handling, logging │
|
|
|
|
|
│ - Memory tracking with global budget │
|
|
|
|
|
└─────────────────────────────────────────────────┘
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
### 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
|
|
|
|
|
## Quick Start
|
|
|
|
|
|
|
|
|
|
### Prerequisites
|
|
|
|
|
|
|
|
|
|
- Zig 0.11.0 or later
|
|
|
|
|
- Zig 0.15+
|
|
|
|
|
- Git
|
|
|
|
|
|
|
|
|
|
### Building from Source
|
|
|
|
|
### Build
|
|
|
|
|
|
|
|
|
|
```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
|
|
|
|
|
zig build # Build library + examples
|
|
|
|
|
zig build test # Run all 2002 tests
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
### Library Integration
|
|
|
|
|
### Poll-based Event Loop
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
> ⚠️ **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](docs/API.md#event-loop-architecture).
|
|
|
|
|
|
|
|
|
|
### Basic Server Example
|
|
|
|
|
> **Critical**: This library uses a poll-based architecture. You **must** call `p2p.update()` in your main loop for the library to process network I/O. This enables WASM compatibility and single-threaded simplicity.
|
|
|
|
|
|
|
|
|
|
```zig
|
|
|
|
|
const std = @import("std");
|
|
|
|
|
const p2p = @import("p2p");
|
|
|
|
|
const p2p_lib = @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,
|
|
|
|
|
});
|
|
|
|
|
var config = p2p_lib.P2PConfig.default();
|
|
|
|
|
config.network.listen_port = 8080;
|
|
|
|
|
|
|
|
|
|
var node = p2p_lib.P2P.init(allocator, config);
|
|
|
|
|
defer node.deinit();
|
|
|
|
|
|
|
|
|
|
try node.start();
|
|
|
|
|
std.debug.print("P2P node started on port 8080\n", .{});
|
|
|
|
|
defer node.stop() catch {};
|
|
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
|
while (true) {
|
|
|
|
|
try node.update(); // Process network I/O
|
|
|
|
|
// Application logic here
|
|
|
|
|
std.Thread.sleep(10 * std.time.ns_per_ms);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
### File Sharing Example
|
|
|
|
|
## Modules
|
|
|
|
|
|
|
|
|
|
```zig
|
|
|
|
|
const p2p = @import("p2p");
|
|
|
|
|
### Core (`src/core/`)
|
|
|
|
|
- **Address** — IPv4/IPv6 with serialization and NAT-aware handling
|
|
|
|
|
- **Buffers** — Zero-copy operations with memory pooling and growth
|
|
|
|
|
- **Connections** — State machine, health checks, metrics
|
|
|
|
|
- **Rate Limiting** — Per-peer and per-connection limits
|
|
|
|
|
- **Memory Tracking** — Global budget with saturating atomic counters
|
|
|
|
|
|
|
|
|
|
pub fn shareFile(p2p_instance: *p2p.P2PLibrary, file_path: []const u8) !void {
|
|
|
|
|
const allocator = p2p_instance.allocator;
|
|
|
|
|
### Network (`src/network/`)
|
|
|
|
|
- **Kademlia DHT** — 32-byte node IDs, k-buckets, iterative lookup
|
|
|
|
|
- **NAT Traversal** — STUN (RFC 5389), TURN (RFC 5766), UPnP IGD, NAT-PMP (RFC 6886)
|
|
|
|
|
- **NAT Type Detection** — Full Cone, Restricted Cone, Port Restricted, Symmetric
|
|
|
|
|
- **UDP Hole Punching** — Direct connectivity through NAT
|
|
|
|
|
- **Topology** — Graph-based network representation
|
|
|
|
|
- **DoS Protection** — WireGuard-style stateless cookie challenge
|
|
|
|
|
- **Key Pinning** — TOFU and strict modes with file persistence
|
|
|
|
|
- **Peer Eviction** — LRU eviction when at max connections
|
|
|
|
|
|
|
|
|
|
// Load and hash the file
|
|
|
|
|
const file_data = try std.fs.cwd().readFileAlloc(allocator, file_path);
|
|
|
|
|
defer allocator.free(file_data);
|
|
|
|
|
### Protocol (`src/protocol/`)
|
|
|
|
|
- **Noise Protocol** (`src/noise/`) — Noise_XX_25519_ChaChaPoly_BLAKE2b mutual authentication
|
|
|
|
|
- **HMAC** — SHA-256 message authentication
|
|
|
|
|
- **Encryption** — Session-based encryption with forward secrecy via rekeying
|
|
|
|
|
- **Replay Protection** — Timestamp + nonce validation
|
|
|
|
|
- **Serialization** — High-performance binary codec
|
|
|
|
|
- **Ed25519** — Identity keys and message signatures
|
|
|
|
|
|
|
|
|
|
const file_hash = try p2p.Hash.computeSHA256(file_data);
|
|
|
|
|
### File Sharing (`src/files/`)
|
|
|
|
|
- **Piece Transfer** — 256KB chunks with SHA-256 per-piece verification
|
|
|
|
|
- **Multi-peer Downloads** — Parallel piece fetching from multiple seeders
|
|
|
|
|
- **Resume** — Bitfield-based resume state with content hash validation
|
|
|
|
|
- **Adaptive Concurrency** — Dynamic in-flight piece count
|
|
|
|
|
- **Piece Buffer Pool** — Memory-efficient piece staging
|
|
|
|
|
- **Verification Pool** — Parallel hash verification
|
|
|
|
|
|
|
|
|
|
// Create file record
|
|
|
|
|
const file_record = try p2p.FileRecord.init(allocator, file_path, file_hash);
|
|
|
|
|
defer file_record.deinit();
|
|
|
|
|
### Mutual Witness Protocol (`src/mwp/`)
|
|
|
|
|
|
|
|
|
|
// Add to file manager
|
|
|
|
|
try p2p_instance.file_manager.addFile(&file_record);
|
|
|
|
|
The Mutual Witness Protocol (MWP) is a NAT traversal scheme designed for this project. Unlike traditional approaches that depend on STUN/TURN servers, MWP uses the DHT itself as the only coordination layer. See the full [MWP Specification](docs/mwp/SPEC.md) and [comparison with existing approaches](docs/mwp/COMPARISON.md).
|
|
|
|
|
|
|
|
|
|
std.debug.print("File shared: {s} (hash: {})\n", .{ file_path, file_hash });
|
|
|
|
|
}
|
|
|
|
|
- **Zero Infrastructure** — Uses only the DHT as rendezvous, no STUN/TURN servers needed
|
|
|
|
|
- **Trustless** — Peers publish signed address records, validated with timestamps
|
|
|
|
|
- **Hole Punching** — Nonce-based symmetric rendezvous timing, 500ms resend interval
|
|
|
|
|
- **Meeting Points** — Deterministic DHT key derivation from peer identities
|
|
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
## Security
|
|
|
|
|
|
|
|
|
|
for (peers) |peer| {
|
|
|
|
|
// Attempt download from peer
|
|
|
|
|
const download = try p2p_instance.transfer_manager.startDownload(file_hash, peer);
|
|
|
|
|
defer download.deinit();
|
|
|
|
|
| Layer | Mechanism | Details |
|
|
|
|
|
|-------|-----------|---------|
|
|
|
|
|
| Transport | Noise_XX | X25519 + ChaCha20-Poly1305 + BLAKE2b |
|
|
|
|
|
| Identity | Ed25519 | Keypair generation, signing, verification |
|
|
|
|
|
| Messages | HMAC-SHA256 | Per-message authentication |
|
|
|
|
|
| Sessions | Forward secrecy | Key ratcheting on nonce exhaustion |
|
|
|
|
|
| Replay | Nonce + timestamp | Sliding window replay protection |
|
|
|
|
|
| DoS | Cookie challenge | Stateless WireGuard-style under-load protection |
|
|
|
|
|
| Keys | TOFU / Strict | Trust-on-first-use or pinned key verification |
|
|
|
|
|
| DHT | Secure mode | Signature verification, Sybil protection |
|
|
|
|
|
| Bootstrap | Key pinning | Optional Ed25519 key pins on bootstrap nodes |
|
|
|
|
|
| Memory | Secure zeroing | `@memset` + volatile for keys, handshake state, derived material |
|
|
|
|
|
|
|
|
|
|
try download.waitForCompletion();
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
## Performance
|
|
|
|
|
|
|
|
|
|
## 📊 Performance
|
|
|
|
|
Tested on localhost (Apple Silicon):
|
|
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
| Benchmark | Result |
|
|
|
|
|
|-----------|--------|
|
|
|
|
|
| Multi-peer download (10 peers, 1GB) | ~500 MB/s |
|
|
|
|
|
| Swarm test (9 peers, 2 files) | ~100 MB/s |
|
|
|
|
|
| Chaos test (seeder failures) | 17-213 MB/s per peer |
|
|
|
|
|
|
|
|
|
|
```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
|
|
|
|
|
zig build run-multi-peer-download # 10-peer 1GB download
|
|
|
|
|
zig build run-multi-file-swarm # 9-peer multi-file swarm
|
|
|
|
|
zig build run-swarm-chaos # Chaos: seeder failures, late joiners
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 📈 Examples
|
|
|
|
|
## Testing
|
|
|
|
|
|
|
|
|
|
The `examples/` directory contains working examples:
|
|
|
|
|
2002 tests across unit, integration, and security suites:
|
|
|
|
|
|
|
|
|
|
- `server.zig` - Basic P2P server implementation
|
|
|
|
|
- `client.zig` - P2P client with file sharing
|
|
|
|
|
- `protocol_example.zig` - Protocol usage examples
|
|
|
|
|
```bash
|
|
|
|
|
zig build test # All tests
|
|
|
|
|
zig build test-src # Source-level unit tests
|
|
|
|
|
zig build test-integration # Integration tests
|
|
|
|
|
zig build test-connected-coverage # Connected peer tests (Noise + plaintext)
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 🤝 Contributing
|
|
|
|
|
### Module-specific tests
|
|
|
|
|
|
|
|
|
|
We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
|
|
|
|
|
```bash
|
|
|
|
|
zig build test-core-src # Core: sockets, buffers, connections
|
|
|
|
|
zig build test-network-src # Network: DHT, NAT, topology
|
|
|
|
|
zig build test-protocol-src # Protocol: crypto, serialization
|
|
|
|
|
zig build test-p2p-src # P2P: lifecycle, events, config
|
|
|
|
|
zig build test-noise-src # Noise: handshake, encryption
|
|
|
|
|
zig build test-files-src # Files: download, upload, hashing
|
|
|
|
|
zig build test-mwp # MWP: hole punch integration
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 📚 Documentation
|
|
|
|
|
### Coverage
|
|
|
|
|
|
|
|
|
|
- [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
|
|
|
|
|
```bash
|
|
|
|
|
./scripts/coverage.sh # Source + files coverage (kcov)
|
|
|
|
|
./scripts/coverage.sh --full # Include integration tests
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 🗺️ Roadmap
|
|
|
|
|
### Docker Tests
|
|
|
|
|
|
|
|
|
|
- [ ] QUIC transport protocol support
|
|
|
|
|
- [ ] IPv6 enhancements
|
|
|
|
|
- [ ] Hardware acceleration (SIMD/GPU)
|
|
|
|
|
- [ ] Advanced routing algorithms
|
|
|
|
|
- [ ] Mobile platform support
|
|
|
|
|
Containerized NAT traversal testing with miniupnpd:
|
|
|
|
|
|
|
|
|
|
```bash
|
|
|
|
|
# Build Linux binary first
|
|
|
|
|
zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux
|
|
|
|
|
|
|
|
|
|
# NAT-PMP
|
|
|
|
|
cd docker-tests/nat-pmp && docker compose up --build
|
|
|
|
|
|
|
|
|
|
# UPnP
|
|
|
|
|
cd docker-tests/upnp && docker compose up --build
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
|
|
|
|
|
| Example | Description |
|
|
|
|
|
|---------|-------------|
|
|
|
|
|
| `server.zig` / `client.zig` | Basic P2P server and client |
|
|
|
|
|
| `encrypted_server.zig` / `encrypted_client.zig` | Noise Protocol encrypted communication |
|
|
|
|
|
| `basic_file_share.zig` | Simple file transfer between peers |
|
|
|
|
|
| `multi_peer_download_test.zig` | 10-peer parallel 1GB download |
|
|
|
|
|
| `multi_file_swarm_test.zig` | 9-peer swarm with 2 files |
|
|
|
|
|
| `swarm_chaos_test.zig` | Seeder failure and recovery |
|
|
|
|
|
| `resume_test.zig` | Download resume after interruption |
|
|
|
|
|
| `dht_test.zig` | DHT peer discovery end-to-end |
|
|
|
|
|
| `mwp_demo.zig` | Mutual Witness Protocol hole punching |
|
|
|
|
|
| `benchmark.zig` | Throughput and latency benchmarks |
|
|
|
|
|
| `a2a/` | Agent-to-Agent LLM communication over P2P |
|
|
|
|
|
|
|
|
|
|
## Configuration
|
|
|
|
|
|
|
|
|
|
```zig
|
|
|
|
|
var config = p2p_lib.P2PConfig.default();
|
|
|
|
|
|
|
|
|
|
// Network
|
|
|
|
|
config.network.listen_port = 8080;
|
|
|
|
|
config.network.max_connections = 500;
|
|
|
|
|
config.network.connection_timeout = 30000;
|
|
|
|
|
config.network.enable_noise_encryption = true;
|
|
|
|
|
config.network.enable_nat_traversal = true;
|
|
|
|
|
config.network.enable_rate_limiting = true;
|
|
|
|
|
config.network.enable_dos_protection = true;
|
|
|
|
|
config.network.dht_secure_mode = true;
|
|
|
|
|
config.network.key_pinning_mode = .tofu;
|
|
|
|
|
|
|
|
|
|
// Protocol
|
|
|
|
|
config.protocol.max_message_size = 2 * 1024 * 1024;
|
|
|
|
|
config.protocol.enable_encryption = true;
|
|
|
|
|
|
|
|
|
|
// Events
|
|
|
|
|
config.events.max_event_queue = 10000;
|
|
|
|
|
config.events.overflow_policy = .drop_oldest;
|
|
|
|
|
|
|
|
|
|
// Library
|
|
|
|
|
config.library.max_memory = 256 * 1024 * 1024;
|
|
|
|
|
config.library.shutdown_timeout_ms = 30000;
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## Documentation
|
|
|
|
|
|
|
|
|
|
| Document | Description |
|
|
|
|
|
|----------|-------------|
|
|
|
|
|
| [Architecture](architecture/ARCHITECTURE.md) | System design and module interactions |
|
|
|
|
|
| [Security](architecture/SECURITY_IMPLEMENTATION.md) | Threat model and security architecture |
|
|
|
|
|
| [Crypto](architecture/CRYPTO_IMPLEMENTATION.md) | Cryptographic implementation details |
|
|
|
|
|
| [Encryption](architecture/ENCRYPTION_INTEGRATION.md) | Noise Protocol integration |
|
|
|
|
|
| [HMAC](architecture/HMAC_AUTHENTICATION.md) | Message authentication design |
|
|
|
|
|
| [Pipelining](architecture/adaptive-request-pipelining.md) | Adaptive request pipelining |
|
|
|
|
|
| [Production Readiness](PRODUCTION_READINESS.md) | Audit results and status |
|
|
|
|
|
| [Contributing](CONTRIBUTING.md) | Development guidelines |
|
|
|
|
|
|
|
|
|
|
## Recent Fixes (Production Audit)
|
|
|
|
|
|
|
|
|
|
- **Concurrency** — Deadlock in P2P shutdown, lock ordering in peer mapping
|
|
|
|
|
- **Memory Safety** — Use-after-free in DHT, buffer overflows in TURN, integer truncation
|
|
|
|
|
- **Crypto** — Secure zeroization of handshake state, ephemeral keys, derived keys
|
|
|
|
|
- **Correctness** — IPv6 `::` parsing, `AF_INET6` on macOS, DHT heap fallback, resume hash validation
|
|
|
|
|
- **MWP** — Incremental Blake2b hashing, address count limits, timestamp validation
|
|
|
|
|
- **Files** — Resume state content hash, download cancel batching, piece response bounds
|
|
|
|
|
- **Infra** — Saturating memory tracker (no more underflow on shutdown), buffer growth test
|
|
|
|
|
|
|
|
|
|
## Roadmap
|
|
|
|
|
|
|
|
|
|
- [ ] QUIC transport
|
|
|
|
|
- [ ] WebAssembly compilation target
|
|
|
|
|
- [ ] Mobile platform support (iOS/Android)
|
|
|
|
|
- [ ] Hardware-accelerated hashing (SIMD)
|
|
|
|
|
|
|
|
|
|
## 📄 License
|
|
|
|
|
## 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)
|
|
|
|
|
MIT License — see [LICENSE](LICENSE).
|
|
|
|
|
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
|