Merge pull request 'update docs' (#3) from docs-update-0.0.1 into main

Reviewed-on: #3
This commit is contained in:
mdt
2026-02-11 18:28:35 +00:00
9 changed files with 270 additions and 244 deletions

View File

@@ -1,6 +1,6 @@
# 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
@@ -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:
- **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
- **Build tools**: Compiler toolchain for your platform
- **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**:
```bash
git clone https://github.com/your-username/p2p-library.git
cd p2p-library
git clone https://github.com/mdtanrikulu/zig-p2p.git
cd zig-p2p
```
2. **Build the project**:
@@ -1203,4 +1203,4 @@ Thank you for contributing to the P2P file sharing library! Your contributions h
For more information:
- [GitHub Issues](https://github.com/your-username/p2p-library/issues)
- [GitHub Discussions](https://github.com/your-username/p2p-library/discussions)
- [Email](mailto:maintainers@p2p-library.org)
- [Email](mailto:maintainers@p2p-library.org)

View File

@@ -2,7 +2,7 @@
**Library:** zig-p2p
**Version:** 0.1.0
**Assessment Date:** February 2025
**Assessment Date:** February 2026
**Overall Score:** 8/10 - Production Ready for Most Use Cases
---

456
README.md
View File

@@ -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.
[![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)
[![Zig](https://img.shields.io/badge/Zig-0.15+-blue.svg)](https://ziglang.org/)
[![Tests](https://img.shields.io/badge/Tests-2002_Passing-green.svg)](#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;
// 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 });
}
### 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
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;
}
}
```
### 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
## 📊 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
- **Throughput**: Gbps-level data transfer rates
- **Memory**: Efficient memory usage with pooling
- **CPU**: Optimized for modern multi-core processors
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).
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
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,
},
};
```
## Performance
### JSON Configuration File
Tested on localhost (Apple Silicon):
```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).
---
**Built with ❤️ in Zig**
**Built with ❤️ in Zig**

View File

@@ -1976,6 +1976,34 @@ pub fn build(b: *std.Build) void {
const check_step = b.step("check", "Check for compilation errors");
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)
// ============================================================

View File

@@ -1,6 +1,6 @@
# 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
@@ -20,7 +20,7 @@ Comprehensive guide for using the P2P file sharing library. This guide covers tu
### 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
# macOS (using Homebrew)
brew install zig
@@ -34,8 +34,8 @@ Comprehensive guide for using the P2P file sharing library. This guide covers tu
2. **Clone the repository**:
```bash
git clone https://github.com/your-username/p2p-library.git
cd p2p-library
git clone https://github.com/mdtanrikulu/zig-p2p.git
cd zig-p2p
```
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).

View File

@@ -198,7 +198,7 @@ pub const Node = struct {
- Signature verification
#### Encryption (`encryption.zig`)
- AES-256-GCM for symmetric encryption
- ChaCha20-Poly1305 AEAD for symmetric encryption
- Key derivation functions
- Nonce management
- Authenticated encryption
@@ -819,7 +819,7 @@ pub const SecurityConfig = struct {
"enable_signatures": true,
"key_rotation_interval": 86400,
"max_key_age": 2592000,
"allowed_cipher_suites": ["AES-256-GCM"]
"allowed_cipher_suites": ["ChaCha20-Poly1305"]
},
"storage": {
"data_directory": "./p2p_data",

View File

@@ -1,7 +1,7 @@
# Mutual Witness Protocol (MWP)
**Version:** 1.0.0
**Status:** Prototype
**Status:** Implemented
**Created:** February 2026
---

View File

@@ -1,7 +1,7 @@
# Mutual Witness Protocol Specification
**Version:** 1.0.0
**Status:** Draft
**Status:** Implemented
**Created:** February 2026
---

Binary file not shown.