webrtc-transport #6

Open
mdt wants to merge 13 commits from webrtc-transport into main
121 changed files with 23892 additions and 3047 deletions
Showing only changes of commit 6b8067ce9b - Show all commits

5
.gitignore vendored
View File

@@ -9,9 +9,14 @@ coverage/
# Test data (large binary files) # Test data (large binary files)
tests/test_data/*.bin tests/test_data/*.bin
# Rust build artifacts
deps/rustrtc-capi/target/
# macOS # macOS
.DS_Store .DS_Store
**/node_modules/*
# IDE # IDE
.vscode/ .vscode/
.idea/ .idea/

View File

@@ -1,4 +1,5 @@
# Contributing Guide # Contributing Guide
claude --resume d20e9abd-2540-4d0d-8d04-3214fccdd911
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. 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.

View File

@@ -9,7 +9,9 @@
## Executive Summary ## 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 | | Core Networking | 9/10 | Production Ready |
| Security | 9/10 | Production Ready | | Security | 9/10 | Production Ready |
| File Transfer | 8/10 | Production Ready | | File Transfer | 8/10 | Production Ready |
| NAT Traversal | 7/10 | Ready with Caveats | | NAT Traversal | 8/10 | Production Ready |
| Documentation | 6/10 | Adequate | | DHT & Discovery | 8/10 | Production Ready |
| Testing | 8/10 | Well Tested | | Testing | 9/10 | Well Tested |
| Performance | 9/10 | Excellent | | 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) ### Core Networking (9/10)
**Strengths:** **Strengths:**
- Robust UDP-based transport with reliability layer - TCP and UDP transport with reliability layer
- Efficient connection management with proper lifecycle handling - Connection management with full lifecycle handling (6-state machine)
- Memory-bounded operations with configurable limits (CRIT-8 compliance) - Memory-bounded operations with configurable limits (CRIT-8 compliance)
- Clean separation between network, protocol, and application layers - Clean separation between network, protocol, and application layers
- Poll-based event loop — single-threaded, WASM-compatible by design
**Production Features:** **Production Features:**
- Connection pooling and reuse - Connection pooling and reuse (configurable max, default 500)
- Graceful shutdown handling - Graceful shutdown with configurable timeout (default 30s)
- Automatic reconnection with exponential backoff - Automatic reconnection with exponential backoff (100ms-10s, 3 retries)
- Rate limiting and flow control - 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) ### Security (9/10)
**Strengths:** **Encryption:**
- Noise Protocol Framework (Noise_XX_25519_ChaChaPoly_BLAKE2b) - Noise Protocol Framework (Noise_XX_25519_ChaChaPoly_BLAKE2b)
- Same encryption as WireGuard - industry-proven - Same encryption as WireGuard — industry-proven
- Perfect forward secrecy via ephemeral keys - Perfect forward secrecy via ephemeral keys with key ratcheting on nonce exhaustion
- Mutual authentication - Mutual authentication — both peers verify identity
**Security Features:** **Wire-level Protection:**
- DoS protection with stateless cookies - Wire envelope replay protection with per-session SipHash authentication
- Key pinning (TOFU - Trust On First Use) - Format: `[app_id:1][salt:8][timestamp:8][payload:N]`
- Connection rate limiting - When Noise is enabled: nonce derived from session key via HKDF — attacker cannot forge without session secret
- No plaintext on the wire - 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:** **Considerations:**
- Key management is application responsibility - Key generation and storage is application responsibility
- No built-in certificate authority (by design - P2P) - No built-in certificate authority (by design — P2P)
### File Transfer (8/10) ### File Transfer (8/10)
**Strengths:** **Strengths:**
- BitTorrent-inspired piece-based transfer - BitTorrent-inspired piece-based transfer (256KB default, configurable up to 64MB)
- Parallel downloads from multiple peers - Parallel downloads from multiple peers simultaneously
- SHA-256 integrity verification per piece - SHA-256 integrity verification per piece
- Resume support for interrupted transfers - Resume support with bitfield-based state and content hash validation
**Performance:** **Piece Selection:**
- Achieved 500+ MB/s on localhost benchmarks - Sequential, random, rarest-first, and balanced strategies
- Efficient zero-copy data paths where possible - Adaptive concurrency based on network conditions
- Adaptive piece selection algorithms
**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 - Large file (>100GB) testing limited
- No built-in compression (application layer concern) - No built-in compression (application layer concern)
### NAT Traversal (8/10) ### NAT Traversal (8/10)
**Implemented:** **Implemented:**
- NAT-PMP (RFC 6886) - automatic port mapping via 2-packet UDP exchange - **NAT-PMP** (RFC 6886) — automatic port mapping via 2-packet UDP exchange
- UPnP IGD - SSDP discovery + SOAP port mapping for consumer routers - **UPnP IGD** — SSDP discovery + SOAP port mapping for consumer routers
- IP Reflection - bundled STUN via DHT responses (zero-infrastructure) - **IP Reflection** — bundled STUN via DHT responses (zero-infrastructure)
- UDP hole punching - **UDP hole punching** — simultaneous open with 500ms resend intervals
- Connection reversal for symmetric NATs - **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:** **Limitations:**
- TURN relay not fully implemented - Carrier-grade NAT with symmetric NAT on both sides requires TURN fallback
- Some carrier-grade NAT scenarios may fail - ~5% of network configurations may need relay
- Requires fallback strategy for ~5% of network configurations
### DHT & Discovery (8/10) ### DHT & Discovery (8/10)
**Implemented:** **Implemented:**
- Kademlia-based distributed hash table - Kademlia-based distributed hash table with 32-byte node IDs
- Peer discovery without central server - `dhtStore(key, value, ttl)` — store and propagate to network
- Configurable bootstrap nodes - `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:** **Maturity:**
- Works well in controlled environments - Works well in controlled and local network environments
- Large-scale (1000+ nodes) testing ongoing - Large-scale (1000+ nodes) testing ongoing
--- ---
## Performance Benchmarks ## Performance Benchmarks
| Metric | Result | Comparison | Measured on Apple Silicon (M-series), February 2026:
|--------|--------|------------|
| Throughput (localhost) | 500+ MB/s | Competitive with libp2p | | Scenario | Result | Details |
| Throughput (LAN) | 100-300 MB/s | Network-bound | |----------|--------|---------|
| Connection setup | <50ms | Includes Noise handshake | | Multi-peer download (10 peers, localhost) | 497 MB/s | 5GB file, Noise off |
| Memory per connection | ~64KB | Highly efficient | | Multi-peer download (10 peers, localhost) | 103 MB/s | 5GB file, cold start with file creation |
| Latency overhead | <1ms | Minimal encryption cost | | 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 | | Language | Zig | Go | Rust |
| Dependencies | 0 | Many | Many | | Dependencies | 0 | Many | Many |
| Binary size | ~2MB | ~15MB | ~10MB | | Binary size | ~5MB | ~15MB | ~10MB |
| Memory usage | Low | Medium | Low | | Memory usage | Low (~131KB/conn) | Medium | Low |
| Encryption | Noise XX | Multiple | Multiple | | 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 | | Maturity | New | Mature | Mature |
| Documentation | Growing | Extensive | Good |
--- ---
## Production Deployment Checklist ## Production Deployment Checklist
### Required ### Required
- [x] Enable Noise encryption (`enable_noise_encryption = true`) - [x] Enable Noise encryption (`enable_noise_encryption = true` — this is the default)
- [x] Configure memory limits appropriately - [x] Configure memory limits appropriately for your deployment
- [x] Implement application-level authentication if needed
- [x] Set up monitoring for connection counts and bandwidth - [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 ### Recommended
- [x] Enable DoS protection for public-facing nodes - [x] Enable DoS protection for public-facing nodes
- [x] Configure connection timeouts for your use case - [x] Configure connection and piece timeouts for your use case
- [x] Implement graceful degradation for network issues - [x] Enable DHT secure mode (`dht_secure_mode = true`) for production
- [x] Set up logging for debugging (can be disabled in production) - [x] Set up logging (can be disabled or leveled in production)
### Optional ### Optional
- [ ] Custom bootstrap nodes for private networks - [ ] 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 ## Known Limitations
1. **No TCP fallback** - UDP only, some corporate firewalls may block 1. **Single-threaded event loop** — by design for WASM compatibility, but limits single-connection throughput
2. **Single-threaded event loop** - By design, but limits single-connection throughput 2. **No streaming API** — piece-based transfer only, not suited for live audio/video
3. **No streaming API** - Piece-based transfer only 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 ## Recommended Use Cases
**Excellent Fit:** **Excellent Fit:**
- Decentralized applications
- Private file sharing networks - Private file sharing networks
- Agent-to-agent (A2A) communication - Agent-to-agent (A2A) communication
- IoT device mesh networking - Decentralized applications needing encrypted P2P
- Game networking (low latency) - IoT / edge device mesh networking
**Good Fit:** **Good Fit:**
- Content distribution - Content distribution networks
- Backup synchronization - Backup synchronization
- Collaborative tools - Collaborative tools
- Game networking (low latency messaging)
**Consider Alternatives For:** **Consider Alternatives For:**
- High-reliability enterprise (needs more battle-testing)
- Browser-based P2P (no WebRTC) - Browser-based P2P (no WebRTC)
- Streaming media (no streaming protocol) - 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 | | Feature | Priority | Status |
|---------|----------|--------| |---------|----------|--------|
| TURN relay support | High | Planned |
| WebRTC data channels | Medium | Investigating |
| Metrics/observability | Medium | Planned |
| Formal security audit | High | Seeking funding | | 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 ## Conclusion
zig-p2p is **production-ready** for applications that: zig-p2p is **production-ready** for applications that:
- Need encrypted P2P communication - Need encrypted P2P communication with mutual authentication
- Can tolerate ~10% NAT traversal failures (or have fallbacks) - Require decentralized file sharing with swarm resilience
- Want NAT traversal without mandatory infrastructure (MWP)
- Value zero dependencies and small binary size - 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. **Recommendation:** Suitable for production deployment with appropriate monitoring and fallback strategies.

1381
convo.md

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,603 @@
# WASM/Browser + Native WebRTC — Detailed Task List
**80 tasks across 6 phases, ~234 hours estimated**
---
## Phase 0: Preparation and Audit (4 tasks, ~7h)
### T0.1 — Create `src/platform/` directory (1h)
- Create empty `src/platform/` directory for platform-specific code
- No build changes yet
### T0.2 — Audit every Socket access point (2h)
- Read-only audit of all files importing `core.Socket`
- Produce reference table: every call to send, sendTo, receive, receiveFrom, bind, listen, accept, connect, close, poll, setNonBlocking with file:line
- **Output**: Reference document for Transport interface design
- Files: `src/core/socket.zig`, `src/network/network_manager.zig`, `src/network/secure_connection.zig`, `src/network/upnp.zig`, `src/network/nat_pmp.zig`, `src/network/discovery.zig`, `src/network/nat.zig`, `src/network/turn_integration.zig`, `src/mwp/hole_punch.zig`, `src/p2p/connection.zig`, `src/p2p/messaging.zig`
### T0.3 — Audit Mutex usage and threading model (2h)
- Classify each of the 835 Mutex occurrences into:
- (a) Protects truly concurrent multi-thread access (e.g., worker thread + update loop)
- (b) Single-threaded access only (artifact of lock ordering discipline)
- (c) Within spawned worker threads (handler.zig, verification_pool.zig)
- Identify which 4 files spawn threads: `nat.zig`, `handler.zig`, `request_tracker.zig`, `verification_pool.zig`
### T0.4 — Audit random and time usage (1.5h)
- Document all `std.crypto.random.bytes()` sites (18 files, 30+ calls)
- Document all `std.time.milliTimestamp()`, `timestamp()`, `nanoTimestamp()` sites (50+ files)
- Identify hot-path vs initialization-only usage
- Check if Zig's std.crypto/std.time has WASM support via WASI
---
## Phase 1: Transport Abstraction (16 tasks, ~48h)
### T1.1 — Define Transport interface (3h)
- **Create**: `src/core/transport.zig`
- Define `Transport` struct with vtable: `send`, `receive`, `close`, `canSend`, `canReceive`, `getRemoteId`, `getState`
- Define `TransportError` error set
- Include datagram methods: `sendTo(data, address)`, `receiveFrom(buffer) -> {size, address}`
- Unit test with mock vtable dispatch
- **Decision**: Single interface with mode flag (stream + datagram), not two separate interfaces. Unsupported ops return `OperationNotSupported`.
- **Depends on**: T0.1, T0.2
### T1.2 — Define TransportFactory interface (2h)
- **Modify**: `src/core/transport.zig`
- Add `TransportFactory` with vtable: `connect(address, callback)`, `listen(address, callback)`, `stopListening()`, `poll(timeout_ms)`
- Factory creates Transport instances
- **Depends on**: T1.1
### T1.3 — Implement PosixStreamTransport (4h)
- **Create**: `src/platform/posix_transport.zig`
- Wraps existing `Socket` for TCP (not replacing Socket, wrapping it)
- Implements Transport vtable: send → socket.send, receive → socket.receive, etc.
- `canSend`/`canReceive` use `posix.poll()` with 0ms timeout
- Unit test: create, send data through loopback, receive
- **Depends on**: T1.1, T1.2
### T1.4 — Implement PosixDatagramTransport (3h)
- **Modify**: `src/platform/posix_transport.zig`
- Add datagram variant: `sendTo` → socket.sendTo, `receiveFrom` → socket.receiveFrom
- Critical for DHT and discovery (UDP)
- Unit test: two UDP sockets exchanging packets
- **Depends on**: T1.3
### T1.5 — Implement MockTransport (2h)
- **Create**: `src/platform/mock_transport.zig`
- In-memory transport with configurable delays, errors, queued data
- Mirrors existing MockSocket pattern in socket.zig (line 1025+)
- Both stream and datagram modes
- **Depends on**: T1.1
### T1.6 — Export Transport types from core module (1h)
- **Modify**: `src/core.zig`
- Add `pub const transport = @import("core/transport.zig")`
- Re-export: Transport, TransportFactory, TransportError, TransportState
- **Depends on**: T1.1
### T1.7 — Add transport module to build.zig (1h)
- **Modify**: `build.zig`
- Add `src/platform/` files to appropriate module
- Add `const is_wasm = target.cpu_arch == .wasm32;` for conditional compilation
- Verify `zig build` succeeds and runs transport unit tests
- **Depends on**: T1.3, T1.4, T1.5, T1.6
### T1.8 — Refactor PeerConnection: `*Socket` → `Transport` (4h) ⚠️ HIGH RISK
- **Modify**: `src/network/network_manager.zig` (PeerConnection struct, ~line 136)
- Change `PeerConnection.socket: *Socket` to `PeerConnection.transport: Transport`
- Update `init()`, `initSecure()`, all methods accessing `self.socket`
- Add backward-compatible factory: `PeerConnection.initFromSocket()` wraps Socket in PosixStreamTransport
- Must preserve atomic send semantics and PendingSend/EncryptedQueueEntry patterns
- **ALL existing tests must pass unchanged**
- **Depends on**: T1.3, T1.7
- **Risk**: Most invasive change — touches sendToPeerAtomicImpl, drainPendingSendsImpl, processReceive, processSendQueue
### T1.9 — Refactor SecureConnection to use Transport (4h)
- **Modify**: `src/network/secure_connection.zig` (447 lines)
- Change `SecureConnection.socket: *Socket` → accept Transport
- Update `sendRaw()` (line 379) and `receiveRaw()` (line 401) to use transport.send/receive
- Blocking retry loops with Thread.sleep remain for now (Phase 2 fixes these)
- Update sendEncrypted/receiveDecrypted
- **Depends on**: T1.8
### T1.10 — Refactor NetworkManager receive path (3h)
- **Modify**: `src/network/network_manager.zig` — `processReceive()` (~line 971)
- Read from PeerConnection.transport instead of Socket directly
- Pattern: iterate peer_connections, check transport.canReceive(), call transport.receive()
- **Depends on**: T1.8
### T1.11 — Refactor NetworkManager send path (3h)
- **Modify**: `src/network/network_manager.zig` — `sendMessage()`, `processSendQueue()`
- **Modify**: `src/p2p/connection.zig` — `sendToPeerAtomicImpl()`, `sendSegmentsToPeerAtomicImpl()`, `drainPendingSendsImpl()`
- Replace peer_conn.socket.send() with peer_conn.transport.send()
- WouldBlock handling unchanged — just goes through Transport
- **Depends on**: T1.8, T1.10
### T1.12 — Refactor connection establishment to use TransportFactory (4h)
- **Modify**: `src/p2p/connection.zig` — `connectToPeerImpl()`, `attemptConnectionInternalImpl()`, `acceptConnectionsImpl()`
- New flow: TransportFactory.connect() → Transport → PeerConnection
- For accept: TransportFactory.listen() callback yields new Transports
- PosixTransportFactory wraps existing Socket creation
- **Depends on**: T1.2, T1.8, T1.11
### T1.13 — Refactor discovery module to use Transport (3h)
- **Modify**: `src/network/discovery.zig`
- Uses Socket/MockSocket directly (line 12). Change to DatagramTransport.
- Broadcast/multicast → DatagramTransport.sendTo()
- Receive → DatagramTransport.receiveFrom()
- **Depends on**: T1.4
### T1.14 — Refactor NAT module to use Transport (3h)
- **Modify**: `src/network/nat.zig`
- Already generic over Socket/MockSocket (lines 36-37). Change to DatagramTransport.
- STUN message exchange through Transport
- Hole punch UDP send/receive through Transport
- Thread.spawn for hole punching remains for now (Phase 2)
- **Depends on**: T1.4
### T1.15 — Refactor DHT coordinator to use Transport (3h)
- **Modify**: `src/network/dht.zig`, `src/p2p/dht.zig`
- DHT messages flow through P2P send path (already through NetworkManager)
- Ensure DHT-specific send/receive routes through Transport
- Remove any direct Socket references
- **Depends on**: T1.11
### T1.16 — Phase 1 full regression test (4h)
- Run `zig build test`, `zig build test-integration`
- Fix any failures from Transport refactoring
- Run performance benchmarks — no regression
- Verify TestP2PPair still works (real TCP on localhost)
- **Depends on**: T1.8 through T1.15
- **Gate**: MUST pass before Phase 2
---
## Phase 2: Event-Driven I/O (13 tasks, ~37h)
### T2.1 — Implement EventQueue (3h)
- **Create**: `src/platform/event_queue.zig`
- Events: transport_readable, transport_writable, transport_state, timer, file_io_complete
- Methods: push(), processAll(), processN(), registerHandler()
- Optional for native (poll-based loop works). Required for WASM.
- **Depends on**: T1.7
### T2.2 — Implement platform-aware Mutex (2h)
- **Create**: `src/platform/sync.zig`
- `pub const Mutex = if (builtin.target.isWasm()) WasmMutex else std.Thread.Mutex;`
- WasmMutex: no-op with debug recursive lock detection
- **Depends on**: T0.3
### T2.3 — Implement platform-aware time abstraction (2h)
- **Create**: `src/platform/time.zig`
- `milliTimestamp()`: std.time.milliTimestamp() on native, js_timestamp_ms() on WASM
- Same for timestamp(), nanoTimestamp()
- **Depends on**: T0.4
### T2.4 — Implement platform-aware random abstraction (2h)
- **Create**: `src/platform/random.zig`
- `bytes(buf)`: std.crypto.random.bytes() on native, js_random_bytes() on WASM (crypto.getRandomValues)
- **Depends on**: T0.4
### T2.5 — Non-blocking Noise handshake (4h) ⚠️ HIGH RISK
- **Modify**: `src/network/secure_connection.zig` — sendRaw() (line 379), receiveRaw() (line 401)
- Replace blocking retry loops with state machine: `HandshakeState { .sending_msg1, .awaiting_msg2, .sending_msg3, .complete }`
- Each call to `advanceHandshake()` does non-blocking I/O, returns `.progress` or `.would_block`
- Caller (connection.zig) calls from update loop
- Must buffer partial sends/receives
- **Depends on**: T1.9
- **Risk**: Noise XX expects complete messages from writeMessage/readMessage
### T2.6 — Non-blocking connection establishment (4h)
- **Modify**: `src/p2p/connection.zig` — attemptConnectionInternalImpl()
- Multi-step state: Connecting → HandshakeMsg1 → HandshakeMsg2 → HandshakeMsg3 → Connected
- Pending connections stored in list, advanced each update cycle
- **Depends on**: T2.5
### T2.7 — Remove Thread.sleep from network_manager, dht, discovery (3h)
- **Modify**: `src/network/network_manager.zig`, `src/network/dht.zig`, `src/network/discovery.zig`
- Replace sleep with timestamp-based retry (store retry-at, check in update loop)
- **Depends on**: T2.3
### T2.8 — Remove Thread.sleep from MWP modules (2h)
- **Modify**: `src/mwp_integration.zig`, `src/mwp/meeting_point.zig`, `src/mwp/hole_punch.zig`
- Hole punch resend (500ms) → timestamp check in update loop instead of sleep
- **Depends on**: T2.3
### T2.9 — Remove Thread.sleep from file transfer (2h)
- **Modify**: `src/files/manager.zig`, `src/files/piece_pipeline.zig`, `src/files/verification_pool.zig`
- Replace blocking sleeps with cooperative patterns
- Thread spawning handled separately in T2.11
- **Depends on**: T2.3
### T2.10 — Replace Thread.spawn in protocol handler with TaskQueue (4h)
- **Create**: `src/platform/task_queue.zig`
- **Modify**: `src/protocol/handler.zig`
- Implement cooperative TaskQueue (design doc Section 9.3)
- Comptime switch: `if (builtin.target.isWasm()) task_queue.schedule(...) else Thread.spawn(...)`
- **Depends on**: T2.2
### T2.11 — Replace Thread.spawn in verification_pool (3h)
- **Modify**: `src/files/verification_pool.zig`
- WASM: chunked single-threaded SHA-256 verification (process N bytes per update, yield)
- Native: keep existing thread pool
- Comptime switch
- **Depends on**: T2.10
### T2.12 — Replace Thread.spawn in NAT and request_tracker (2h)
- **Modify**: `src/network/nat.zig`, `src/protocol/request_tracker.zig`
- Hole punching → update-loop-driven (check timer, send packet, return)
- Request tracker cleanup → update-loop-driven
- **Depends on**: T2.10
### T2.13 — Phase 2 full regression test (3h)
- All tests pass
- Verify: no Thread.sleep or Thread.spawn in WASM code paths (grep)
- **Depends on**: T2.5 through T2.12
- **Gate**: MUST pass before Phase 3
---
## Phase 3: WASM WebRTC Transport — Browser Side (8 tasks, ~24h)
### T3.1 — Create WASM entry point and exports (3h)
- **Create**: `src/wasm/main.zig`, `src/wasm/exports.zig`
- Exports: p2p_init, p2p_connect, p2p_send, wasm_tick, alloc, free, on_timer, on_data_available, on_channel_closed
- `zig build -Dtarget=wasm32-freestanding` produces .wasm
- **Depends on**: T2.2, T2.3, T2.4
### T3.2 — Implement WebRTCTransport for WASM (Zig side) (3h)
- **Create**: `src/platform/webrtc_wasm_transport.zig`
- Transport vtable backed by `extern "webrtc"` imports (js_send, js_recv, js_close, etc.)
- Channel-ID based
- **Depends on**: T1.1
### T3.3 — Create JS WebRTC glue layer (4h)
- **Create**: `wasm/js/webrtc-transport.js`
- WebRTCTransportManager class: RTCPeerConnection + RTCDataChannel management
- Provides WASM imports (js_send, js_recv, etc.)
- Handles connection setup, ICE, data channel lifecycle
- **Depends on**: T3.2
### T3.4 — Implement signaling protocol (3h)
- **Create**: `wasm/js/signaling.js`, `tools/signaling-server.js`
- Simple WebSocket signaling (~50 lines Node.js)
- Message types: register, offer, answer, ice-candidate
- **Depends on**: T3.3
### T3.5 — Create main JS API (3h)
- **Create**: `wasm/js/zig-p2p.js`
- ZigP2P class: init(), connect(), send(), onMessage(), onPeerConnected()
- WASM loading, memory management, event loop (requestAnimationFrame → wasm_tick)
- **Depends on**: T3.1, T3.3, T3.4
### T3.6 — Build system WASM target (3h)
- **Modify**: `build.zig`
- Add `wasm` step: wasm32-freestanding target, export symbols, disable entry, copy JS files
- `zig build wasm` produces `zig-out/wasm/zig-p2p.wasm` + JS files
- Native build unaffected
- **Depends on**: T3.1, T3.2
### T3.7 — Browser demo page (2h)
- **Create**: `wasm/demo/index.html`, `wasm/demo/demo.js`
- Load zig-p2p WASM, connect to signaling server, show peers, send messages
- **Depends on**: T3.5, T3.6
### T3.8 — Browser-to-browser integration test (3h)
- **Create**: `tests/browser/test_browser_p2p.js` (Playwright)
- Two browser contexts: init P2P, connect, exchange encrypted messages
- `npx playwright test`
- **Depends on**: T3.7
---
## Phase 4: File System and Threading Adaptation (7 tasks, ~17h)
### T4.1 — Define FileSystem interface (2h)
- **Create**: `src/platform/filesystem_interface.zig`
- Vtable: open, read, write, close, stat, delete
- Replaces `use_mock_fs` compile-time flag with runtime dispatch
- **Depends on**: T1.1
### T4.2 — Implement NativeFileSystem (2h)
- **Create**: `src/platform/native_fs.zig`
- Wraps std.fs.File operations
- **Depends on**: T4.1
### T4.3 — Implement IndexedDB FileSystem (3h)
- **Create**: `src/platform/indexeddb_fs.zig`, `wasm/js/indexeddb-fs.js`
- Zig: vtable backed by extern "indexeddb" imports
- JS: IndexedDBFileSystem class with blob storage
- **Depends on**: T4.1
### T4.4 — Refactor files module to use FileSystem interface (4h)
- **Modify**: `src/files/filesystem.zig`, `src/files/manager.zig`, `src/files/download.zig`, `src/files/upload.zig`
- Replace use_mock_fs with runtime FileSystem
- FileSharingManager receives FileSystem in config
- **Depends on**: T4.2
### T4.5 — Refactor crypto key persistence (2h)
- **Modify**: `src/protocol/crypto.zig`, `src/network/key_pinning.zig`
- These use std.fs directly. Accept FileSystem in config.
- WASM: keys go to IndexedDB. Native: keys go to disk.
- **Depends on**: T4.1
### T4.6 — Create platform module aggregator (2h)
- **Create**: `src/platform/native.zig`, `src/platform/wasm.zig`
- Each exports platform-specific implementations
- `pub const platform = if (builtin.target.isWasm()) @import("platform/wasm.zig") else @import("platform/native.zig");`
- **Depends on**: T2.2, T4.2, T4.3
### T4.7 — Phase 4 regression test (2h)
- All native tests pass
- WASM builds compile
- File transfer works with NativeFS and MockFS
- **Depends on**: T4.1 through T4.6
---
## Phase 5: Native WebRTC via libdatachannel C Bindings (23 tasks, ~71h)
### T5.1 — Install libdatachannel and verify headers (2h)
- System install: `brew install libdatachannel` (macOS) or build from source
- Verify `rtc/rtc.h` accessible
- Document version + install instructions in `docs/WEBRTC_BUILD.md`
- Pin to specific version (e.g., 0.21.x)
### T5.2 — Create @cImport wrapper and type mappings (3h)
- **Create**: `src/platform/webrtc_native.zig`
- `const rtc = @cImport({ @cInclude("rtc/rtc.h"); });`
- Zig type aliases for C types: RtcConfiguration, RtcDataChannelInit, RtcReliability
- Map rtcState enum → Transport.State
- Verify: rtc.rtcPreload() + rtc.rtcCleanup() callable from Zig
- **Depends on**: T5.1
### T5.3 — Add `-Denable-webrtc` build option (2h)
- **Modify**: `build.zig`
- `b.option(bool, "enable-webrtc", "Enable native WebRTC transport via libdatachannel")`
- When true: linkSystemLibrary("datachannel"), linkLibC(), add include path
- When false: no WebRTC code compiled or linked
- **Depends on**: T5.2
### T5.4 — Smoke test: lifecycle (1.5h)
- **Create**: `tests/integration/test_webrtc_smoke.zig`
- Call rtcPreload(), create PeerConnection, close, delete, rtcCleanup()
- Verify no crashes, no leaks (TrackingAllocator)
- **Depends on**: T5.3
### T5.5 — Implement C→Zig callback bridge (4h) ⚠️ HIGH RISK
- **Modify**: `src/platform/webrtc_native.zig`
- 8 `callconv(.c)` callbacks: onLocalDescription, onLocalCandidate, onStateChange, onGatheringStateChange, onMessage, onOpen, onClosed, onError
- Each recovers ChannelState via rtcGetUserPointer, updates state or queues data
- **CRITICAL**: libdatachannel calls from internal thread → must be thread-safe
- Push to lock-free queue or use atomic state flags consumed by update loop
- **Depends on**: T5.2
### T5.6 — Implement thread-safe ChannelState (3h)
- **Modify**: `src/platform/webrtc_native.zig`
- `state: std.atomic.Value(Transport.State)` — lock-free state reads
- `recv_queue` — mutex-protected FIFO (SPSC: libdatachannel thread writes, update loop reads)
- `local_sdp`, `local_candidates`, `gathering_complete` — atomic or mutex-protected
- Concurrent read/write test from two threads
- **Depends on**: T5.5
### T5.7 — Implement createOffer() (4h)
- **Modify**: `src/platform/webrtc_native.zig`
- Build rtcConfiguration with ICE servers
- rtcCreatePeerConnection → allocate ChannelState → wire callbacks via rtcSetUserPointer
- rtcCreateDataChannelEx (reliable, ordered, protocol "zig-p2p")
- Wire DataChannel callbacks (open, closed, message)
- Return {channel_id, state}. Caller polls state.local_sdp for generated offer.
- Test: createOffer(), wait for local_sdp != null, verify SDP contains "v=0"
- **Depends on**: T5.6
### T5.8 — Implement acceptOffer() (3h)
- **Modify**: `src/platform/webrtc_native.zig`
- Create PeerConnection, set remote description (triggers answer generation)
- Wire DataChannel callback for incoming channel from remote
- Test: createOffer on A → pass SDP to acceptOffer on B → verify answer SDP
- **Depends on**: T5.7
### T5.9 — Implement send/receive/close (3h)
- **Modify**: `src/platform/webrtc_native.zig`
- send() → rtcSendMessage(dc_id, data.ptr, data.len)
- receive() → read from ChannelState.recv_queue
- close() → rtcClose, rtcDeleteDataChannel, rtcDeletePeerConnection
- canSend() → check rtcGetBufferedAmount < threshold
- canReceive() → check recv_queue non-empty
- **Depends on**: T5.7, T5.8
### T5.10 — Implement ICE candidate exchange (2h)
- **Modify**: `src/platform/webrtc_native.zig`
- addRemoteCandidate(channel_id, candidate) → rtcAddRemoteCandidate(pc_id, cand, "0")
- drainLocalCandidates(channel_id) → return accumulated local candidates, clear list
- getLocalSdp(channel_id) → return SDP
- Test: two NativeWebRTCTransport exchanging SDP/ICE in-memory
- **Depends on**: T5.9
### T5.11 — Loopback integration test: two native WebRTC peers (4h)
- **Create**: `tests/integration/test_webrtc_loopback.zig`
- Two NativeWebRTCTransport instances
- A creates offer, B accepts, exchange ICE in-memory
- Wait for DataChannel open
- Send "hello world" A→B, verify. Send response B→A, verify.
- Test reliable and unreliable channel configs
- **Depends on**: T5.10
- **Risk**: ICE may fail in loopback. Use 127.0.0.1 bind, may need STUN disabled.
### T5.12 — Conform to Transport vtable (3h)
- **Modify**: `src/platform/webrtc_native.zig`
- Create `WebRTCChannelTransport` wrapper: holds ref to NativeWebRTCTransport + channel_id
- Implements Transport vtable (send → self.manager.send(self.channel_id, data), etc.)
- Interchangeable with PosixStreamTransport in PeerConnection
- **Depends on**: T5.9, T1.1
### T5.13 — Implement SignalingMessage serialization (3h)
- **Create**: `src/platform/webrtc_signaling.zig`
- SignalingMessage: msg_type (offer/answer/ice_candidate), from_pubkey, sdp/candidate, timestamp, Ed25519 signature
- serialize/deserialize
- computeSignalingKey() — SHA-256(sorted pubkeys), same as MWP meeting point
- Roundtrip + signature verification tests
- **Depends on**: none (uses existing Ed25519)
### T5.14 — Implement DHT-based signaling (4h)
- **Create**: `src/platform/webrtc_dht_signaling.zig`
- Use dhtStore/dhtFindValue to exchange WebRTC signaling messages
- Flow: compute meeting key → store offer → poll for answer → exchange ICE
- Reuse MWP meeting point derivation
- Timeout with retry
- Test: two P2P instances on localhost, one stores offer in DHT, other finds it
- **Depends on**: T5.13, T1.15
### T5.15 — Implement ICE candidate trickle via DHT (3h)
- **Modify**: `src/platform/webrtc_dht_signaling.zig`
- Periodically store batched candidates in DHT
- Other peer polls for new candidates
- Versioned keys or growing value
- Test: ICE candidates propagate, connection succeeds with delayed candidates
- **Depends on**: T5.14
### T5.16 — WebSocket signaling fallback (3h)
- **Create**: `src/platform/webrtc_ws_signaling.zig`
- For bootstrap: when DHT unavailable (first browser peer with no native bootstrap)
- Use libdatachannel's WebSocket client (rtcCreateWebSocket — free with the library)
- Lower priority — DHT signaling (T5.14) is primary path
- **Depends on**: T5.10, T3.4
### T5.17 — Integrate WebRTC transport into P2P connection flow (4h)
- **Modify**: `src/p2p/connection.zig`, `src/p2p/config.zig`
- Add `webrtc: bool = false` to P2PConfig.transports
- When enabled + peer is browser: WebRTC connection path
- Flow: compute signaling key → create/wait offer → exchange SDP/ICE via DHT → DataChannel opens → create PeerConnection with WebRTCChannelTransport → Noise handshake
- When connecting to native peer: prefer UDP
- **Depends on**: T5.12, T5.14, T1.12
### T5.18 — Noise handshake over WebRTC DataChannel (3h)
- Verify Noise XX works over WebRTC DataChannel transport
- SecureConnection uses Transport interface (T1.9), WebRTCChannelTransport implements it (T5.12)
- Should work without code changes — create integration test
- Test: two peers connect via WebRTC, Noise handshake, exchange encrypted messages, verify wire envelope nonce auth
- **Depends on**: T5.12, T1.9
### T5.19 — Native-to-browser connection test (4h) ⚠️ HIGH RISK
- **Create**: `tests/integration/test_native_browser.js` (Playwright + native)
- Launch native peer with WebRTC enabled
- Launch browser page with WASM peer
- Exchange signaling via WebSocket signaling server
- Verify DataChannel established
- Send native→browser, verify. Send browser→native, verify.
- **Depends on**: T5.17, T3.7
- **Risk**: DTLS negotiation, SDP format, ICE candidates must be compatible
### T5.20 — File transfer over WebRTC DataChannel (3h)
- Test piece-based file transfer through WebRTC transport
- Key: WebRTC DataChannel max message size (default 256KB) must be >= piece size
- Configure rtcConfiguration.maxMessageSize if needed
- Test: 1MB file from native to browser, all pieces verified
- **Depends on**: T5.19
### T5.21 — Cleanup and resource management (3h)
- **Modify**: `src/platform/webrtc_native.zig`
- Proper deinit(): close DataChannels, delete PeerConnections, rtcCleanup()
- Edge cases: disconnect during handshake, ICE failure, DataChannel close
- Leak test: 100 connections created+closed, verify zero leaked allocations
- **Depends on**: T5.11
### T5.22 — CI build integration (2h)
- Add CI step: `zig build -Denable-webrtc=true`
- Document install steps per platform
- Non-WebRTC builds unaffected
- **Depends on**: T5.3
### T5.23 — Phase 5 comprehensive test (4h)
- Full suite with WebRTC enabled
- Matrix: native↔native via UDP (no regression), native↔native via WebRTC, native↔browser via WebRTC
- Verify Noise + wire envelope on all paths
- **Depends on**: T5.17 through T5.21
- **Gate**: MUST pass before Phase 6
---
## Phase 6: Integration and Polish (9 tasks, ~30h)
### T6.1 — Auto-transport negotiation (4h)
- **Modify**: `src/p2p/connection.zig`, `src/p2p/config.zig`
- Native-to-native: prefer UDP. Native-to-browser: use WebRTC.
- Store transport capabilities in DHT peer metadata
- Auto-select on connection
- **Depends on**: T5.17
### T6.2 — Connection upgrade: WebRTC → UDP (3h)
- **Modify**: `src/p2p/connection.zig`
- If two native peers connected via WebRTC, attempt upgrade to UDP
- Exchange UDP addresses, attempt direct connection, migrate transport
- **Depends on**: T6.1
### T6.3 — Error handling and timeouts (3h)
- **Modify**: `src/platform/webrtc_native.zig`, `src/platform/webrtc_dht_signaling.zig`
- 30s timeout for WebRTC connection establishment
- Handle ICE failure, DTLS failure, DataChannel not opening
- Propagate errors for retry/fallback
- **Depends on**: T5.17
### T6.4 — TURN server support (2h)
- **Modify**: `src/platform/webrtc_native.zig`
- Add TURN server URLs to rtcConfiguration
- Config: `ice_servers: ["stun:stun.l.google.com:19302", "turn:user:pass@turn.example.com:3478"]`
- **Depends on**: T5.7
### T6.5 — End-to-end browser + DHT test (4h)
- **Create**: `tests/e2e/test_full_stack.js`
- 3 native peers forming DHT + 1 browser peer
- Browser discovers native peers via DHT, connects via WebRTC
- Exchange messages, store/retrieve DHT values across transport boundaries
- **Depends on**: T5.19, T5.14
### T6.6 — Cross-browser testing (3h)
- Run browser tests on Chrome, Firefox, Safari
- Fix browser-specific WebRTC quirks
- Document minimum browser versions
- **Depends on**: T3.8
### T6.7 — Performance profiling (3h)
- Measure: WebRTC connection setup time, DataChannel throughput, latency vs UDP, WASM memory, CPU
- Compare against design doc targets (setup <500ms, throughput >10MB/s)
- Document results
- **Depends on**: T5.23
### T6.8 — Documentation (4h)
- **Create/Modify**: `docs/WEBRTC_BUILD.md`, `docs/WASM_QUICKSTART.md`, README.md
- Build instructions, deployment guide, API reference, architecture diagrams
- New developer can follow docs to run native-to-browser demo
- **Depends on**: T6.5
### T6.9 — Final regression and cleanup (4h)
- Full suite: native + WASM + WebRTC
- No Thread.sleep in WASM paths, no direct posix.* in platform-agnostic code
- Remove temporary workarounds
- **Depends on**: all above
---
## Critical Path
```
T0.2 → T1.1 → T1.3 → T1.7 → T1.8 → T1.9 → T2.5 → T2.6 → T2.13
↓
T5.1 → T5.2 → T5.3 → T5.5 → T5.6 → T5.7 → T5.9 → T5.12 → T5.17 → T5.19
```
## Summary
| Phase | Tasks | Hours |
|-------|-------|-------|
| 0: Audit | 4 | 7 |
| 1: Transport Abstraction | 16 | 48 |
| 2: Event-Driven I/O | 13 | 37 |
| 3: WASM Browser | 8 | 24 |
| 4: FileSystem | 7 | 17 |
| 5: Native WebRTC (libdatachannel) | 23 | 71 |
| 6: Integration | 9 | 30 |
| **Total** | **80** | **~234** |
Phase 3 and Phase 4 can run in parallel after Phase 2 completes.