update docs #3
@@ -1,6 +1,6 @@
|
|||||||
# Contributing Guide
|
# Contributing Guide
|
||||||
|
|
||||||
Thank you for your interest in contributing to the P2P file sharing library! This guide will help you get started with development, understand our coding standards, and learn how to contribute effectively.
|
Thank you for your interest in contributing to zig-p2p! This guide will help you get started with development, understand our coding standards, and learn how to contribute effectively.
|
||||||
|
|
||||||
## Table of Contents
|
## Table of Contents
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ Thank you for your interest in contributing to the P2P file sharing library! Thi
|
|||||||
|
|
||||||
Before you start contributing, make sure you have:
|
Before you start contributing, make sure you have:
|
||||||
|
|
||||||
- **Zig 0.11.0 or later**: The library requires a recent version of Zig
|
- **Zig 0.15.0 or later**: The library requires a recent version of Zig
|
||||||
- **Git**: For version control
|
- **Git**: For version control
|
||||||
- **Build tools**: Compiler toolchain for your platform
|
- **Build tools**: Compiler toolchain for your platform
|
||||||
- **Development environment**: Code editor with Zig support (recommended: VS Code with Zig extension)
|
- **Development environment**: Code editor with Zig support (recommended: VS Code with Zig extension)
|
||||||
@@ -33,8 +33,8 @@ Before you start contributing, make sure you have:
|
|||||||
|
|
||||||
1. **Fork the repository**:
|
1. **Fork the repository**:
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/your-username/p2p-library.git
|
git clone https://github.com/mdtanrikulu/zig-p2p.git
|
||||||
cd p2p-library
|
cd zig-p2p
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **Build the project**:
|
2. **Build the project**:
|
||||||
@@ -1203,4 +1203,4 @@ Thank you for contributing to the P2P file sharing library! Your contributions h
|
|||||||
For more information:
|
For more information:
|
||||||
- [GitHub Issues](https://github.com/your-username/p2p-library/issues)
|
- [GitHub Issues](https://github.com/your-username/p2p-library/issues)
|
||||||
- [GitHub Discussions](https://github.com/your-username/p2p-library/discussions)
|
- [GitHub Discussions](https://github.com/your-username/p2p-library/discussions)
|
||||||
- [Email](mailto:maintainers@p2p-library.org)
|
- [Email](mailto:maintainers@p2p-library.org)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
**Library:** zig-p2p
|
**Library:** zig-p2p
|
||||||
**Version:** 0.1.0
|
**Version:** 0.1.0
|
||||||
**Assessment Date:** February 2025
|
**Assessment Date:** February 2026
|
||||||
**Overall Score:** 8/10 - Production Ready for Most Use Cases
|
**Overall Score:** 8/10 - Production Ready for Most Use Cases
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
456
README.md
456
README.md
@@ -1,295 +1,293 @@
|
|||||||
# 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://opensource.org/licenses/MIT)
|
||||||
[](https://ziglang.org/)
|
[](https://ziglang.org/)
|
||||||
[](#testing)
|
[](#testing)
|
||||||
|
|
||||||
## 🚀 Features
|
## Features
|
||||||
|
|
||||||
- **Zero Dependencies**: Pure Zig implementation using only the standard library
|
- **Zero Dependencies** — Pure Zig, standard library only
|
||||||
- **High Performance**: Optimized for low-latency, high-throughput scenarios
|
- **Noise Protocol Encryption** — Noise_XX_25519_ChaChaPoly_BLAKE2b (same primitives as WireGuard)
|
||||||
- **Memory Safe**: Zig's safety features prevent common networking vulnerabilities
|
- **Kademlia DHT** — Decentralized peer discovery with Sybil/impersonation protection
|
||||||
- **Type Safe**: Strong typing throughout prevents runtime errors
|
- **NAT Traversal** — STUN, TURN, UPnP, NAT-PMP, and UDP hole punching
|
||||||
- **Modular Architecture**: Flexible design allowing selective feature usage
|
- **Mutual Witness Protocol** — Trustless NAT traversal using only the DHT as rendezvous
|
||||||
- **Secure**: Built-in cryptographic support with encryption and signatures
|
- **Messaging** — Typed message routing with broadcast, unicast, and custom handlers
|
||||||
- **Scalable**: Designed for large-scale distributed networks
|
- **File Transfer** — BitTorrent-style piece-based, multi-peer parallel downloads with resume
|
||||||
- **Cross-Platform**: Works on Linux, macOS, and Windows
|
- **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
|
│ Application │
|
||||||
- **Connection Abstraction**: State tracking, health checking, and metrics
|
├─────────────────────────────────────────────────┤
|
||||||
- **Error Handling**: Comprehensive error types and propagation
|
│ 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/`)
|
## Quick Start
|
||||||
- **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
|
### Prerequisites
|
||||||
|
|
||||||
- Zig 0.11.0 or later
|
- Zig 0.15+
|
||||||
- Git
|
- Git
|
||||||
|
|
||||||
### Building from Source
|
### Build
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Clone the repository
|
zig build # Build library + examples
|
||||||
git clone https://github.com/your-username/p2p-library.git
|
zig build test # Run all 2002 tests
|
||||||
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
|
### Poll-based Event Loop
|
||||||
|
|
||||||
Add to your `build.zig`:
|
> **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 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
|
|
||||||
|
|
||||||
```zig
|
```zig
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const p2p = @import("p2p");
|
const p2p_lib = @import("p2p");
|
||||||
|
|
||||||
pub fn main() !void {
|
pub fn main() !void {
|
||||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||||
defer _ = gpa.deinit();
|
defer _ = gpa.deinit();
|
||||||
const allocator = gpa.allocator();
|
const allocator = gpa.allocator();
|
||||||
|
|
||||||
// Initialize P2P node
|
var config = p2p_lib.P2PConfig.default();
|
||||||
var node = try p2p.P2P.init(allocator, .{
|
config.network.listen_port = 8080;
|
||||||
.listen_port = 8080,
|
|
||||||
.max_peers = 100,
|
var node = p2p_lib.P2P.init(allocator, config);
|
||||||
});
|
|
||||||
defer node.deinit();
|
defer node.deinit();
|
||||||
|
|
||||||
try node.start();
|
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 (true) {
|
||||||
while (node.isRunning()) {
|
try node.update(); // Process network I/O
|
||||||
// Process network I/O (incoming messages, connections, etc.)
|
// Application logic here
|
||||||
try node.update();
|
|
||||||
|
|
||||||
// Your application logic here
|
|
||||||
// ...
|
|
||||||
|
|
||||||
// Control loop timing (10ms = ~100 updates/sec)
|
|
||||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### File Sharing Example
|
## Modules
|
||||||
|
|
||||||
```zig
|
### Core (`src/core/`)
|
||||||
const p2p = @import("p2p");
|
- **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 {
|
### Network (`src/network/`)
|
||||||
const allocator = p2p_instance.allocator;
|
- **Kademlia DHT** — 32-byte node IDs, k-buckets, iterative lookup
|
||||||
|
- **NAT Traversal** — STUN (RFC 5389), TURN (RFC 5766), UPnP IGD, NAT-PMP (RFC 6886)
|
||||||
// Load and hash the file
|
- **NAT Type Detection** — Full Cone, Restricted Cone, Port Restricted, Symmetric
|
||||||
const file_data = try std.fs.cwd().readFileAlloc(allocator, file_path);
|
- **UDP Hole Punching** — Direct connectivity through NAT
|
||||||
defer allocator.free(file_data);
|
- **Topology** — Graph-based network representation
|
||||||
|
- **DoS Protection** — WireGuard-style stateless cookie challenge
|
||||||
const file_hash = try p2p.Hash.computeSHA256(file_data);
|
- **Key Pinning** — TOFU and strict modes with file persistence
|
||||||
|
- **Peer Eviction** — LRU eviction when at max connections
|
||||||
// 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 {
|
### Protocol (`src/protocol/`)
|
||||||
// Find file in network
|
- **Noise Protocol** (`src/noise/`) — Noise_XX_25519_ChaChaPoly_BLAKE2b mutual authentication
|
||||||
const peers = try p2p_instance.discovery.findFilePeers(file_hash);
|
- **HMAC** — SHA-256 message authentication
|
||||||
|
- **Encryption** — Session-based encryption with forward secrecy via rekeying
|
||||||
for (peers) |peer| {
|
- **Replay Protection** — Timestamp + nonce validation
|
||||||
// Attempt download from peer
|
- **Serialization** — High-performance binary codec
|
||||||
const download = try p2p_instance.transfer_manager.startDownload(file_hash, peer);
|
- **Ed25519** — Identity keys and message signatures
|
||||||
defer download.deinit();
|
|
||||||
|
|
||||||
try download.waitForCompletion();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📊 Performance
|
### 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
|
||||||
|
|
||||||
The library is optimized for high-performance scenarios:
|
### Mutual Witness Protocol (`src/mwp/`)
|
||||||
|
|
||||||
- **Latency**: Sub-millisecond message routing
|
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).
|
||||||
- **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.
|
- **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
|
||||||
|
|
||||||
## 🔧 Configuration
|
## Security
|
||||||
|
|
||||||
### Basic Configuration
|
| 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 |
|
||||||
|
|
||||||
```zig
|
## Performance
|
||||||
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
|
Tested on localhost (Apple Silicon):
|
||||||
|
|
||||||
```json
|
| Benchmark | Result |
|
||||||
{
|
|-----------|--------|
|
||||||
"network": {
|
| Multi-peer download (10 peers, 1GB) | ~500 MB/s |
|
||||||
"listen_address": "0.0.0.0",
|
| Swarm test (9 peers, 2 files) | ~100 MB/s |
|
||||||
"listen_port": 8080,
|
| Chaos test (seeder failures) | 17-213 MB/s per peer |
|
||||||
"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
|
```bash
|
||||||
# Run all tests
|
zig build run-multi-peer-download # 10-peer 1GB download
|
||||||
zig build test
|
zig build run-multi-file-swarm # 9-peer multi-file swarm
|
||||||
|
zig build run-swarm-chaos # Chaos: seeder failures, late joiners
|
||||||
# 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
|
## Testing
|
||||||
|
|
||||||
The `examples/` directory contains working examples:
|
2002 tests across unit, integration, and security suites:
|
||||||
|
|
||||||
- `server.zig` - Basic P2P server implementation
|
```bash
|
||||||
- `client.zig` - P2P client with file sharing
|
zig build test # All tests
|
||||||
- `protocol_example.zig` - Protocol usage examples
|
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
|
```bash
|
||||||
- [User Guide](GUIDE.md) - Detailed usage guide and tutorials
|
./scripts/coverage.sh # Source + files coverage (kcov)
|
||||||
- [Architecture](ARCHITECTURE.md) - Technical architecture details
|
./scripts/coverage.sh --full # Include integration tests
|
||||||
- [Contributing Guide](CONTRIBUTING.md) - Development guidelines
|
```
|
||||||
|
|
||||||
## 🗺️ Roadmap
|
### Docker Tests
|
||||||
|
|
||||||
- [ ] QUIC transport protocol support
|
Containerized NAT traversal testing with miniupnpd:
|
||||||
- [ ] IPv6 enhancements
|
|
||||||
- [ ] Hardware acceleration (SIMD/GPU)
|
```bash
|
||||||
- [ ] Advanced routing algorithms
|
# Build Linux binary first
|
||||||
- [ ] Mobile platform support
|
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
|
- [ ] 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.
|
MIT License — see [LICENSE](LICENSE).
|
||||||
|
|
||||||
## 🙏 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**
|
**Built with ❤️ in Zig**
|
||||||
|
|||||||
28
build.zig
28
build.zig
@@ -1976,6 +1976,34 @@ pub fn build(b: *std.Build) void {
|
|||||||
const check_step = b.step("check", "Check for compilation errors");
|
const check_step = b.step("check", "Check for compilation errors");
|
||||||
check_step.dependOn(&check_exe.step);
|
check_step.dependOn(&check_exe.step);
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Documentation Generation
|
||||||
|
// ============================================================
|
||||||
|
const docs_module = b.createModule(.{
|
||||||
|
.root_source_file = b.path("src/p2p.zig"),
|
||||||
|
.target = target,
|
||||||
|
.optimize = optimize,
|
||||||
|
});
|
||||||
|
docs_module.addImport("core", core_module);
|
||||||
|
docs_module.addImport("network", network_module);
|
||||||
|
docs_module.addImport("protocol", protocol_module);
|
||||||
|
docs_module.addImport("files", files_module);
|
||||||
|
docs_module.addImport("noise", noise_module);
|
||||||
|
|
||||||
|
const docs_lib = b.addLibrary(.{
|
||||||
|
.name = "p2p",
|
||||||
|
.root_module = docs_module,
|
||||||
|
});
|
||||||
|
|
||||||
|
const install_docs = b.addInstallDirectory(.{
|
||||||
|
.source_dir = docs_lib.getEmittedDocs(),
|
||||||
|
.install_dir = .{ .custom = "../docs" },
|
||||||
|
.install_subdir = "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const docs_step = b.step("docs", "Generate API documentation");
|
||||||
|
docs_step.dependOn(&install_docs.step);
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// Clean step (informational only)
|
// Clean step (informational only)
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# User Guide
|
# User Guide
|
||||||
|
|
||||||
Comprehensive guide for using the P2P file sharing library. This guide covers tutorials, best practices, and real-world usage patterns.
|
Comprehensive guide for using the zig-p2p networking library. This guide covers tutorials, best practices, and real-world usage patterns.
|
||||||
|
|
||||||
## Table of Contents
|
## Table of Contents
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ Comprehensive guide for using the P2P file sharing library. This guide covers tu
|
|||||||
|
|
||||||
### Installation and Setup
|
### Installation and Setup
|
||||||
|
|
||||||
1. **Install Zig**: Ensure you have Zig 0.11.0 or later
|
1. **Install Zig**: Ensure you have Zig 0.15.0 or later
|
||||||
```bash
|
```bash
|
||||||
# macOS (using Homebrew)
|
# macOS (using Homebrew)
|
||||||
brew install zig
|
brew install zig
|
||||||
@@ -34,8 +34,8 @@ Comprehensive guide for using the P2P file sharing library. This guide covers tu
|
|||||||
|
|
||||||
2. **Clone the repository**:
|
2. **Clone the repository**:
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/your-username/p2p-library.git
|
git clone https://github.com/mdtanrikulu/zig-p2p.git
|
||||||
cd p2p-library
|
cd zig-p2p
|
||||||
```
|
```
|
||||||
|
|
||||||
3. **Build the library**:
|
3. **Build the library**:
|
||||||
@@ -1084,4 +1084,4 @@ In these cases, use `--public-ip` with a known reachable address, or set up a re
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
This guide provides comprehensive coverage of the P2P library usage. For API reference, see [API.md](API.md). For architecture details, see [ARCHITECTURE.md](ARCHITECTURE.md).
|
This guide provides comprehensive coverage of the P2P library usage. For API reference, see [API.md](API.md). For architecture details, see [ARCHITECTURE.md](ARCHITECTURE.md).
|
||||||
|
|||||||
@@ -198,7 +198,7 @@ pub const Node = struct {
|
|||||||
- Signature verification
|
- Signature verification
|
||||||
|
|
||||||
#### Encryption (`encryption.zig`)
|
#### Encryption (`encryption.zig`)
|
||||||
- AES-256-GCM for symmetric encryption
|
- ChaCha20-Poly1305 AEAD for symmetric encryption
|
||||||
- Key derivation functions
|
- Key derivation functions
|
||||||
- Nonce management
|
- Nonce management
|
||||||
- Authenticated encryption
|
- Authenticated encryption
|
||||||
@@ -819,7 +819,7 @@ pub const SecurityConfig = struct {
|
|||||||
"enable_signatures": true,
|
"enable_signatures": true,
|
||||||
"key_rotation_interval": 86400,
|
"key_rotation_interval": 86400,
|
||||||
"max_key_age": 2592000,
|
"max_key_age": 2592000,
|
||||||
"allowed_cipher_suites": ["AES-256-GCM"]
|
"allowed_cipher_suites": ["ChaCha20-Poly1305"]
|
||||||
},
|
},
|
||||||
"storage": {
|
"storage": {
|
||||||
"data_directory": "./p2p_data",
|
"data_directory": "./p2p_data",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Mutual Witness Protocol (MWP)
|
# Mutual Witness Protocol (MWP)
|
||||||
|
|
||||||
**Version:** 1.0.0
|
**Version:** 1.0.0
|
||||||
**Status:** Prototype
|
**Status:** Implemented
|
||||||
**Created:** February 2026
|
**Created:** February 2026
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Mutual Witness Protocol Specification
|
# Mutual Witness Protocol Specification
|
||||||
|
|
||||||
**Version:** 1.0.0
|
**Version:** 1.0.0
|
||||||
**Status:** Draft
|
**Status:** Implemented
|
||||||
**Created:** February 2026
|
**Created:** February 2026
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
BIN
docs/sources.tar
BIN
docs/sources.tar
Binary file not shown.
Reference in New Issue
Block a user