update docs and housekeeping

This commit is contained in:
2026-02-19 11:41:49 -03:00
parent c0dbc502cc
commit 6b8067ce9b
6 changed files with 1527 additions and 1673 deletions

View File

@@ -9,7 +9,9 @@
## Executive Summary
zig-p2p is a high-performance, zero-dependency P2P networking library written in Zig. It demonstrates production-grade quality in core networking, security, and file transfer capabilities. The library is suitable for production deployment in applications requiring encrypted peer-to-peer communication, distributed file sharing, and agent-to-agent messaging.
zig-p2p is a high-performance, zero-dependency P2P networking library written in Zig. It provides encrypted peer-to-peer communication, distributed file sharing, NAT traversal (including infrastructure-free hole punching via Mutual Witness Protocol), and a Kademlia DHT — all in a single ~5MB binary with no external dependencies.
The library is suitable for production deployment in applications requiring encrypted peer-to-peer communication, distributed file sharing, and agent-to-agent messaging.
---
@@ -20,10 +22,11 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
| Core Networking | 9/10 | Production Ready |
| Security | 9/10 | Production Ready |
| File Transfer | 8/10 | Production Ready |
| NAT Traversal | 7/10 | Ready with Caveats |
| Documentation | 6/10 | Adequate |
| Testing | 8/10 | Well Tested |
| NAT Traversal | 8/10 | Production Ready |
| DHT & Discovery | 8/10 | Production Ready |
| Testing | 9/10 | Well Tested |
| Performance | 9/10 | Excellent |
| Documentation | 6/10 | Adequate |
---
@@ -32,88 +35,119 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
### Core Networking (9/10)
**Strengths:**
- Robust UDP-based transport with reliability layer
- Efficient connection management with proper lifecycle handling
- TCP and UDP transport with reliability layer
- Connection management with full lifecycle handling (6-state machine)
- Memory-bounded operations with configurable limits (CRIT-8 compliance)
- Clean separation between network, protocol, and application layers
- Poll-based event loop — single-threaded, WASM-compatible by design
**Production Features:**
- Connection pooling and reuse
- Graceful shutdown handling
- Automatic reconnection with exponential backoff
- Rate limiting and flow control
- Connection pooling and reuse (configurable max, default 500)
- Graceful shutdown with configurable timeout (default 30s)
- Automatic reconnection with exponential backoff (100ms-10s, 3 retries)
- Per-peer rate limiting (default 1000 msg/s) and connection rate limiting (default 10/s)
- Health monitoring with configurable intervals (default 5s)
- Circuit breaker / maintenance mode on excessive error rates
### Security (9/10)
**Strengths:**
**Encryption:**
- Noise Protocol Framework (Noise_XX_25519_ChaChaPoly_BLAKE2b)
- Same encryption as WireGuard - industry-proven
- Perfect forward secrecy via ephemeral keys
- Mutual authentication
- Same encryption as WireGuard — industry-proven
- Perfect forward secrecy via ephemeral keys with key ratcheting on nonce exhaustion
- Mutual authentication — both peers verify identity
**Security Features:**
- DoS protection with stateless cookies
- Key pinning (TOFU - Trust On First Use)
- Connection rate limiting
- No plaintext on the wire
**Wire-level Protection:**
- Wire envelope replay protection with per-session SipHash authentication
- Format: `[app_id:1][salt:8][timestamp:8][payload:N]`
- When Noise is enabled: nonce derived from session key via HKDF — attacker cannot forge without session secret
- DoS protection with WireGuard-style stateless cookies (challenge-response under load)
**Key Management:**
- Ed25519 identity keys for signing and peer authentication
- Key pinning: disabled, TOFU (Trust-On-First-Use), or strict mode
- Optional key pinning persistence across restarts
- Bootstrap node pinning via Ed25519 public keys (MITM protection)
**Considerations:**
- Key management is application responsibility
- No built-in certificate authority (by design - P2P)
- Key generation and storage is application responsibility
- No built-in certificate authority (by design — P2P)
### File Transfer (8/10)
**Strengths:**
- BitTorrent-inspired piece-based transfer
- Parallel downloads from multiple peers
- BitTorrent-inspired piece-based transfer (256KB default, configurable up to 64MB)
- Parallel downloads from multiple peers simultaneously
- SHA-256 integrity verification per piece
- Resume support for interrupted transfers
- Resume support with bitfield-based state and content hash validation
**Performance:**
- Achieved 500+ MB/s on localhost benchmarks
- Efficient zero-copy data paths where possible
- Adaptive piece selection algorithms
**Piece Selection:**
- Sequential, random, rarest-first, and balanced strategies
- Adaptive concurrency based on network conditions
**Limitations:**
**Resilience:**
- Peer reputation tracking with automatic blacklisting (exponential backoff)
- Swarm survives seeder failure — downloaders become seeders automatically
- Per-peer memory quota (128MB default) prevents resource exhaustion
**Limits:**
- Default max file size: 10GB (configurable)
- Large file (>100GB) testing limited
- No built-in compression (application layer concern)
### NAT Traversal (8/10)
**Implemented:**
- NAT-PMP (RFC 6886) - automatic port mapping via 2-packet UDP exchange
- UPnP IGD - SSDP discovery + SOAP port mapping for consumer routers
- IP Reflection - bundled STUN via DHT responses (zero-infrastructure)
- UDP hole punching
- Connection reversal for symmetric NATs
- **NAT-PMP** (RFC 6886) — automatic port mapping via 2-packet UDP exchange
- **UPnP IGD** — SSDP discovery + SOAP port mapping for consumer routers
- **IP Reflection** — bundled STUN via DHT responses (zero-infrastructure)
- **UDP hole punching** — simultaneous open with 500ms resend intervals
- **TURN relay** — full client implementation with allocation refresh and fallback strategy (direct -> STUN -> TURN)
- **Connection reversal** for symmetric NATs
- **NAT type detection** — Full Cone, Restricted Cone, Port Restricted, Symmetric
**Mutual Witness Protocol (MWP):**
- Infrastructure-free NAT traversal using only the DHT as rendezvous
- Deterministic meeting point computed from both peers' public keys
- Symmetric rendezvous timing from nonce exchange — both sides punch simultaneously
- Tested on localhost and Docker NAT environments
- No STUN/TURN server required for peers that can hole punch
**Limitations:**
- TURN relay not fully implemented
- Some carrier-grade NAT scenarios may fail
- Requires fallback strategy for ~5% of network configurations
- Carrier-grade NAT with symmetric NAT on both sides requires TURN fallback
- ~5% of network configurations may need relay
### DHT & Discovery (8/10)
**Implemented:**
- Kademlia-based distributed hash table
- Peer discovery without central server
- Configurable bootstrap nodes
- Kademlia-based distributed hash table with 32-byte node IDs
- `dhtStore(key, value, ttl)` — store and propagate to network
- `dhtFindValue(key)` — async lookup, checks local first
- `dhtFindNode(target)` — find k closest nodes
- Configurable bootstrap nodes with optional Ed25519 key pinning
**Security:**
- Secure mode with TOFU-based peer validation and signature verification
- Insecure/development mode for testing (auto-accept, skip signatures)
- Sybil protection
**Maturity:**
- Works well in controlled environments
- Works well in controlled and local network environments
- Large-scale (1000+ nodes) testing ongoing
---
## Performance Benchmarks
| Metric | Result | Comparison |
|--------|--------|------------|
| Throughput (localhost) | 500+ MB/s | Competitive with libp2p |
| Throughput (LAN) | 100-300 MB/s | Network-bound |
| Connection setup | <50ms | Includes Noise handshake |
| Memory per connection | ~64KB | Highly efficient |
| Latency overhead | <1ms | Minimal encryption cost |
Measured on Apple Silicon (M-series), February 2026:
| Scenario | Result | Details |
|----------|--------|---------|
| Multi-peer download (10 peers, localhost) | 497 MB/s | 5GB file, Noise off |
| Multi-peer download (10 peers, localhost) | 103 MB/s | 5GB file, cold start with file creation |
| Multi-file swarm (9 peers) | 130 MB/s | 25GB total across mixed 1GB/5GB files |
| Swarm chaos (seeder failure + recovery) | 1GB in 87s | 7 peers, seeder killed mid-transfer |
| Memory per connection | ~131KB | Noise protocol pre-allocated encrypt/decrypt buffers |
---
@@ -123,28 +157,29 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
|---------|---------|-------------|---------------|
| Language | Zig | Go | Rust |
| Dependencies | 0 | Many | Many |
| Binary size | ~2MB | ~15MB | ~10MB |
| Memory usage | Low | Medium | Low |
| Binary size | ~5MB | ~15MB | ~10MB |
| Memory usage | Low (~131KB/conn) | Medium | Low |
| Encryption | Noise XX | Multiple | Multiple |
| NAT traversal | NAT-PMP, UPnP, TURN, MWP | AutoNAT, Relay | AutoNAT, Relay |
| File transfer | Built-in (BitTorrent-style) | Separate (Bitswap) | Separate (Bitswap) |
| Event loop | Poll-based (WASM-ready) | Goroutine-based | Async/await |
| Maturity | New | Mature | Mature |
| Documentation | Growing | Extensive | Good |
---
## Production Deployment Checklist
### Required
- [x] Enable Noise encryption (`enable_noise_encryption = true`)
- [x] Configure memory limits appropriately
- [x] Implement application-level authentication if needed
- [x] Enable Noise encryption (`enable_noise_encryption = true` — this is the default)
- [x] Configure memory limits appropriately for your deployment
- [x] Set up monitoring for connection counts and bandwidth
- [x] Plan for NAT traversal fallbacks
- [x] Plan NAT traversal strategy (UPnP/NAT-PMP for home routers, TURN for fallback)
### Recommended
- [x] Enable DoS protection for public-facing nodes
- [x] Configure connection timeouts for your use case
- [x] Implement graceful degradation for network issues
- [x] Set up logging for debugging (can be disabled in production)
- [x] Configure connection and piece timeouts for your use case
- [x] Enable DHT secure mode (`dht_secure_mode = true`) for production
- [x] Set up logging (can be disabled or leveled in production)
### Optional
- [ ] Custom bootstrap nodes for private networks
@@ -155,30 +190,31 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
## Known Limitations
1. **No TCP fallback** - UDP only, some corporate firewalls may block
2. **Single-threaded event loop** - By design, but limits single-connection throughput
3. **No streaming API** - Piece-based transfer only
1. **Single-threaded event loop** — by design for WASM compatibility, but limits single-connection throughput
2. **No streaming API** — piece-based transfer only, not suited for live audio/video
3. **No browser support** — native only (no WebRTC/WebTransport), WASM compilation planned
4. **Large-scale DHT untested** — works well at tens of nodes, 1000+ node testing ongoing
---
## Recommended Use Cases
**Excellent Fit:**
- Decentralized applications
- Private file sharing networks
- Agent-to-agent (A2A) communication
- IoT device mesh networking
- Game networking (low latency)
- Decentralized applications needing encrypted P2P
- IoT / edge device mesh networking
**Good Fit:**
- Content distribution
- Content distribution networks
- Backup synchronization
- Collaborative tools
- Game networking (low latency messaging)
**Consider Alternatives For:**
- High-reliability enterprise (needs more battle-testing)
- Browser-based P2P (no WebRTC)
- Streaming media (no streaming protocol)
- Enterprise requiring formal security audit (seeking funding)
---
@@ -186,23 +222,36 @@ zig-p2p is a high-performance, zero-dependency P2P networking library written in
| Feature | Priority | Status |
|---------|----------|--------|
| TURN relay support | High | Planned |
| WebRTC data channels | Medium | Investigating |
| Metrics/observability | Medium | Planned |
| Formal security audit | High | Seeking funding |
| Large-scale DHT testing | Medium | In progress |
| WASM compilation target | High | Architecture ready, build not wired |
| Large-scale DHT testing (1000+ nodes) | Medium | In progress |
| WebRTC data channels | Medium | Investigating |
| Metrics/observability export | Medium | Planned |
| Structured pub/sub messaging | Low | Not started |
---
## Test Coverage
- **~2,467 test declarations** across 118 test files
- **79.87% code coverage** (kcov-measured)
- Unit tests, integration tests (connected pairs), security/crypto tests
- Docker-based NAT tests (NAT-PMP and UPnP with miniupnpd)
- Chaos/resilience tests (seeder failure, swarm recovery)
- Noise + plaintext mode coverage
---
## Conclusion
zig-p2p is **production-ready** for applications that:
- Need encrypted P2P communication
- Can tolerate ~10% NAT traversal failures (or have fallbacks)
- Need encrypted P2P communication with mutual authentication
- Require decentralized file sharing with swarm resilience
- Want NAT traversal without mandatory infrastructure (MWP)
- Value zero dependencies and small binary size
- Are written in Zig or can use C ABI
- Target native platforms (WASM planned)
The library demonstrates excellent engineering quality, strong security foundations, and competitive performance. The main gaps are in edge-case NAT scenarios and large-scale battle-testing, which are being actively addressed.
The library demonstrates strong security foundations (Noise XX + wire envelope replay protection), competitive performance (130+ MB/s swarm throughput), and resilience (swarm survives seeder failure). The main gaps are large-scale battle-testing and a formal security audit.
**Recommendation:** Suitable for production deployment with appropriate monitoring and fallback strategies.