zig-p2p

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 Zig Tests

Features

  • 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)

Architecture

┌─────────────────────────────────────────────────┐
│                   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           │
└─────────────────────────────────────────────────┘

Quick Start

Prerequisites

  • Zig 0.15+
  • Git

Build

zig build          # Build library + examples
zig build test     # Run all 2002 tests

Poll-based Event Loop

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.

const std = @import("std");
const p2p_lib = @import("p2p");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    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();
    defer node.stop() catch {};

    while (true) {
        try node.update();  // Process network I/O
        // Application logic here
        std.Thread.sleep(10 * std.time.ns_per_ms);
    }
}

Modules

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

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

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

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

Mutual Witness Protocol (src/mwp/)

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 and comparison with existing approaches.

  • 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

Security

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

Performance

Tested on localhost (Apple Silicon):

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
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

Testing

2002 tests across unit, integration, and security suites:

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)

Module-specific tests

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

Coverage

./scripts/coverage.sh           # Source + files coverage (kcov)
./scripts/coverage.sh --full    # Include integration tests

Docker Tests

Containerized NAT traversal testing with miniupnpd:

# 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

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 System design and module interactions
Security Threat model and security architecture
Crypto Cryptographic implementation details
Encryption Noise Protocol integration
HMAC Message authentication design
Pipelining Adaptive request pipelining
Production Readiness Audit results and status
Contributing 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

MIT License — see LICENSE.


Built with ❤️ in Zig

Description
No description provided
Readme 17 MiB
Languages
Zig 98.9%
Shell 1%