Compare commits

...

49 Commits

Author SHA1 Message Date
3150b3be5a add bootstrap node, MWP peer discovery, and DNS resolution 2026-02-19 17:45:32 -03:00
6b8067ce9b update docs and housekeeping 2026-02-19 11:41:49 -03:00
c0dbc502cc update build.zig: WebRTC, WASM, platform module wiring 2026-02-19 11:41:28 -03:00
9230359fb2 add WebRTC bridge TUI demo 2026-02-19 11:41:16 -03:00
e19797b4e4 add WASM browser module and browser demo 2026-02-19 11:41:00 -03:00
e7ff1eec81 add WebRTC tests 2026-02-19 11:38:56 -03:00
d8111dd32a feat: add native WebRTC bridge with libdatachannel/rustrtc bindings 2026-02-19 11:38:10 -03:00
3da00503a2 refactor MWP: platform abstractions 2026-02-19 11:36:27 -03:00
7b120731a6 refactor p2p: keepalive pings, WASM-safe messaging, non-blocking
connections
2026-02-19 11:36:11 -03:00
75087fb635 feat: add non-blocking Noise handshake, SecureConnection transport
refactor
2026-02-19 11:34:43 -03:00
4c1927588d feat: refactor files module: platform abstractions, filesystem error
handling
2026-02-19 11:34:07 -03:00
b466979bc7 feat: refactor core+network+protocol: use platform abstractions,
transport vtable
2026-02-19 11:32:30 -03:00
63e5ac59ce feat: add platform abstraction layer for WASM compatibility 2026-02-19 11:29:47 -03:00
c18d4b3946 update build.zig 2026-02-13 19:50:39 -03:00
367be10e16 Merge branch 'main' into mwp-fixes 2026-02-13 18:52:39 -03:00
46c1fa13af fix tests: disable Noise encryption in multi-peer, swarm, chaos perf
tests
2026-02-13 17:29:45 -03:00
6ec1346cfd fix protocol+tests: replay protection rework, wire envelope nonce auth,
flaky e2e test deadlines, build imports
2026-02-13 16:37:30 -03:00
c94d189d42 [DO-NOT-MERGE] Proposed explanation on request_id vs nonce topic 2026-02-12 14:13:24 +01:00
e745f849dc [DO-NOT-MERGE] proposed fix (thx to claude) 2026-02-12 14:12:28 +01:00
mdt
1180227fba Merge pull request 'update docs' (#3) from docs-update-0.0.1 into main
Reviewed-on: #3
2026-02-11 18:28:35 +00:00
b8857d9548 update docs 2026-02-11 15:27:57 -03:00
mdt
b5f4be0ade Merge pull request 'create Mutual Witness Protocol specs and implementation.' (#1) from mwp into main
Reviewed-on: #1
2026-02-11 17:38:08 +00:00
789897b51a fix infra: saturating memory tracker, check build imports, buffer growth
test
2026-02-11 14:22:05 -03:00
47f949e4cc fix files: resume state hash validation, download cancel batching, piece
response bounds
2026-02-11 14:21:44 -03:00
30bad26e67 fix MWP: incremental Blake2b hashing, address count limit in
deserialization
2026-02-11 14:21:23 -03:00
137469c3e1 fix correctness: IPv6 :: parsing, AF_INET6 on macOS, health check units,
DHT heap fallback
2026-02-11 14:20:55 -03:00
e45bffbd8b fix crypto: secure zeroization of handshake state, ephemeral keys,
derived keys
2026-02-11 14:20:16 -03:00
4770fad51c fix memory safety: use-after-free in DHT, buffer overflows in TURN,
integer truncation
2026-02-11 14:19:28 -03:00
88a2abe521 fix concurrency: resolve deadlock and lock ordering in P2P shutdown and
peer mapping
2026-02-11 14:19:09 -03:00
4c64c4cc0a Merge branch 'main' into mwp 2026-02-10 20:25:27 -03:00
4a79a9cedc fix benchmark buffer operations exceeding rate limit by reducing
iterations to stay under BufferManager cap
2026-02-10 20:16:40 -03:00
134ddde241 enable "test-connected-coverage" and "test-manager-src" in coverage
script
2026-02-10 20:16:24 -03:00
ae1061f4a5 reduce processSessions log spam and fix kcov bottleneck. raise TIMING
threshold from 1ms to 10ms, demote ADAPTIVE in_flight log to debug,
switch 3 tests from full init to initForTesting eliminating thread pool
overhead under kcov
2026-02-10 20:16:01 -03:00
ab150b3489 use core.log.err for oversized message security logs to avoid Zig
"logged errors" test failures
2026-02-10 20:15:23 -03:00
37a74e1ca9 fix: "test-connected-coverage" Noise handshake deadlock. spawn
background server update thread during connectToPeer when Noise is
enabled so the 3 message handshake can complete in single threaded tests
2026-02-10 20:15:01 -03:00
b7d013a272 clean up tests. remove placeholder assert-true tests, fix replay
protection and NAT test logic, fix MWP connection test peer ID
registration, use atomic port counter for test parallelism
2026-02-10 20:13:54 -03:00
a44af22739 improve docker healthchecks to verify port binding and iptables chains
not just process existence
2026-02-10 20:12:21 -03:00
49ef3f6640 harden MWP error handling. return errors from signing instead of
unreachable, fix memory leak on deserialization failure, validate peer
publication timestamps against max skew
2026-02-10 20:11:30 -03:00
bc4c49f724 network reliability and security hardening. auto-cleanup expired backoff
entries, atomic file writes for key pinning, forward secrecy via
rekeying, peer eviction when at max connections, NAT-PMP source address
verification, UPnP response timeout
2026-02-10 20:10:50 -03:00
b744ba5c09 add DHT security mode and event queue overflow policy. bidirectional
node-to-peer ID mapping with Sybil/impersonation checks, configurable
event queue overflow strategy (drop_oldest/drop_newest/fail)
2026-02-10 20:09:31 -03:00
600fdd4245 harden core layer. panic on refcount underflow instead of silent error,
replace socket magic numbers with posix constants, fix race where socket
state was set after closing FD
2026-02-10 20:08:11 -03:00
mdt
4d56e11139 Merge pull request 'compiling on linux - bunch of fixes' (#2) from compiling-on-linux into main
Reviewed-on: #2
Reviewed-by: mdt <mdt@anon.pff.sh>
2026-02-10 14:44:43 +00:00
2fe03cb855 fix MWP hole punch for production use. bind to 0.0.0.0 instead of
published IP, resend packets every 500ms instead of single-shot, fix
Docker iptables-legacy chains so miniupnpd port mapping fully works
without warnings
2026-02-10 11:26:57 -03:00
33730fed8a add UPnP IGD for automatic port mapping and external address discovery 2026-02-09 17:49:44 -03:00
cf5eb0d5fd add NAT-PMP for automatic port mapping and external address discovery 2026-02-09 17:05:24 -03:00
7b47ef155c bidirectional ip reflection for listener address discovery 2026-02-09 16:02:23 -03:00
59e9e420be update mwp docs 2026-02-08 13:16:50 -03:00
f86119f571 add IP Reflection to DHT for zero-infrastructure NAT traversal
bundled STUN. every DHT response now includes observed_addr field so
nodes discover their public IP without external STUN servers
2026-02-07 21:09:59 -03:00
abb398d363 create Mutual Witness Protocol specs and implementation. mwp aims to be
a zero-infrastructure NAT traversal
2026-02-07 18:01:12 -03:00
188 changed files with 38783 additions and 4317 deletions

6
.gitignore vendored
View File

@@ -1,6 +1,7 @@
# Zig build artifacts
.zig-cache/
zig-out/
*.o
# Coverage reports
coverage/
@@ -8,9 +9,14 @@ coverage/
# Test data (large binary files)
tests/test_data/*.bin
# Rust build artifacts
deps/rustrtc-capi/target/
# macOS
.DS_Store
**/node_modules/*
# IDE
.vscode/
.idea/

View File

@@ -1,6 +1,7 @@
# Contributing Guide
claude --resume d20e9abd-2540-4d0d-8d04-3214fccdd911
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 +25,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 +34,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 +1204,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,14 +2,16 @@
**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
---
## 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,86 +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 (7/10)
### NAT Traversal (8/10)
**Implemented:**
- STUN client for public IP discovery
- 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 ~10% 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 |
---
@@ -121,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
@@ -153,31 +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. **No UPnP** - Manual port forwarding may be needed
3. **Single-threaded event loop** - By design, but limits single-connection throughput
4. **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)
---
@@ -185,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.

474
README.md
View File

@@ -1,303 +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
### 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 library
const config = p2p.Configuration{
.network = .{
.listen_address = try p2p.Address.parse("0.0.0.0:8080"),
.max_connections = 1000,
.connection_timeout = 30000,
},
.transport = .{
.tcp_enabled = true,
.udp_enabled = true,
},
};
var p2p_instance = try p2p.P2PLibrary.init(config);
defer p2p_instance.deinit();
// Start the service
try p2p_instance.start();
// Join the network
const bootstrap_nodes = &[_]p2p.Address{
try p2p.Address.parse("192.168.1.10:8080"),
try p2p.Address.parse("192.168.1.11:8080"),
};
try p2p_instance.join(bootstrap_nodes);
std.debug.print("P2P server started successfully\n", .{});
// Keep running
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) {
std.time.sleep(std.time.ns_per_min);
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**

1118
browser/demo/demo.js Normal file

File diff suppressed because it is too large Load Diff

86
browser/demo/index.html Normal file
View File

@@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>zig-p2p Browser Demo</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: system-ui, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; }
h1 { margin-bottom: 1rem; }
.section { margin-bottom: 1.5rem; }
label { font-weight: 600; display: block; margin-bottom: .25rem; }
input, button { font-size: .95rem; padding: .4rem .6rem; }
input[type="text"] { width: 100%; margin-bottom: .5rem; }
button { cursor: pointer; margin-right: .5rem; }
#status { padding: .5rem; border-radius: 4px; background: #f0f0f0; font-family: monospace; font-size: .85rem; }
#log { height: 300px; overflow-y: auto; border: 1px solid #ccc; border-radius: 4px; padding: .5rem; font-family: monospace; font-size: .82rem; background: #fafafa; }
.log-entry { padding: 2px 0; border-bottom: 1px solid #eee; }
.log-entry.sent { color: #0066cc; }
.log-entry.recv { color: #009900; }
.log-entry.info { color: #666; }
.log-entry.error { color: #cc0000; }
#transferList { margin-top: .75rem; }
.transfer-entry { border: 1px solid #ddd; border-radius: 6px; padding: .6rem .8rem; margin-bottom: .5rem; background: #fafafa; }
.transfer-entry .te-header { display: flex; justify-content: space-between; align-items: center; font-size: .85rem; margin-bottom: .25rem; }
.transfer-entry .te-header .te-label { font-weight: 600; }
.transfer-entry .te-header .te-status { color: #e67e00; font-weight: 600; }
.transfer-entry .te-info { font-family: monospace; font-size: .82rem; color: #555; margin-bottom: .3rem; }
.progress-bar { height: 14px; background: #e0e0e0; border-radius: 7px; overflow: hidden; }
.progress-fill { height: 100%; background: #4caf50; border-radius: 7px; transition: width .15s; }
.progress-fill.paused { background: #e67e00; }
.progress-fill.completed { background: #2196f3; }
.transfer-controls { margin-top: .35rem; }
.transfer-controls button { font-size: .8rem; padding: .2rem .5rem; margin-right: .3rem; cursor: pointer; }
.cancel-btn { color: #cc0000; border-color: #cc0000; }
.transfer-entry.completed { background: #f0f8f0; border-color: #a0d0a0; }
.transfer-entry.completed a { color: #0066cc; font-weight: 600; }
</style>
</head>
<body>
<h1>zig-p2p Browser Demo</h1>
<div class="section" id="status">
Status: <span id="statusText">Not connected</span> |
Peer ID: <span id="peerId">—</span> |
Channels: <span id="channels">0</span>
</div>
<div class="section">
<label>Signaling Server</label>
<input type="text" id="signalingUrl" value="ws://localhost:8080">
<button id="connectBtn" onclick="doConnect()">Connect</button>
<button id="disconnectBtn" onclick="doDisconnect()" disabled>Disconnect</button>
</div>
<div class="section">
<label>Connect to Peer</label>
<input type="text" id="remotePeerId" placeholder="Enter remote peer ID">
<button id="peerBtn" onclick="doConnectPeer()" disabled>Connect to Peer</button>
</div>
<div class="section">
<label>Send Message</label>
<input type="text" id="msgInput" placeholder="Type a message..." onkeydown="if(event.key==='Enter')doSend()">
<button id="sendBtn" onclick="doSend()" disabled>Send</button>
</div>
<div class="section">
<label>File Transfer</label>
<input type="file" id="fileInput">
<button id="shareBtn" onclick="doShareFile()" disabled>Share File</button>
<div id="fileStatus" style="margin-top:.5rem;font-family:monospace;font-size:.85rem"></div>
<div id="fileOffers" style="margin-top:.5rem"></div>
<div id="transferList"></div>
</div>
<div class="section">
<label>Log</label>
<div id="log"></div>
<button onclick="document.getElementById('log').innerHTML=''" style="margin-top:.5rem">Clear</button>
<button onclick="navigator.clipboard.writeText(document.getElementById('log').innerText).then(()=>{this.textContent='Copied!';setTimeout(()=>this.textContent='Copy',1500)})" style="margin-top:.5rem">Copy</button>
</div>
<script type="module" src="demo.js"></script>
</body>
</html>

1
browser/demo/zig-p2p.wasm Symbolic link
View File

@@ -0,0 +1 @@
/Users/mdt./Projects/zig-p2p/zig-out/bin/zig-p2p.wasm

331
browser/host/file-host.js Normal file
View File

@@ -0,0 +1,331 @@
/**
* File Host — provides extern "env" file I/O functions for WASM.
*
* Maps to `extern "env" fn js_file_*` declarations in
* src/files/filesystem.zig (WASM backend).
*
* Storage model:
* - Upload files: registered as browser File objects (lazy, no upfront copy)
* - Small files / WASM-created files: stored as Uint8Array in memory
* - Download files: accumulated in memory, retrieved via getFileBlob()
* - All files identified by virtual paths (string keys)
*
* For large uploads, the File object is kept as-is and sliced on demand.
* WASM extern "env" reads (js_file_read) work from in-memory data only,
* so files must be materialized before WASM can access them. For the
* JS-level transfer, we stream directly from the File object.
*/
export class FileHost {
/** @type {Map<number, { data: Uint8Array, pos: number, name: string, readOnly: boolean }>} */
#files = new Map();
/** @type {number} */
#nextId = 1;
/** @type {Map<string, Uint8Array>} virtual path -> materialized file data */
#registered = new Map();
/** @type {Map<string, File>} virtual path -> browser File object (lazy, not loaded) */
#browserFiles = new Map();
/** @type {Set<string>} virtual directory paths */
#directories = new Set();
/** @type {() => WebAssembly.Memory} */
#getMemory;
/**
* @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance
*/
constructor(getMemory) {
this.#getMemory = getMemory;
}
/**
* Register in-memory data for virtual file access (small files, WASM downloads).
* @param {string} virtualPath
* @param {Uint8Array} data
*/
registerFile(virtualPath, data) {
this.#registered.set(virtualPath, data);
}
/**
* Register a browser File object for streaming access.
* Does NOT read the file into memory — stores the File handle for
* on-demand slice reads via readFileChunk().
* @param {File} file
* @returns {string} virtual path
*/
registerBrowserFile(file) {
const virtualPath = file.name;
this.#browserFiles.set(virtualPath, file);
return virtualPath;
}
/**
* Materialize a browser File into memory so WASM extern "env" can access it.
* Only needed if WASM-side code needs to read the file (hashing, etc.).
* For JS-level transfers, use readFileChunk() instead.
* @param {string} virtualPath
* @param {(loaded: number, total: number) => void} [onProgress]
* @returns {Promise<void>}
*/
async materializeFile(virtualPath, onProgress) {
const file = this.#browserFiles.get(virtualPath);
if (!file) return;
if (this.#registered.has(virtualPath)) return; // already materialized
const total = file.size;
const data = new Uint8Array(total);
const chunkSize = 4 * 1024 * 1024; // 4MB chunks
let offset = 0;
while (offset < total) {
const end = Math.min(offset + chunkSize, total);
const slice = file.slice(offset, end);
const buf = await slice.arrayBuffer();
data.set(new Uint8Array(buf), offset);
offset = end;
if (onProgress) onProgress(offset, total);
}
this.#registered.set(virtualPath, data);
}
/**
* Read a chunk from a browser File without loading the whole file.
* Returns a Uint8Array of the requested range.
* @param {string} virtualPath
* @param {number} offset
* @param {number} length
* @returns {Promise<Uint8Array>}
*/
async readFileChunk(virtualPath, offset, length) {
// Prefer in-memory data if available
const data = this.#registered.get(virtualPath);
if (data) {
const end = Math.min(offset + length, data.length);
return data.subarray(offset, end);
}
// Stream from File object
const file = this.#browserFiles.get(virtualPath);
if (!file) throw new Error(`File not found: ${virtualPath}`);
const end = Math.min(offset + length, file.size);
const slice = file.slice(offset, end);
const buf = await slice.arrayBuffer();
return new Uint8Array(buf);
}
/**
* Get file size without loading into memory.
* @param {string} virtualPath
* @returns {number | null}
*/
getFileSize(virtualPath) {
const data = this.#registered.get(virtualPath);
if (data) return data.length;
const file = this.#browserFiles.get(virtualPath);
if (file) return file.size;
return null;
}
/**
* Get a completed download as a Blob.
* @param {string} virtualPath
* @returns {Blob | null}
*/
getFileBlob(virtualPath) {
const data = this.#registered.get(virtualPath);
if (data) return new Blob([data]);
const file = this.#browserFiles.get(virtualPath);
if (file) return file; // File is already a Blob
return null;
}
/**
* Check if a file is registered (either in-memory or as File handle).
* @param {string} virtualPath
* @returns {boolean}
*/
hasFile(virtualPath) {
return this.#registered.has(virtualPath) || this.#browserFiles.has(virtualPath);
}
/**
* Get all registered file paths.
* @returns {string[]}
*/
listFiles() {
return [...new Set([...this.#registered.keys(), ...this.#browserFiles.keys()])];
}
// ============================================================
// extern "env" implementations (work with in-memory data only)
// ============================================================
#readString(ptr, len) {
const bytes = new Uint8Array(this.#getMemory().buffer, ptr, len);
return new TextDecoder().decode(bytes);
}
/**
* Open an existing file. Returns file_id >= 0 or -1 on error.
* Only works with materialized (in-memory) files.
*/
js_file_open(pathPtr, pathLen, readOnly) {
const path = this.#readString(pathPtr, pathLen);
const data = this.#registered.get(path);
if (!data) return -1;
const fileId = this.#nextId++;
this.#files.set(fileId, {
data: readOnly ? data : new Uint8Array(data), // copy for writable
pos: 0,
name: path,
readOnly: readOnly === 1,
});
return fileId;
}
/**
* Create a new file. Returns file_id >= 0 or -1 on error.
*/
js_file_create(pathPtr, pathLen) {
const path = this.#readString(pathPtr, pathLen);
const fileId = this.#nextId++;
const data = new Uint8Array(0);
this.#registered.set(path, data);
this.#files.set(fileId, {
data,
pos: 0,
name: path,
readOnly: false,
});
return fileId;
}
/**
* Read from file at offset. Returns bytes read or -1 on error.
*/
js_file_read(fileId, bufPtr, bufLen, offset) {
const file = this.#files.get(fileId);
if (!file) return -1;
// Use BigInt-safe conversion (offset comes as i64 from WASM)
const off = Number(offset);
const available = Math.max(0, file.data.length - off);
const toRead = Math.min(bufLen, available);
if (toRead <= 0) return 0;
const dest = new Uint8Array(this.#getMemory().buffer, bufPtr, toRead);
dest.set(file.data.subarray(off, off + toRead));
return toRead;
}
/**
* Write to file at offset. Returns bytes written or -1 on error.
*/
js_file_write(fileId, dataPtr, dataLen, offset) {
const file = this.#files.get(fileId);
if (!file || file.readOnly) return -1;
const off = Number(offset);
const src = new Uint8Array(this.#getMemory().buffer, dataPtr, dataLen);
// Grow file if needed
const needed = off + dataLen;
if (needed > file.data.length) {
const newData = new Uint8Array(needed);
newData.set(file.data);
file.data = newData;
// Update registered copy
this.#registered.set(file.name, file.data);
}
file.data.set(src, off);
return dataLen;
}
/**
* Get file size. Returns size >= 0 or -1 on error.
*/
js_file_get_size(fileId) {
const file = this.#files.get(fileId);
if (!file) return -1n; // BigInt for i64 return
return BigInt(file.data.length);
}
/**
* Close a file handle.
*/
js_file_close(fileId) {
this.#files.delete(fileId);
}
/**
* Check if a file exists. Returns 1 if exists, 0 if not.
*/
js_file_exists(pathPtr, pathLen) {
const path = this.#readString(pathPtr, pathLen);
return this.#registered.has(path) || this.#browserFiles.has(path) || this.#directories.has(path) ? 1 : 0;
}
/**
* Delete a file. Returns 1 on success, 0 on failure.
*/
js_file_delete(pathPtr, pathLen) {
const path = this.#readString(pathPtr, pathLen);
const a = this.#registered.delete(path);
const b = this.#browserFiles.delete(path);
return (a || b) ? 1 : 0;
}
/**
* Rename a file. Returns 1 on success, 0 on failure.
*/
js_file_rename(oldPtr, oldLen, newPtr, newLen) {
const oldPath = this.#readString(oldPtr, oldLen);
const newPath = this.#readString(newPtr, newLen);
const data = this.#registered.get(oldPath);
if (data) {
this.#registered.delete(oldPath);
this.#registered.set(newPath, data);
return 1;
}
const file = this.#browserFiles.get(oldPath);
if (file) {
this.#browserFiles.delete(oldPath);
this.#browserFiles.set(newPath, file);
return 1;
}
return 0;
}
/**
* Create a directory (no-op in memory model, just track it).
* Returns 1 on success.
*/
js_file_mkdir(pathPtr, pathLen) {
const path = this.#readString(pathPtr, pathLen);
this.#directories.add(path);
return 1;
}
/**
* Get the env bindings to merge into the WASM import object.
* @returns {Record<string, Function>}
*/
getEnvBindings() {
return {
js_file_open: (p, l, r) => this.js_file_open(p, l, r),
js_file_create: (p, l) => this.js_file_create(p, l),
js_file_read: (f, b, l, o) => this.js_file_read(f, b, l, o),
js_file_write: (f, d, l, o) => this.js_file_write(f, d, l, o),
js_file_get_size: (f) => this.js_file_get_size(f),
js_file_close: (f) => this.js_file_close(f),
js_file_exists: (p, l) => this.js_file_exists(p, l),
js_file_delete: (p, l) => this.js_file_delete(p, l),
js_file_rename: (op, ol, np, nl) => this.js_file_rename(op, ol, np, nl),
js_file_mkdir: (p, l) => this.js_file_mkdir(p, l),
};
}
}

16
browser/host/package.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "@zig-p2p/browser-host",
"version": "0.1.0",
"description": "Browser host for zig-p2p WASM module",
"type": "module",
"main": "zig-p2p.js",
"exports": {
".": "./zig-p2p.js"
},
"files": [
"zig-p2p.js",
"platform-env.js",
"webrtc-host.js",
"signaling.js"
]
}

View File

@@ -0,0 +1,66 @@
/**
* Platform environment — provides extern "env" functions for the WASM module.
*
* These map directly to the `extern "env" fn js_*` declarations in the Zig
* platform abstraction layer (src/platform/time.zig, random.zig, etc.).
*/
/**
* Create the env import object for WASM instantiation.
* @param {() => WebAssembly.Memory} getMemory - Returns the WASM memory instance
* @returns {Record<string, Function>} env imports
*/
export function createPlatformEnv(getMemory) {
return {
// -- Time (src/platform/time.zig) --
/** @returns {bigint} milliseconds since epoch */
js_timestamp_ms() {
return BigInt(Date.now());
},
/** @returns {bigint} nanoseconds since epoch (ms precision in browser) */
js_timestamp_ns() {
return BigInt(Date.now()) * 1_000_000n;
},
// -- Random (src/platform/random.zig) --
/** Fill buffer with cryptographically secure random bytes */
js_random_bytes(ptr, len) {
const bytes = new Uint8Array(getMemory().buffer, ptr, len);
crypto.getRandomValues(bytes);
},
// -- Logging (src/wasm/main.zig) --
/** Log a message from WASM to the browser console */
js_log(ptr, len) {
const bytes = new Uint8Array(getMemory().buffer, ptr, len);
const msg = new TextDecoder().decode(bytes);
console.log('[zig-p2p]', msg);
},
// -- WebRTC DataChannel (src/platform/webrtc_wasm.zig) --
// These are called by the WASM transport when sending data.
// They are wired to the WebRTCHost by zig-p2p.js during initialization.
/** Send data on a DataChannel. Returns 0 on success, -1 on error. */
js_datachannel_send(channelId, dataPtr, dataLen) {
// Overridden by zig-p2p.js to route to WebRTCHost
console.warn('[zig-p2p] js_datachannel_send called before WebRTCHost wired');
return -1;
},
/** Close a DataChannel */
js_datachannel_close(channelId) {
// Overridden by zig-p2p.js to route to WebRTCHost
},
/** Get buffered amount for a DataChannel */
js_datachannel_buffered_amount(channelId) {
// Overridden by zig-p2p.js to route to WebRTCHost
return 0;
},
};
}

137
browser/host/signaling.js Normal file
View File

@@ -0,0 +1,137 @@
/**
* WebSocket signaling client for WebRTC SDP/ICE exchange.
*
* Connects to the signaling server and relays offers, answers, and ICE
* candidates between peers. The signaling server is a simple JSON relay
* (see browser/signaling-server/server.js).
*/
export class SignalingClient {
/** @type {WebSocket | null} */
#ws = null;
/** @type {string} */
#url;
/** @type {string} */
#peerId;
/** @type {Map<string, Function[]>} */
#handlers = new Map();
/** @type {boolean} */
#connected = false;
/** @type {number | null} */
#heartbeatTimer = null;
/**
* @param {string} url - WebSocket URL of the signaling server
* @param {string} peerId - This peer's unique ID
*/
constructor(url, peerId) {
this.#url = url;
this.#peerId = peerId;
}
get connected() {
return this.#connected;
}
get peerId() {
return this.#peerId;
}
/** Connect to the signaling server. */
connect() {
return new Promise((resolve, reject) => {
this.#ws = new WebSocket(this.#url);
this.#ws.onopen = () => {
this.#connected = true;
// Register our peer ID with the server
this.#send({ type: 'register', peerId: this.#peerId });
// Start heartbeat
this.#heartbeatTimer = setInterval(() => {
if (this.#connected) this.#send({ type: 'ping' });
}, 30_000);
resolve();
};
this.#ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data);
this.#dispatch(msg.type, msg);
} catch (e) {
console.warn('[signaling] Failed to parse message:', e);
}
};
this.#ws.onclose = () => {
this.#connected = false;
this.#stopHeartbeat();
this.#dispatch('disconnect', {});
};
this.#ws.onerror = (err) => {
if (!this.#connected) reject(err);
this.#dispatch('error', { error: err });
};
});
}
/** Disconnect from the signaling server. */
disconnect() {
this.#stopHeartbeat();
if (this.#ws) {
this.#ws.close();
this.#ws = null;
}
this.#connected = false;
}
/** Send an SDP offer to a remote peer. */
sendOffer(to, sdp) {
this.#send({ type: 'offer', to, sdp });
}
/** Send an SDP answer to a remote peer. */
sendAnswer(to, sdp) {
this.#send({ type: 'answer', to, sdp });
}
/** Send an ICE candidate to a remote peer. */
sendCandidate(to, candidate, sdpMid) {
this.#send({ type: 'candidate', to, candidate, sdpMid });
}
/**
* Register an event handler.
* @param {'offer'|'answer'|'candidate'|'error'|'disconnect'} type
* @param {Function} handler
*/
on(type, handler) {
if (!this.#handlers.has(type)) this.#handlers.set(type, []);
this.#handlers.get(type).push(handler);
}
/** Remove all handlers for a given event type. */
off(type) {
this.#handlers.delete(type);
}
#send(msg) {
if (this.#ws && this.#ws.readyState === WebSocket.OPEN) {
this.#ws.send(JSON.stringify(msg));
}
}
#dispatch(type, msg) {
const handlers = this.#handlers.get(type);
if (handlers) {
for (const handler of handlers) handler(msg);
}
}
#stopHeartbeat() {
if (this.#heartbeatTimer !== null) {
clearInterval(this.#heartbeatTimer);
this.#heartbeatTimer = null;
}
}
}

323
browser/host/webrtc-host.js Normal file
View File

@@ -0,0 +1,323 @@
/**
* WebRTC host — manages RTCPeerConnection and DataChannel instances
* on behalf of the WASM module.
*
* The WASM side sees channels as integer IDs. This host maps those IDs
* to browser RTCDataChannel objects and routes events back to WASM via
* the exported callback functions.
*/
export class WebRTCHost {
/** @type {Map<number, RTCDataChannel>} channel_id → DataChannel */
#channels = new Map();
/** @type {Map<number, boolean>} channelId → true if we created the offer */
#channelRoles = new Map();
/** @type {Map<string, RTCPeerConnection>} remote_peer_id → PeerConnection */
#peerConnections = new Map();
/** @type {number} next channel ID to assign */
#nextChannelId = 1;
/** @type {RTCConfiguration} */
#rtcConfig;
/** @type {object | null} WASM exports (set after load) */
#wasm = null;
/** @type {number} WASM instance ID */
#instanceId = 0;
/** @type {import('./signaling.js').SignalingClient | null} */
#signaling = null;
/** @type {Array<(channelId: number, appId: number, payload: Uint8Array) => void>} */
#directHandlers = [];
/** Direct message prefix byte — distinguishes from P2P-framed messages */
static DIRECT_PREFIX = 0xFF;
/**
* @param {RTCConfiguration} [rtcConfig] - ICE server configuration
*/
constructor(rtcConfig) {
this.#rtcConfig = rtcConfig || {
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
};
}
/**
* Bind to WASM exports so we can call back into the module.
* @param {object} wasmExports - The WASM module's exports
* @param {number} instanceId - The P2P instance ID in WASM
*/
bind(wasmExports, instanceId) {
this.#wasm = wasmExports;
this.#instanceId = instanceId;
}
/**
* Bind to a signaling client for SDP/ICE exchange.
* @param {import('./signaling.js').SignalingClient} signaling
*/
bindSignaling(signaling) {
this.#signaling = signaling;
signaling.on('offer', (msg) => this.handleOffer(msg.from, msg.sdp));
signaling.on('answer', (msg) => this.handleAnswer(msg.from, msg.sdp));
signaling.on('candidate', (msg) =>
this.handleCandidate(msg.from, msg.candidate, msg.sdpMid)
);
}
/**
* Initiate a WebRTC connection to a remote peer.
* @param {string} remotePeerId - The remote peer's signaling ID
* @returns {Promise<number>} The channel ID assigned to this connection
*/
async connectToPeer(remotePeerId) {
const pc = this.#createPeerConnection(remotePeerId);
const dc = pc.createDataChannel('zig-p2p', {
protocol: 'zig-p2p',
ordered: true,
});
const channelId = this.#registerChannel(dc);
this.#channelRoles.set(channelId, true); // outbound = initiator
this.#setupDataChannel(dc, channelId);
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
this.#signaling?.sendOffer(remotePeerId, pc.localDescription.sdp);
return channelId;
}
/**
* Handle an incoming SDP offer from a remote peer.
* @param {string} fromPeerId
* @param {string} sdp
*/
async handleOffer(fromPeerId, sdp) {
const pc = this.#createPeerConnection(fromPeerId);
pc.ondatachannel = (event) => {
const dc = event.channel;
const channelId = this.#registerChannel(dc);
this.#channelRoles.set(channelId, false); // inbound = responder
this.#setupDataChannel(dc, channelId);
};
await pc.setRemoteDescription({ type: 'offer', sdp });
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
this.#signaling?.sendAnswer(fromPeerId, pc.localDescription.sdp);
}
/**
* Handle an incoming SDP answer.
* @param {string} fromPeerId
* @param {string} sdp
*/
async handleAnswer(fromPeerId, sdp) {
const pc = this.#peerConnections.get(fromPeerId);
if (!pc) {
console.warn('[webrtc] Got answer from unknown peer:', fromPeerId);
return;
}
await pc.setRemoteDescription({ type: 'answer', sdp });
}
/**
* Handle an incoming ICE candidate.
* @param {string} fromPeerId
* @param {string} candidate
* @param {string} sdpMid
*/
async handleCandidate(fromPeerId, candidate, sdpMid) {
const pc = this.#peerConnections.get(fromPeerId);
if (!pc) return;
await pc.addIceCandidate({ candidate, sdpMid });
}
/**
* Send data on a channel (called by WASM via extern "env").
* @param {number} channelId
* @param {Uint8Array} data
* @returns {number} 0 on success, -1 on error
*/
send(channelId, data) {
const dc = this.#channels.get(channelId);
if (!dc || dc.readyState !== 'open') return -1;
try {
dc.send(data);
return 0;
} catch {
return -1;
}
}
/**
* Close a channel (called by WASM via extern "env").
* @param {number} channelId
*/
closeChannel(channelId) {
const dc = this.#channels.get(channelId);
if (dc) {
dc.close();
this.#channels.delete(channelId);
}
}
/**
* Get buffered amount for a channel (called by WASM via extern "env").
* @param {number} channelId
* @returns {number}
*/
bufferedAmount(channelId) {
const dc = this.#channels.get(channelId);
return dc ? dc.bufferedAmount : 0;
}
/** Close all connections and clean up. */
destroy() {
for (const dc of this.#channels.values()) {
dc.close();
}
this.#channels.clear();
this.#channelRoles.clear();
for (const pc of this.#peerConnections.values()) {
pc.close();
}
this.#peerConnections.clear();
}
/** @returns {number} Number of active channels */
get channelCount() {
return this.#channels.size;
}
/** @returns {number[]} All active channel IDs */
getChannelIds() {
return [...this.#channels.keys()];
}
/**
* Get total buffered amount across all channels (for flow control).
* @returns {number} Sum of all DataChannel bufferedAmount values
*/
get totalBufferedAmount() {
let total = 0;
for (const dc of this.#channels.values()) {
total += dc.bufferedAmount;
}
return total;
}
/**
* Send a pre-formatted direct message on a DataChannel.
* The caller must include the [0xFF][app_id] prefix in the data.
* This avoids an extra copy for large payloads.
* @param {number} channelId
* @param {Uint8Array} data - Complete message including 0xFF prefix
* @returns {boolean} true on success
*/
sendDirect(channelId, data) {
const dc = this.#channels.get(channelId);
if (!dc || dc.readyState !== 'open') return false;
try {
dc.send(data);
return true;
} catch {
return false;
}
}
/**
* Register a handler for direct messages (0xFF-prefixed).
* Handler receives (channelId, appId, payload).
* @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler
*/
registerDirectHandler(handler) {
this.#directHandlers.push(handler);
}
// -- Private helpers --
#createPeerConnection(remotePeerId) {
// Close existing connection to same peer if any
const existing = this.#peerConnections.get(remotePeerId);
if (existing) existing.close();
const pc = new RTCPeerConnection(this.#rtcConfig);
this.#peerConnections.set(remotePeerId, pc);
pc.onicecandidate = (event) => {
if (event.candidate) {
this.#signaling?.sendCandidate(
remotePeerId,
event.candidate.candidate,
event.candidate.sdpMid
);
}
};
pc.onconnectionstatechange = () => {
if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
this.#peerConnections.delete(remotePeerId);
}
};
return pc;
}
#registerChannel(dc) {
const channelId = this.#nextChannelId++;
this.#channels.set(channelId, dc);
return channelId;
}
#setupDataChannel(dc, channelId) {
dc.binaryType = 'arraybuffer';
dc.onopen = () => {
const isInitiator = this.#channelRoles.get(channelId) ?? false;
this.#wasm?.wasm_on_datachannel_open(this.#instanceId, channelId, isInitiator ? 1 : 0);
};
dc.onmessage = (event) => {
const data = new Uint8Array(event.data);
// Direct message path: 0xFF prefix → JS handlers only, never enters WASM.
// This eliminates 3 alloc+copy cycles per message through the WASM stack.
if (data.length >= 2 && data[0] === WebRTCHost.DIRECT_PREFIX) {
const appId = data[1];
const payload = data.subarray(2);
for (const handler of this.#directHandlers) {
try { handler(channelId, appId, payload); } catch {}
}
return;
}
// P2P-framed message → route through WASM
if (!this.#wasm) return;
const ptr = this.#wasm.wasm_alloc(data.length);
if (!ptr) {
console.warn('[webrtc] Failed to allocate WASM memory for message');
return;
}
const wasmBuf = new Uint8Array(this.#wasm.memory.buffer, ptr, data.length);
wasmBuf.set(data);
this.#wasm.wasm_on_datachannel_message(
this.#instanceId,
channelId,
ptr,
data.length
);
this.#wasm.wasm_free(ptr, data.length);
};
dc.onclose = () => {
this.#wasm?.wasm_on_datachannel_close(this.#instanceId, channelId);
this.#channels.delete(channelId);
this.#channelRoles.delete(channelId);
};
dc.onerror = () => {
this.#wasm?.wasm_on_datachannel_error(this.#instanceId, channelId);
};
}
}

461
browser/host/zig-p2p.js Normal file
View File

@@ -0,0 +1,461 @@
/**
* zig-p2p Browser Host
*
* Loads the WASM module, provides platform APIs, and manages WebRTC
* connections. The entire P2P protocol (Noise, DHT, messaging, wire
* envelope) runs inside WASM — this is a thin glue layer.
*
* Usage:
* import { ZigP2P } from './zig-p2p.js';
*
* const p2p = await ZigP2P.load('/zig-p2p.wasm', {
* signalingUrl: 'ws://localhost:8080',
* iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
* });
*
* p2p.onMessage((peerId, appId, data) => { ... });
* await p2p.connectToPeer('remote-peer-id');
* p2p.send(peerId, 0x03, new Uint8Array([1, 2, 3]));
*/
import { createPlatformEnv } from './platform-env.js';
import { WebRTCHost } from './webrtc-host.js';
import { SignalingClient } from './signaling.js';
import { FileHost } from './file-host.js';
export class ZigP2P {
/** @type {WebAssembly.Instance} */
#wasmInstance;
/** @type {WebAssembly.Memory} */
#memory;
/** @type {object} WASM exports */
#exports;
/** @type {number} WASM P2P instance ID */
#instanceId;
/** @type {WebRTCHost} */
#webrtcHost;
/** @type {SignalingClient} */
#signaling;
/** @type {number | null} update interval handle */
#updateTimer = null;
/** @type {Function[]} message handlers */
#messageHandlers = [];
/** @type {Function[]} connection handlers */
#connectionHandlers = [];
/** @type {Function[]} file event handlers */
#fileEventHandlers = [];
/** @type {FileHost} */
#fileHost;
/** @type {boolean} */
#destroyed = false;
/** @type {number} WASM pointer for event polling buffer */
#eventBufPtr = 0;
/** @type {number} */
#eventBufLen = 0;
/** @type {Map<number, number>} channelId → channelId (identity, for reverse lookup from peerId) */
#peerIdToChannel = new Map(); // peerId hex → channelId
/**
* Load the WASM module and initialize the P2P library.
*
* @param {string | URL | ArrayBuffer} wasmSource - URL to .wasm file, or raw bytes
* @param {object} config
* @param {string} config.signalingUrl - WebSocket URL of the signaling server
* @param {string} [config.peerId] - Peer ID for signaling (random if not set)
* @param {number} [config.listenPort=0] - Port (unused in browser, passed to WASM init)
* @param {RTCConfiguration} [config.rtcConfig] - WebRTC ICE configuration
* @param {number} [config.updateIntervalMs=16] - How often to call wasm_p2p_update
* @returns {Promise<ZigP2P>}
*/
static async load(wasmSource, config) {
const instance = new ZigP2P();
await instance.#init(wasmSource, config);
return instance;
}
async #init(wasmSource, config) {
const {
signalingUrl,
peerId = crypto.randomUUID(),
listenPort = 0,
rtcConfig,
updateIntervalMs = 16,
} = config;
// 1. Create WebRTC host and file host
this.#webrtcHost = new WebRTCHost(rtcConfig);
let memory;
this.#fileHost = new FileHost(() => memory);
// 2. Create platform env with WebRTC + file wiring
const env = {
...createPlatformEnv(() => memory),
...this.#fileHost.getEnvBindings(),
};
// Wire datachannel extern "env" functions to the WebRTC host
env.js_datachannel_send = (channelId, dataPtr, dataLen) => {
const data = new Uint8Array(memory.buffer, dataPtr, dataLen);
return this.#webrtcHost.send(channelId, data);
};
env.js_datachannel_close = (channelId) => {
this.#webrtcHost.closeChannel(channelId);
};
env.js_datachannel_buffered_amount = (channelId) => {
return this.#webrtcHost.bufferedAmount(channelId);
};
// 3. Load WASM module
let wasmBytes;
if (wasmSource instanceof ArrayBuffer) {
wasmBytes = wasmSource;
} else {
const response = await fetch(wasmSource);
wasmBytes = await response.arrayBuffer();
}
const { instance } = await WebAssembly.instantiate(wasmBytes, { env });
this.#wasmInstance = instance;
this.#exports = instance.exports;
memory = instance.exports.memory;
this.#memory = memory;
// 4. Initialize P2P instance in WASM
this.#instanceId = this.#exports.wasm_p2p_init(listenPort);
if (this.#instanceId < 0) {
throw new Error('Failed to initialize P2P instance in WASM');
}
// 5. Bind WebRTC host to WASM exports
this.#webrtcHost.bind(
{ ...this.#exports, memory: this.#memory },
this.#instanceId
);
// 6. Connect to signaling server
this.#signaling = new SignalingClient(signalingUrl, peerId);
this.#webrtcHost.bindSignaling(this.#signaling);
await this.#signaling.connect();
// 7. Allocate event polling buffer (reused every tick)
// 2MB to support large file chunks (up to 1MB+ per message)
this.#eventBufPtr = this.#exports.wasm_alloc(2097152);
this.#eventBufLen = 2097152;
// 8. Start update loop
this.#updateTimer = setInterval(() => {
if (!this.#destroyed) {
this.#exports.wasm_p2p_update(this.#instanceId);
this.#drainEvents();
}
}, updateIntervalMs);
}
/**
* Connect to a remote peer via WebRTC (through signaling server).
* @param {string} remotePeerId - The remote peer's signaling ID
* @returns {Promise<number>} Channel ID
*/
async connectToPeer(remotePeerId) {
return this.#webrtcHost.connectToPeer(remotePeerId);
}
/**
* Get the 32-byte P2P PeerId for a given WebRTC channel.
* @param {number} channelId - The WebRTC channel ID
* @returns {Uint8Array | null} 32-byte PeerId, or null on failure
*/
getPeerIdForChannel(channelId) {
if (this.#destroyed) return null;
const outPtr = this.#exports.wasm_alloc(32);
if (!outPtr) return null;
try {
const result = this.#exports.wasm_get_peer_id_for_channel(
this.#instanceId,
channelId,
outPtr
);
if (result !== 0) return null;
const bytes = new Uint8Array(32);
bytes.set(new Uint8Array(this.#memory.buffer, outPtr, 32));
return bytes;
} finally {
this.#exports.wasm_free(outPtr, 32);
}
}
/**
* Send a message to a peer.
* @param {Uint8Array} peerId - 32-byte peer ID
* @param {number} appId - Application ID byte
* @param {Uint8Array} data - Message payload
* @returns {boolean} true on success
*/
send(peerId, appId, data) {
if (this.#destroyed) return false;
// Allocate WASM memory for peer ID + data
const peerPtr = this.#exports.wasm_alloc(peerId.length);
const dataPtr = this.#exports.wasm_alloc(data.length);
if (!peerPtr || !dataPtr) return false;
try {
new Uint8Array(this.#memory.buffer, peerPtr, peerId.length).set(peerId);
new Uint8Array(this.#memory.buffer, dataPtr, data.length).set(data);
const result = this.#exports.wasm_p2p_send(
this.#instanceId,
peerPtr,
appId,
dataPtr,
data.length
);
return result === 0;
} finally {
this.#exports.wasm_free(peerPtr, peerId.length);
this.#exports.wasm_free(dataPtr, data.length);
}
}
/**
* Register a message handler.
* @param {(peerId: Uint8Array, appId: number, data: Uint8Array) => void} handler
*/
onMessage(handler) {
this.#messageHandlers.push(handler);
}
/**
* Register a connection handler.
* @param {(peerId: string, channelId: number) => void} handler
*/
onConnection(handler) {
this.#connectionHandlers.push(handler);
}
/**
* Send a pre-formatted direct message on a DataChannel, bypassing WASM.
* The data must include the [0xFF][app_id] prefix. Use for high-throughput
* data (file chunks) where WASM alloc/copy overhead is wasteful.
* @param {number} channelId - The WebRTC channel ID
* @param {Uint8Array} data - Complete message including 0xFF prefix
* @returns {boolean} true on success
*/
sendDirect(channelId, data) {
if (this.#destroyed) return false;
return this.#webrtcHost.sendDirect(channelId, data);
}
/**
* Register a handler for direct messages (bypasses WASM).
* @param {(channelId: number, appId: number, payload: Uint8Array) => void} handler
*/
onDirectMessage(handler) {
this.#webrtcHost.registerDirectHandler(handler);
}
/**
* Get all active channel IDs.
* @returns {number[]}
*/
getChannelIds() {
return this.#webrtcHost.getChannelIds();
}
/** @returns {number} Library version from WASM */
get version() {
return this.#exports.wasm_version();
}
/** @returns {string} This peer's signaling ID */
get peerId() {
return this.#signaling.peerId;
}
/** @returns {boolean} Whether connected to signaling server */
get signalingConnected() {
return this.#signaling.connected;
}
/** @returns {number} Number of active WebRTC channels */
get channelCount() {
return this.#webrtcHost.channelCount;
}
/** @returns {number} Total buffered bytes across all DataChannels (for flow control) */
get totalBufferedAmount() {
return this.#webrtcHost.totalBufferedAmount;
}
/** Drain pending events from the WASM P2P event queue. */
#drainEvents() {
if (!this.#eventBufPtr) return;
for (let i = 0; i < 4096; i++) {
const n = this.#exports.wasm_poll_event(
this.#instanceId,
this.#eventBufPtr,
this.#eventBufLen
);
if (n <= 0) break;
const buf = new Uint8Array(this.#memory.buffer, this.#eventBufPtr, n);
const eventType = buf[0];
if (eventType === 1 && n >= 34) {
// message_received: [1][app_id:1][peer_id:32][data:N]
const appId = buf[1];
const peerId = new Uint8Array(buf.slice(2, 34));
const data = new Uint8Array(buf.slice(34, n));
for (const handler of this.#messageHandlers) {
try { handler(peerId, appId, data); } catch {}
}
} else if (eventType === 2 && n >= 33) {
// peer_connected: [2][peer_id:32]
const peerId = new Uint8Array(buf.slice(1, 33));
const peerHex = Array.from(peerId.slice(0, 8))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
for (const handler of this.#connectionHandlers) {
try { handler(peerHex, 0); } catch {}
}
}
// type 3 (peer_disconnected) — not wired yet
else if (eventType === 4 && n >= 13) {
// file_shared: [4][session_id:8 LE][path_len:4 LE][path:N]
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
const sessionId = view.getBigUint64(1, true);
const pathLen = view.getUint32(9, true);
const path = new TextDecoder().decode(buf.slice(13, 13 + pathLen));
for (const handler of this.#fileEventHandlers) {
try { handler({ type: 'shared', sessionId, path }); } catch {}
}
} else if (eventType === 5 && n >= 13) {
// file_download_started: [5][session_id:8 LE][name_len:4 LE][name:N]
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
const sessionId = view.getBigUint64(1, true);
const nameLen = view.getUint32(9, true);
const name = new TextDecoder().decode(buf.slice(13, 13 + nameLen));
for (const handler of this.#fileEventHandlers) {
try { handler({ type: 'download_started', sessionId, name }); } catch {}
}
} else if (eventType === 6 && n >= 9) {
// file_download_completed: [6][session_id:8 LE]
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
const sessionId = view.getBigUint64(1, true);
for (const handler of this.#fileEventHandlers) {
try { handler({ type: 'download_completed', sessionId }); } catch {}
}
} else if (eventType === 7 && n >= 9) {
// file_download_failed: [7][session_id:8 LE]
const view = new DataView(this.#memory.buffer, this.#eventBufPtr, n);
const sessionId = view.getBigUint64(1, true);
for (const handler of this.#fileEventHandlers) {
try { handler({ type: 'download_failed', sessionId }); } catch {}
}
}
}
}
// ============================================================
// File Transfer API
// ============================================================
/**
* Register a file event handler.
* @param {(event: { type: string, sessionId: bigint, path?: string, name?: string }) => void} handler
*/
onFileEvent(handler) {
this.#fileEventHandlers.push(handler);
}
/**
* Share a file with connected peers.
*
* For small files (<50MB): materializes into WASM memory and registers
* with the Zig file manager (full hashing + session management).
*
* For large files: registers the File handle for streaming JS-level
* transfer (no WASM hashing, no full memory copy).
*
* @param {File} file - Browser File object to share
* @returns {Promise<{ virtualPath: string, size: number }>}
*/
async shareFile(file) {
if (this.#destroyed) throw new Error('Instance destroyed');
const MATERIALIZE_THRESHOLD = 50 * 1024 * 1024; // 50MB
const virtualPath = this.#fileHost.registerBrowserFile(file);
if (file.size <= MATERIALIZE_THRESHOLD) {
// Small file: materialize and register with WASM file manager
await this.#fileHost.materializeFile(virtualPath);
const pathBytes = new TextEncoder().encode(virtualPath);
const pathPtr = this.#exports.wasm_alloc(pathBytes.length);
if (!pathPtr) throw new Error('WASM alloc failed');
try {
new Uint8Array(this.#memory.buffer, pathPtr, pathBytes.length).set(pathBytes);
const sessionId = this.#exports.wasm_file_share(
this.#instanceId,
pathPtr,
pathBytes.length
);
// wasm_file_share returns -1n (i64) on error; valid session IDs are
// u64 values that may appear negative in signed BigInt when > 2^63.
if (sessionId === -1n) throw new Error('Failed to share file');
} finally {
this.#exports.wasm_free(pathPtr, pathBytes.length);
}
}
// Large files: File handle is stored in FileHost for streaming reads.
// The JS-level transfer (demo.js) reads via fileHost.readFileChunk().
return { virtualPath, size: file.size };
}
/**
* Get a completed download as a Blob for saving.
* @param {string} name - File name (virtual path)
* @returns {Blob | null}
*/
getDownloadBlob(name) {
return this.#fileHost.getFileBlob(name);
}
/**
* Trigger a browser download for a completed file.
* @param {string} name - File name
*/
downloadToDesktop(name) {
const blob = this.#fileHost.getFileBlob(name);
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = name;
a.click();
URL.revokeObjectURL(url);
}
/** @returns {FileHost} The file host for advanced use */
get fileHost() {
return this.#fileHost;
}
/** Shut down everything. */
destroy() {
this.#destroyed = true;
if (this.#updateTimer !== null) {
clearInterval(this.#updateTimer);
this.#updateTimer = null;
}
this.#webrtcHost.destroy();
this.#signaling.disconnect();
if (this.#instanceId >= 0) {
this.#exports.wasm_p2p_deinit(this.#instanceId);
}
if (this.#eventBufPtr) {
this.#exports.wasm_free(this.#eventBufPtr, this.#eventBufLen);
this.#eventBufPtr = 0;
}
}
}

View File

@@ -0,0 +1,36 @@
{
"name": "@zig-p2p/signaling-server",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@zig-p2p/signaling-server",
"version": "0.1.0",
"dependencies": {
"ws": "^8.18.0"
}
},
"node_modules/ws": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz",
"integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

View File

@@ -0,0 +1,13 @@
{
"name": "@zig-p2p/signaling-server",
"version": "0.1.0",
"description": "WebSocket signaling relay for zig-p2p WebRTC connections",
"type": "module",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"ws": "^8.18.0"
}
}

View File

@@ -0,0 +1,212 @@
/**
* zig-p2p Signaling Server
*
* Simple WebSocket relay that routes SDP offers/answers and ICE candidates
* between peers by peerId. No authentication — the Noise handshake over
* the resulting WebRTC DataChannel provides mutual authentication.
*
* Protocol (JSON over WebSocket):
*
* Client → Server:
* { "type": "register", "peerId": "abc123" }
* { "type": "offer", "to": "xyz789", "sdp": "v=0..." }
* { "type": "answer", "to": "abc123", "sdp": "v=0..." }
* { "type": "candidate", "to": "xyz789", "candidate": "...", "sdpMid": "0" }
* { "type": "ping" }
*
* Server → Client:
* { "type": "registered", "peerId": "abc123" }
* { "type": "offer", "from": "abc123", "sdp": "v=0..." }
* { "type": "answer", "from": "xyz789", "sdp": "v=0..." }
* { "type": "candidate", "from": "abc123", "candidate": "...", "sdpMid": "0" }
* { "type": "error", "message": "peer not found" }
* { "type": "pong" }
*
* Usage:
* npm install
* node server.js [--port 8080] [--host 0.0.0.0]
*/
import { WebSocketServer } from 'ws';
// -- Configuration --
const args = process.argv.slice(2);
function getArg(name, defaultVal) {
const idx = args.indexOf(name);
return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : defaultVal;
}
const PORT = parseInt(getArg('--port', '8080'), 10);
const HOST = getArg('--host', '0.0.0.0');
const HEARTBEAT_INTERVAL_MS = 30_000;
const STALE_TIMEOUT_MS = 90_000;
const MAX_MESSAGE_RATE = 100; // messages per second per client
const MAX_MESSAGE_SIZE = 65536; // 64KB max message
// -- State --
/** @type {Map<string, WebSocket>} peerId → WebSocket */
const peers = new Map();
/** @type {Map<WebSocket, PeerState>} */
const state = new Map();
/**
* @typedef {object} PeerState
* @property {string} peerId
* @property {number} lastActivity - timestamp ms
* @property {number} messageCount - messages in current window
* @property {number} windowStart - start of rate limit window
*/
// -- Server --
const wss = new WebSocketServer({
port: PORT,
host: HOST,
maxPayload: MAX_MESSAGE_SIZE,
});
console.log(`[signaling] Listening on ws://${HOST}:${PORT}`);
wss.on('connection', (ws) => {
state.set(ws, {
peerId: null,
lastActivity: Date.now(),
messageCount: 0,
windowStart: Date.now(),
});
ws.on('message', (raw) => {
const s = state.get(ws);
if (!s) return;
// Rate limiting
const now = Date.now();
if (now - s.windowStart > 1000) {
s.messageCount = 0;
s.windowStart = now;
}
s.messageCount++;
if (s.messageCount > MAX_MESSAGE_RATE) {
send(ws, { type: 'error', message: 'rate limit exceeded' });
return;
}
s.lastActivity = now;
let msg;
try {
msg = JSON.parse(raw.toString());
} catch {
send(ws, { type: 'error', message: 'invalid JSON' });
return;
}
handleMessage(ws, s, msg);
});
ws.on('close', () => {
const s = state.get(ws);
if (s?.peerId) {
peers.delete(s.peerId);
console.log(`[signaling] Peer disconnected: ${s.peerId} (${peers.size} online)`);
}
state.delete(ws);
});
ws.on('error', () => {
// Handled by 'close' event
});
});
// -- Message handling --
function handleMessage(ws, s, msg) {
switch (msg.type) {
case 'register': {
const { peerId } = msg;
if (!peerId || typeof peerId !== 'string') {
send(ws, { type: 'error', message: 'peerId required' });
return;
}
// Disconnect existing peer with same ID
const existing = peers.get(peerId);
if (existing && existing !== ws) {
send(existing, { type: 'error', message: 'replaced by new connection' });
existing.close();
}
s.peerId = peerId;
peers.set(peerId, ws);
send(ws, { type: 'registered', peerId });
console.log(`[signaling] Peer registered: ${peerId} (${peers.size} online)`);
break;
}
case 'offer':
case 'answer':
case 'candidate': {
if (!s.peerId) {
send(ws, { type: 'error', message: 'must register first' });
return;
}
const { to } = msg;
if (!to || typeof to !== 'string') {
send(ws, { type: 'error', message: '"to" field required' });
return;
}
const target = peers.get(to);
if (!target) {
send(ws, { type: 'error', message: 'peer not found' });
return;
}
// Forward with "from" field added
const forwarded = { ...msg, from: s.peerId };
delete forwarded.to;
send(target, forwarded);
break;
}
case 'ping':
send(ws, { type: 'pong' });
break;
default:
send(ws, { type: 'error', message: `unknown type: ${msg.type}` });
}
}
function send(ws, msg) {
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify(msg));
}
}
// -- Heartbeat / stale cleanup --
const heartbeatTimer = setInterval(() => {
const now = Date.now();
for (const [ws, s] of state) {
if (now - s.lastActivity > STALE_TIMEOUT_MS) {
console.log(`[signaling] Dropping stale peer: ${s.peerId}`);
ws.terminate();
}
}
}, HEARTBEAT_INTERVAL_MS);
// -- Graceful shutdown --
function shutdown() {
console.log('[signaling] Shutting down...');
clearInterval(heartbeatTimer);
for (const ws of state.keys()) {
ws.close();
}
wss.close(() => {
console.log('[signaling] Closed.');
process.exit(0);
});
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

482
build.zig
View File

@@ -10,6 +10,35 @@ pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
// ============================================================
// Sync Module (platform-aware synchronization primitives)
// ============================================================
const sync_module = b.addModule("sync", .{
.root_source_file = b.path("src/platform/sync.zig"),
.target = target,
.optimize = optimize,
});
// ============================================================
// Time Module (platform-aware time functions)
// ============================================================
const time_module = b.addModule("time", .{
.root_source_file = b.path("src/platform/time.zig"),
.target = target,
.optimize = optimize,
});
// ============================================================
// Platform Module
// ============================================================
const platform_module = b.addModule("platform", .{
.root_source_file = b.path("src/platform.zig"),
.target = target,
.optimize = optimize,
});
platform_module.addImport("sync", sync_module);
platform_module.addImport("time", time_module);
// ============================================================
// Core Module
// ============================================================
@@ -18,6 +47,10 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = optimize,
});
core_module.addImport("sync", sync_module);
core_module.addImport("time", time_module);
core_module.addImport("platform", platform_module);
platform_module.addImport("core", core_module);
// ============================================================
// Network Module
@@ -28,6 +61,8 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});
network_module.addImport("core", core_module);
network_module.addImport("sync", sync_module);
network_module.addImport("platform", platform_module);
// ============================================================
// Protocol Module
@@ -38,7 +73,9 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});
protocol_module.addImport("core", core_module);
protocol_module.addImport("sync", sync_module);
protocol_module.addImport("network", network_module);
protocol_module.addImport("platform", platform_module);
// ============================================================
// Files Module
@@ -50,7 +87,9 @@ pub fn build(b: *std.Build) void {
.link_libc = true,
});
files_module.addImport("core", core_module);
files_module.addImport("sync", sync_module);
files_module.addImport("protocol", protocol_module);
files_module.addImport("platform", platform_module);
// ============================================================
// Noise Protocol Module
@@ -61,6 +100,8 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});
noise_module.addImport("platform", platform_module);
// Add noise to network module for SecureConnection
network_module.addImport("noise", noise_module);
@@ -73,11 +114,50 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});
p2p_module.addImport("core", core_module);
p2p_module.addImport("sync", sync_module);
p2p_module.addImport("platform", platform_module);
p2p_module.addImport("network", network_module);
p2p_module.addImport("protocol", protocol_module);
p2p_module.addImport("files", files_module);
p2p_module.addImport("noise", noise_module);
// WebRTC Bridge module — separate from platform to avoid circular deps
const webrtc_bridge_module = b.addModule("webrtc_bridge", .{
.root_source_file = b.path("src/platform/webrtc_bridge.zig"),
.target = target,
.optimize = optimize,
});
webrtc_bridge_module.addImport("core", core_module);
webrtc_bridge_module.addImport("sync", sync_module);
webrtc_bridge_module.addImport("platform", platform_module);
webrtc_bridge_module.addImport("network", network_module);
webrtc_bridge_module.addImport("noise", noise_module);
webrtc_bridge_module.addImport("p2p", p2p_module);
// ============================================================
// MWP (Mutual Witness Protocol) Core Library
// ============================================================
const mwp_lib_module = b.addModule("mwp_lib", .{
.root_source_file = b.path("src/mwp/mwp.zig"),
.target = target,
.optimize = optimize,
});
mwp_lib_module.addImport("sync", sync_module);
mwp_lib_module.addImport("platform", platform_module);
// ============================================================
// MWP Integration Module (user-facing API)
// ============================================================
const mwp_module = b.addModule("mwp", .{
.root_source_file = b.path("src/mwp_integration.zig"),
.target = target,
.optimize = optimize,
});
mwp_module.addImport("p2p", p2p_module);
mwp_module.addImport("mwp_lib", mwp_lib_module);
mwp_module.addImport("sync", sync_module);
mwp_module.addImport("platform", platform_module);
// ============================================================
// Example Executables
// ============================================================
@@ -124,6 +204,116 @@ pub fn build(b: *std.Build) void {
const run_client_step = b.step("run-client", "Run the example client");
run_client_step.dependOn(&run_client.step);
// MWP Demo example
const mwp_demo_module = b.createModule(.{
.root_source_file = b.path("examples/mwp_demo.zig"),
.target = target,
.optimize = .Debug,
});
mwp_demo_module.addImport("p2p", p2p_module);
mwp_demo_module.addImport("mwp", mwp_module);
const mwp_demo = b.addExecutable(.{
.name = "mwp-demo",
.root_module = mwp_demo_module,
});
b.installArtifact(mwp_demo);
const run_mwp = b.addRunArtifact(mwp_demo);
run_mwp.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_mwp.addArgs(args);
}
const run_mwp_step = b.step("run-mwp", "Run the MWP demo");
run_mwp_step.dependOn(&run_mwp.step);
// Bootstrap Node (headless, for VPS deployment)
const bootstrap_module = b.createModule(.{
.root_source_file = b.path("examples/bootstrap_node.zig"),
.target = target,
.optimize = optimize,
});
bootstrap_module.addImport("p2p", p2p_module);
bootstrap_module.addImport("core", core_module);
bootstrap_module.addImport("network", network_module);
bootstrap_module.addImport("mwp", mwp_module);
const bootstrap_exe = b.addExecutable(.{
.name = "bootstrap-node",
.root_module = bootstrap_module,
});
b.installArtifact(bootstrap_exe);
const run_bootstrap = b.addRunArtifact(bootstrap_exe);
run_bootstrap.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_bootstrap.addArgs(args);
}
const run_bootstrap_step = b.step("run-bootstrap", "Run the headless bootstrap node");
run_bootstrap_step.dependOn(&run_bootstrap.step);
// WebRTC Bridge demo
const bridge_demo_module = b.createModule(.{
.root_source_file = b.path("examples/webrtc_bridge_demo.zig"),
.target = target,
.optimize = optimize,
});
bridge_demo_module.addImport("p2p", p2p_module);
bridge_demo_module.addImport("platform", platform_module);
bridge_demo_module.addImport("webrtc_bridge", webrtc_bridge_module);
bridge_demo_module.addImport("network", network_module);
bridge_demo_module.addImport("core", core_module);
bridge_demo_module.addImport("files", files_module);
const bridge_demo = b.addExecutable(.{
.name = "webrtc-bridge-demo",
.root_module = bridge_demo_module,
});
b.installArtifact(bridge_demo);
const run_bridge_demo = b.addRunArtifact(bridge_demo);
run_bridge_demo.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_bridge_demo.addArgs(args);
}
const run_bridge_step = b.step("run-webrtc-bridge", "Run the WebRTC bridge demo");
run_bridge_step.dependOn(&run_bridge_demo.step);
// WebRTC Bridge TUI demo (vaxis)
// Step is registered unconditionally so `zig build run-webrtc-bridge-tui` triggers
// the lazy dependency fetch of vaxis.
const run_bridge_tui_step = b.step("run-webrtc-bridge-tui", "Run the WebRTC bridge TUI demo");
if (b.lazyDependency("vaxis", .{})) |vaxis_dep| {
const vaxis_mod = vaxis_dep.module("vaxis");
const bridge_tui_module = b.createModule(.{
.root_source_file = b.path("examples/webrtc_bridge_demo_tui.zig"),
.target = target,
.optimize = optimize,
});
bridge_tui_module.addImport("p2p", p2p_module);
bridge_tui_module.addImport("platform", platform_module);
bridge_tui_module.addImport("webrtc_bridge", webrtc_bridge_module);
bridge_tui_module.addImport("network", network_module);
bridge_tui_module.addImport("core", core_module);
bridge_tui_module.addImport("files", files_module);
bridge_tui_module.addImport("vaxis", vaxis_mod);
bridge_tui_module.addImport("mwp", mwp_module);
const bridge_tui = b.addExecutable(.{
.name = "webrtc-bridge-tui",
.root_module = bridge_tui_module,
});
b.installArtifact(bridge_tui);
const run_bridge_tui = b.addRunArtifact(bridge_tui);
run_bridge_tui.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_bridge_tui.addArgs(args);
}
run_bridge_tui_step.dependOn(&run_bridge_tui.step);
}
// Encrypted server example (Noise Protocol)
const encrypted_server_module = b.createModule(.{
.root_source_file = b.path("examples/encrypted_server.zig"),
@@ -333,6 +523,7 @@ pub fn build(b: *std.Build) void {
b.installArtifact(multi_peer_test);
const run_multi_peer_test = b.addRunArtifact(multi_peer_test);
run_multi_peer_test.setCwd(b.path("."));
run_multi_peer_test.step.dependOn(b.getInstallStep());
const run_multi_peer_test_step = b.step("run-multi-peer-test", "Run multi-peer download test (1GB from 10 peers)");
run_multi_peer_test_step.dependOn(&run_multi_peer_test.step);
@@ -354,6 +545,7 @@ pub fn build(b: *std.Build) void {
b.installArtifact(multi_file_swarm_test);
const run_multi_file_swarm = b.addRunArtifact(multi_file_swarm_test);
run_multi_file_swarm.setCwd(b.path("."));
run_multi_file_swarm.step.dependOn(b.getInstallStep());
const run_multi_file_swarm_step = b.step("run-swarm-test", "Run multi-file swarm test (9 peers, 2 files)");
run_multi_file_swarm_step.dependOn(&run_multi_file_swarm.step);
@@ -375,6 +567,7 @@ pub fn build(b: *std.Build) void {
b.installArtifact(swarm_chaos_test);
const run_swarm_chaos = b.addRunArtifact(swarm_chaos_test);
run_swarm_chaos.setCwd(b.path("."));
run_swarm_chaos.step.dependOn(b.getInstallStep());
const run_swarm_chaos_step = b.step("run-chaos-test", "Run swarm chaos test (seeder failure, cascading, late joiners)");
run_swarm_chaos_step.dependOn(&run_swarm_chaos.step);
@@ -790,6 +983,23 @@ pub fn build(b: *std.Build) void {
const test_e2e_step = b.step("test-e2e", "Run E2E file transfer tests");
test_e2e_step.dependOn(&run_test_e2e.step);
// Test Real E2E (peer connection, messaging, lifecycle)
const test_real_e2e_module = b.createModule(.{
.root_source_file = b.path("tests/integration/test_real_e2e.zig"),
.target = target,
.optimize = .Debug,
});
test_real_e2e_module.addImport("core", core_module);
test_real_e2e_module.addImport("network", network_module);
test_real_e2e_module.addImport("p2p", p2p_module);
const test_real_e2e = b.addTest(.{
.root_module = test_real_e2e_module,
});
const run_test_real_e2e = b.addRunArtifact(test_real_e2e);
const test_real_e2e_step = b.step("test-real-e2e", "Run real E2E integration tests");
test_real_e2e_step.dependOn(&run_test_real_e2e.step);
// Test Noise Protocol Encrypted Connections
const test_noise_connection_module = b.createModule(.{
.root_source_file = b.path("tests/integration/test_noise_connection.zig"),
@@ -857,6 +1067,21 @@ pub fn build(b: *std.Build) void {
const test_replay_protection_step = b.step("test-replay-protection", "Run replay protection comprehensive tests");
test_replay_protection_step.dependOn(&run_test_replay_protection.step);
// Test Replay Integration
const test_replay_integration_module = b.createModule(.{
.root_source_file = b.path("tests/protocol/test_replay_integration.zig"),
.target = target,
.optimize = .Debug,
});
test_replay_integration_module.addImport("protocol", protocol_module);
const test_replay_integration = b.addTest(.{
.root_module = test_replay_integration_module,
});
const run_test_replay_integration = b.addRunArtifact(test_replay_integration);
const test_replay_integration_step = b.step("test-replay-integration", "Run replay protection integration tests");
test_replay_integration_step.dependOn(&run_test_replay_integration.step);
// Test Transfer Protocol
const test_transfer_protocol_module = b.createModule(.{
.root_source_file = b.path("tests/files/test_transfer_protocol.zig"),
@@ -1236,6 +1461,22 @@ pub fn build(b: *std.Build) void {
const test_serializer_extended_step = b.step("test-serializer", "Run serializer extended tests");
test_serializer_extended_step.dependOn(&run_test_serializer_extended.step);
// Test IP Reflection (Bundled STUN) variable-length encoding
const test_ip_reflection_module = b.createModule(.{
.root_source_file = b.path("tests/protocol/test_ip_reflection.zig"),
.target = target,
.optimize = .Debug,
});
test_ip_reflection_module.addImport("protocol", protocol_module);
test_ip_reflection_module.addImport("p2p", p2p_module);
const test_ip_reflection = b.addTest(.{
.root_module = test_ip_reflection_module,
});
const run_test_ip_reflection = b.addRunArtifact(test_ip_reflection);
const test_ip_reflection_step = b.step("test-ip-reflection", "Run IP Reflection variable-length encoding tests");
test_ip_reflection_step.dependOn(&run_test_ip_reflection.step);
// Test Discovery Extended
const test_discovery_extended_module = b.createModule(.{
.root_source_file = b.path("tests/network/test_discovery_extended.zig"),
@@ -1722,6 +1963,8 @@ pub fn build(b: *std.Build) void {
.optimize = .Debug,
});
test_p2p_module.addImport("core", core_module);
test_p2p_module.addImport("sync", sync_module);
test_p2p_module.addImport("platform", platform_module);
test_p2p_module.addImport("network", network_module);
test_p2p_module.addImport("protocol", protocol_module);
test_p2p_module.addImport("files", files_module);
@@ -1739,6 +1982,20 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = .Debug,
});
test_core_module.addImport("sync", sync_module);
test_core_module.addImport("time", time_module);
// Create a test-specific platform module that points back to test_core_module
// to avoid "file exists in modules 'root' and 'core'" conflict
// (since test root IS core.zig, platform's core dep must be the same module)
const test_core_platform = b.createModule(.{
.root_source_file = b.path("src/platform.zig"),
.target = target,
.optimize = .Debug,
});
test_core_platform.addImport("sync", sync_module);
test_core_platform.addImport("time", time_module);
test_core_platform.addImport("core", test_core_module);
test_core_module.addImport("platform", test_core_platform);
const test_core = b.addTest(.{
.root_module = test_core_module,
});
@@ -1753,6 +2010,8 @@ pub fn build(b: *std.Build) void {
.optimize = .Debug,
});
test_network_module.addImport("core", core_module);
test_network_module.addImport("sync", sync_module);
test_network_module.addImport("platform", platform_module);
test_network_module.addImport("noise", noise_module);
const test_network = b.addTest(.{
.root_module = test_network_module,
@@ -1768,6 +2027,8 @@ pub fn build(b: *std.Build) void {
.optimize = .Debug,
});
test_protocol_module.addImport("core", core_module);
test_protocol_module.addImport("sync", sync_module);
test_protocol_module.addImport("platform", platform_module);
test_protocol_module.addImport("network", network_module);
const test_protocol = b.addTest(.{
.root_module = test_protocol_module,
@@ -1783,6 +2044,8 @@ pub fn build(b: *std.Build) void {
.optimize = .Debug,
});
test_files_module.addImport("core", core_module);
test_files_module.addImport("sync", sync_module);
test_files_module.addImport("platform", platform_module);
test_files_module.addImport("protocol", protocol_module);
const test_files = b.addTest(.{
.root_module = test_files_module,
@@ -1797,6 +2060,7 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = .Debug,
});
test_noise_module.addImport("platform", platform_module);
const test_noise = b.addTest(.{
.root_module = test_noise_module,
});
@@ -1828,6 +2092,56 @@ pub fn build(b: *std.Build) void {
const test_security_fixes_step = b.step("test-security-fixes", "Run security fixes tests");
test_security_fixes_step.dependOn(&run_test_security_fixes.step);
// Test MWP Connection - MWP hole punch integration test with two P2P nodes
const test_mwp_connection_module = b.createModule(.{
.root_source_file = b.path("tests/integration/test_mwp_connection.zig"),
.target = target,
.optimize = .Debug,
});
test_mwp_connection_module.addImport("p2p", p2p_module);
test_mwp_connection_module.addImport("core", core_module);
test_mwp_connection_module.addImport("network", network_module);
test_mwp_connection_module.addImport("mwp", mwp_module);
test_mwp_connection_module.addImport("mwp_lib", mwp_lib_module);
test_mwp_connection_module.addImport("helpers", test_helpers_module);
const test_mwp_connection = b.addTest(.{
.root_module = test_mwp_connection_module,
});
const run_test_mwp_connection = b.addRunArtifact(test_mwp_connection);
const test_mwp_step = b.step("test-mwp", "Run MWP hole punch integration test");
test_mwp_step.dependOn(&run_test_mwp_connection.step);
// Test WebRTC Bridge — signaling message parsing, bridge lifecycle
const test_webrtc_bridge_module = b.createModule(.{
.root_source_file = b.path("tests/integration/test_webrtc_bridge.zig"),
.target = target,
.optimize = .Debug,
});
test_webrtc_bridge_module.addImport("platform", platform_module);
test_webrtc_bridge_module.addImport("webrtc_bridge", webrtc_bridge_module);
const test_webrtc_bridge = b.addTest(.{
.root_module = test_webrtc_bridge_module,
});
const run_test_webrtc_bridge = b.addRunArtifact(test_webrtc_bridge);
const test_webrtc_bridge_step = b.step("test-webrtc-bridge", "Run WebRTC bridge integration tests");
test_webrtc_bridge_step.dependOn(&run_test_webrtc_bridge.step);
// Test WebRTC Transfer Protocol — v1 wire format encoding/decoding
const test_webrtc_transfer_module = b.createModule(.{
.root_source_file = b.path("tests/integration/test_webrtc_transfer.zig"),
.target = target,
.optimize = .Debug,
});
const test_webrtc_transfer = b.addTest(.{
.root_module = test_webrtc_transfer_module,
});
const run_test_webrtc_transfer = b.addRunArtifact(test_webrtc_transfer);
const test_webrtc_transfer_step = b.step("test-webrtc-transfer", "Run WebRTC transfer protocol tests");
test_webrtc_transfer_step.dependOn(&run_test_webrtc_transfer.step);
// All integration tests step
const test_all_integration_step = b.step("test-integration", "Run all integration tests");
test_all_integration_step.dependOn(test_network_manager_step);
@@ -1848,6 +2162,7 @@ pub fn build(b: *std.Build) void {
test_all_integration_step.dependOn(test_secure_connection_step);
test_all_integration_step.dependOn(test_nat_step);
test_all_integration_step.dependOn(test_replay_protection_step);
test_all_integration_step.dependOn(test_replay_integration_step);
test_all_integration_step.dependOn(test_transfer_protocol_step);
test_all_integration_step.dependOn(test_upload_step);
test_all_integration_step.dependOn(test_manager_step);
@@ -1863,6 +2178,10 @@ pub fn build(b: *std.Build) void {
test_all_integration_step.dependOn(test_verification_pool_step);
test_all_integration_step.dependOn(test_piece_pipeline_step);
test_all_integration_step.dependOn(test_real_file_io_step);
test_all_integration_step.dependOn(test_mwp_step);
test_all_integration_step.dependOn(test_real_e2e_step);
test_all_integration_step.dependOn(test_webrtc_bridge_step);
test_all_integration_step.dependOn(test_webrtc_transfer_step);
// ============================================================
// Main Test Target
@@ -1883,6 +2202,10 @@ pub fn build(b: *std.Build) void {
check_module.addImport("network", network_module);
check_module.addImport("protocol", protocol_module);
check_module.addImport("files", files_module);
check_module.addImport("noise", noise_module);
check_module.addImport("p2p", p2p_module);
check_module.addImport("mwp", mwp_module);
check_module.addImport("mwp_lib", mwp_lib_module);
const check_exe = b.addExecutable(.{
.name = "p2p-check",
@@ -1892,9 +2215,168 @@ 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)
// ============================================================
const clean_step = b.step("clean", "Remove build artifacts (use: rm -rf zig-out .zig-cache)");
_ = clean_step;
// ============================================================
// WASM Build Target
// ============================================================
{
const wasm_target = b.resolveTargetQuery(.{
.cpu_arch = .wasm32,
.os_tag = .freestanding,
});
const wasm_optimize = .ReleaseSmall;
const wasm_sync = b.createModule(.{
.root_source_file = b.path("src/platform/sync.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
const wasm_time = b.createModule(.{
.root_source_file = b.path("src/platform/time.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
const wasm_core = b.createModule(.{
.root_source_file = b.path("src/core.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_core.addImport("sync", wasm_sync);
wasm_core.addImport("time", wasm_time);
// NOTE: wasm_core.addImport("platform", wasm_platform) is added below after wasm_platform creation
const wasm_platform = b.createModule(.{
.root_source_file = b.path("src/platform.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_platform.addImport("sync", wasm_sync);
wasm_platform.addImport("time", wasm_time);
wasm_platform.addImport("core", wasm_core);
wasm_core.addImport("platform", wasm_platform);
const wasm_noise = b.createModule(.{
.root_source_file = b.path("src/noise/noise.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_noise.addImport("platform", wasm_platform);
const wasm_network = b.createModule(.{
.root_source_file = b.path("src/network.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_network.addImport("core", wasm_core);
wasm_network.addImport("sync", wasm_sync);
wasm_network.addImport("platform", wasm_platform);
wasm_network.addImport("noise", wasm_noise);
const wasm_protocol = b.createModule(.{
.root_source_file = b.path("src/protocol.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_protocol.addImport("core", wasm_core);
wasm_protocol.addImport("sync", wasm_sync);
wasm_protocol.addImport("network", wasm_network);
wasm_protocol.addImport("platform", wasm_platform);
const wasm_files = b.createModule(.{
.root_source_file = b.path("src/files.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_files.addImport("core", wasm_core);
wasm_files.addImport("sync", wasm_sync);
wasm_files.addImport("protocol", wasm_protocol);
wasm_files.addImport("platform", wasm_platform);
const build_options = b.addOptions();
build_options.addOption(bool, "enable_webrtc", false);
const wasm_build_options = build_options.createModule();
const wasm_webrtc = b.createModule(.{
.root_source_file = b.path("src/platform/webrtc_wasm.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_webrtc.addImport("core", wasm_core);
wasm_webrtc.addImport("sync", wasm_sync);
const wasm_p2p = b.createModule(.{
.root_source_file = b.path("src/p2p.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_p2p.addImport("core", wasm_core);
wasm_p2p.addImport("sync", wasm_sync);
wasm_p2p.addImport("platform", wasm_platform);
wasm_p2p.addImport("network", wasm_network);
wasm_p2p.addImport("protocol", wasm_protocol);
wasm_p2p.addImport("files", wasm_files);
wasm_p2p.addImport("noise", wasm_noise);
wasm_p2p.addImport("build_options", wasm_build_options);
wasm_p2p.addImport("webrtc", wasm_webrtc);
const wasm_main = b.createModule(.{
.root_source_file = b.path("src/wasm/main.zig"),
.target = wasm_target,
.optimize = wasm_optimize,
});
wasm_main.addImport("p2p", wasm_p2p);
wasm_main.addImport("core", wasm_core);
wasm_main.addImport("sync", wasm_sync);
wasm_main.addImport("network", wasm_network);
wasm_main.addImport("platform", wasm_platform);
wasm_main.addImport("files", wasm_files);
wasm_main.addImport("noise", wasm_noise);
const wasm_lib = b.addExecutable(.{
.name = "zig-p2p",
.root_module = wasm_main,
});
wasm_lib.entry = .disabled;
wasm_lib.rdynamic = true;
const install_wasm = b.addInstallArtifact(wasm_lib, .{});
const wasm_step = b.step("wasm", "Build WASM library for browser");
wasm_step.dependOn(&install_wasm.step);
}
}

12
build.zig.zon Normal file
View File

@@ -0,0 +1,12 @@
.{
.name = .zig_p2p,
.version = "0.15.2",
.dependencies = .{
.vaxis = .{
.url = "git+https://github.com/rockorager/libvaxis.git#67bbc1ee072aa390838c66caf4ed47edee282dc4",
.hash = "vaxis-0.5.1-BWNV_IxJCQC5OGNaXQfNnqgn9_Vku0PMgey-dplubcQK",
},
},
.paths = .{""},
.fingerprint = 0xab77f73df570597f,
}

1381
convo.md

File diff suppressed because it is too large Load Diff

1766
deps/rustrtc-capi/Cargo.lock generated vendored Normal file

File diff suppressed because it is too large Load Diff

25
deps/rustrtc-capi/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,25 @@
[package]
name = "rustrtc-capi"
version = "0.1.0"
edition = "2021"
[lib]
name = "datachannel"
crate-type = ["cdylib", "rlib"]
[dependencies]
rustrtc = "0.3"
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros"] }
tokio-tungstenite = "0.24"
futures-util = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
parking_lot = "0.12"
log = "0.4"
env_logger = "0.11"
bytes = "1"
time = ">=0.3,<0.3.47"
[[test]]
name = "loopback"
path = "tests/loopback.rs"

753
deps/rustrtc-capi/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,753 @@
//! rustrtc C API wrapper — drop-in replacement for libdatachannel.
//!
//! Exports the same `rtc*` C symbols so that Zig's `webrtc_native.zig`
//! links against this library with zero code changes.
mod monitors;
mod state;
mod types;
pub mod ws_signaling;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use rustrtc::config::RtcConfiguration as RustRtcConfig;
use rustrtc::peer_connection::PeerConnection;
use rustrtc::transports::datachannel::DataChannelConfig;
use rustrtc::transports::ice::IceCandidate;
use crate::monitors::*;
use crate::state::*;
use crate::types::*;
// ===========================================================================
// Global
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcPreload() {
init_runtime();
}
#[no_mangle]
pub extern "C" fn rtcCleanup() {
cleanup();
}
#[no_mangle]
pub extern "C" fn rtcInitLogger(level: c_int, cb: Option<LogCallbackFn>) {
// Simple implementation: if callback provided, store it; otherwise use env_logger
let _ = level;
let _ = cb;
// For now, initialize env_logger for Rust-side logging (best effort)
let _ = env_logger::try_init();
}
// ===========================================================================
// User pointer
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetUserPointer(id: c_int, ptr: *mut c_void) {
set_user_ptr(id, ptr);
}
#[no_mangle]
pub extern "C" fn rtcGetUserPointer(id: c_int) -> *mut c_void {
get_user_ptr(id)
}
// ===========================================================================
// PeerConnection
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcCreatePeerConnection(config: *const RtcConfiguration) -> c_int {
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let cfg = &*config;
let mut rust_config = RustRtcConfig::default();
// Map ICE servers
if !cfg.ice_servers.is_null() && cfg.ice_servers_count > 0 {
let count = cfg.ice_servers_count as usize;
for i in 0..count {
let server_ptr = *cfg.ice_servers.add(i);
if !server_ptr.is_null() {
if let Ok(s) = CStr::from_ptr(server_ptr).to_str() {
let ice_server = rustrtc::config::IceServer::new(vec![s.to_string()]);
rust_config.ice_servers.push(ice_server);
}
}
}
}
// Map port range
if cfg.port_range_begin > 0 && cfg.port_range_end > 0 {
rust_config.rtp_start_port = Some(cfg.port_range_begin);
rust_config.rtp_end_port = Some(cfg.port_range_end);
}
// Enter runtime context — PeerConnection::new() needs a tokio reactor
let _guard = rt.enter();
let pc = Arc::new(PeerConnection::new(rust_config));
let pc_id = alloc_id();
let disable_auto = cfg.disable_auto_negotiation;
// Spawn PC monitoring tasks
let tasks = spawn_pc_monitors(rt, pc_id, &pc);
let pc_state = PcState::new(pc, disable_auto);
*pc_state.tasks.lock() = tasks;
entries().write().insert(pc_id, Entry::Pc(pc_state));
pc_id
}
#[no_mangle]
pub extern "C" fn rtcClosePeerConnection(pc: c_int) -> c_int {
match with_pc(pc, |pc_state| {
pc_state.pc.close();
}) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcDeletePeerConnection(pc: c_int) -> c_int {
let entry = entries().write().remove(&pc);
match entry {
Some(Entry::Pc(pc_state)) => {
// Abort all monitor tasks
for t in pc_state.tasks.lock().drain(..) {
t.abort();
}
pc_state.pc.close();
RTC_ERR_SUCCESS
}
Some(other) => {
// Put it back — wrong type
entries().write().insert(pc, other);
RTC_ERR_INVALID
}
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// Callback setters (PeerConnection)
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetLocalDescriptionCallback(
pc: c_int,
cb: Option<DescriptionCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_local_description.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetLocalCandidateCallback(
pc: c_int,
cb: Option<CandidateCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_local_candidate.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetStateChangeCallback(
pc: c_int,
cb: Option<StateChangeCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_state_change.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetGatheringStateChangeCallback(
pc: c_int,
cb: Option<GatheringStateCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_gathering_state.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetDataChannelCallback(
pc: c_int,
cb: Option<DataChannelCallbackFn>,
) -> c_int {
match with_pc(pc, |s| *s.on_data_channel.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// SDP
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSetLocalDescription(
pc: c_int,
sdp_type: *const c_char,
) -> c_int {
let (pc_arc, _disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation))
{
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let is_answer = if sdp_type.is_null() {
false
} else {
let type_str = CStr::from_ptr(sdp_type).to_str().unwrap_or("");
type_str == "answer"
};
if is_answer {
// Generate answer (assumes remote offer already set)
let pc_clone = pc_arc.clone();
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let handle = rt.spawn(async move {
match pc_clone.create_answer().await {
Ok(answer) => {
let sdp_string = crate::monitors::inject_max_message_size(&answer.to_sdp_string());
if let Err(e) = pc_clone.set_local_description(answer) {
log::error!("set_local_description (answer) failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("answer").unwrap();
with_pc(pc, |s| {
*s.local_sdp.lock() = Some(sdp_c.clone());
*s.local_sdp_type.lock() = Some(type_c.clone());
});
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc) {
cb(pc, sdp_c.as_ptr(), type_c.as_ptr(), ptr);
}
}
Err(e) => log::error!("create_answer failed: {e}"),
}
});
with_pc(pc, |s| s.tasks.lock().push(handle));
} else {
// Generate offer
trigger_offer(pc, pc_arc);
}
RTC_ERR_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn rtcSetRemoteDescription(
pc: c_int,
sdp: *const c_char,
sdp_type: *const c_char,
) -> c_int {
if sdp.is_null() {
return RTC_ERR_INVALID;
}
let sdp_str = match CStr::from_ptr(sdp).to_str() {
Ok(s) => s.to_string(),
Err(_) => return RTC_ERR_INVALID,
};
let type_str = if sdp_type.is_null() {
"offer".to_string()
} else {
CStr::from_ptr(sdp_type)
.to_str()
.unwrap_or("offer")
.to_string()
};
let pc_arc = match with_pc(pc, |s| s.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let is_offer = type_str == "offer";
if is_offer {
// Trigger auto-answer: parse remote offer → set remote desc → create answer → fire callback
trigger_answer(pc, pc_arc, sdp_str);
} else {
// It's an answer — just set the remote description
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let handle = rt.spawn(async move {
let desc = match rustrtc::sdp::SessionDescription::parse(
rustrtc::sdp::SdpType::Answer,
&sdp_str,
) {
Ok(d) => d,
Err(e) => {
log::error!("parse answer SDP failed: {e}");
return;
}
};
if let Err(e) = pc_arc.set_remote_description(desc).await {
log::error!("set_remote_description (answer) failed: {e}");
}
// Cache remote SDP
if let Ok(remote_c) = CString::new(sdp_str) {
with_pc(pc, |s| {
*s.remote_sdp.lock() = Some(remote_c);
});
}
});
with_pc(pc, |s| s.tasks.lock().push(handle));
}
RTC_ERR_SUCCESS
}
#[no_mangle]
pub unsafe extern "C" fn rtcAddRemoteCandidate(
pc: c_int,
cand: *const c_char,
mid: *const c_char,
) -> c_int {
let _ = mid; // mid is typically ignored for data-channel-only connections
if cand.is_null() {
return RTC_ERR_INVALID;
}
let cand_str = match CStr::from_ptr(cand).to_str() {
Ok(s) => s,
Err(_) => return RTC_ERR_INVALID,
};
let pc_arc = match with_pc(pc, |s| s.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
match IceCandidate::from_sdp(cand_str) {
Ok(candidate) => match pc_arc.add_ice_candidate(candidate) {
Ok(_) => RTC_ERR_SUCCESS,
Err(e) => {
log::error!("add_ice_candidate failed: {e}");
RTC_ERR_FAILURE
}
},
Err(e) => {
log::error!("parse ICE candidate failed: {e}");
RTC_ERR_FAILURE
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcGetLocalDescription(
pc: c_int,
buffer: *mut u8,
size: c_int,
) -> c_int {
if buffer.is_null() || size <= 0 {
return RTC_ERR_INVALID;
}
match with_pc(pc, |s| s.local_sdp.lock().clone()) {
Some(Some(sdp)) => {
let bytes = sdp.as_bytes_with_nul();
let len = bytes.len();
if (size as usize) < len {
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
len as c_int
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcGetRemoteDescription(
pc: c_int,
buffer: *mut u8,
size: c_int,
) -> c_int {
if buffer.is_null() || size <= 0 {
return RTC_ERR_INVALID;
}
match with_pc(pc, |s| s.remote_sdp.lock().clone()) {
Some(Some(sdp)) => {
let bytes = sdp.as_bytes_with_nul();
let len = bytes.len();
if (size as usize) < len {
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len);
len as c_int
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// DataChannel
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcCreateDataChannel(
pc: c_int,
label: *const c_char,
) -> c_int {
// Create with default DataChannelInit
let default_init = RtcDataChannelInit {
reliability: RtcReliability {
unordered: false,
unreliable: false,
max_packet_life_time: 0,
max_retransmits: 0,
},
protocol: std::ptr::null(),
negotiated: false,
manual_stream: false,
stream: 0,
};
rtcCreateDataChannelEx(pc, label, &default_init)
}
#[no_mangle]
pub unsafe extern "C" fn rtcCreateDataChannelEx(
pc: c_int,
label: *const c_char,
init: *const RtcDataChannelInit,
) -> c_int {
if label.is_null() || init.is_null() {
return RTC_ERR_INVALID;
}
let label_str = match CStr::from_ptr(label).to_str() {
Ok(s) => s.to_string(),
Err(_) => return RTC_ERR_INVALID,
};
let init_ref = &*init;
let protocol = if init_ref.protocol.is_null() {
String::new()
} else {
CStr::from_ptr(init_ref.protocol)
.to_str()
.unwrap_or("")
.to_string()
};
let (pc_arc, disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation))
{
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let dc_config = DataChannelConfig {
label: label_str,
protocol,
ordered: !init_ref.reliability.unordered,
max_retransmits: if init_ref.reliability.unreliable && init_ref.reliability.max_retransmits > 0
{
Some(init_ref.reliability.max_retransmits as u16)
} else {
None
},
max_packet_life_time: if init_ref.reliability.unreliable
&& init_ref.reliability.max_packet_life_time > 0
{
Some(init_ref.reliability.max_packet_life_time as u16)
} else {
None
},
max_payload_size: None,
negotiated: if init_ref.negotiated {
Some(init_ref.stream)
} else {
None
},
};
// Enter runtime context for create_data_channel
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
let _guard = rt.enter();
let label_for_create = dc_config.label.clone();
let dc = match pc_arc.create_data_channel(&label_for_create, Some(dc_config)) {
Ok(dc) => dc,
Err(e) => {
log::error!("create_data_channel failed: {e}");
return RTC_ERR_FAILURE;
}
};
let dc_id = alloc_id();
let channel_id = dc.id;
// Spawn DC event monitor
let handle = spawn_dc_monitor(dc_id, dc);
let dc_state = DcState::new(pc, pc_arc.clone(), channel_id);
*dc_state.task.lock() = Some(handle);
entries().write().insert(dc_id, Entry::Dc(dc_state));
// Trigger auto-negotiation (offer generation) if enabled
if !disable_auto {
trigger_offer(pc, pc_arc);
}
dc_id
}
#[no_mangle]
pub extern "C" fn rtcDeleteDataChannel(dc: c_int) -> c_int {
let entry = entries().write().remove(&dc);
match entry {
Some(Entry::Dc(dc_state)) => {
if let Some(t) = dc_state.task.lock().take() {
t.abort();
}
RTC_ERR_SUCCESS
}
Some(other) => {
entries().write().insert(dc, other);
RTC_ERR_INVALID
}
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// Callback setters (DataChannel / common)
// ===========================================================================
#[no_mangle]
pub extern "C" fn rtcSetOpenCallback(id: c_int, cb: Option<OpenCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_open.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetClosedCallback(id: c_int, cb: Option<ClosedCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_closed.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetErrorCallback(id: c_int, cb: Option<ErrorCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_error.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcSetMessageCallback(id: c_int, cb: Option<MessageCallbackFn>) -> c_int {
match with_dc(id, |s| *s.on_message.lock() = cb) {
Some(_) => RTC_ERR_SUCCESS,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// I/O
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSendMessage(
id: c_int,
data: *const u8,
size: c_int,
) -> c_int {
let bytes = if size < 0 {
// Treat as null-terminated string
let cstr = CStr::from_ptr(data as *const c_char);
cstr.to_bytes().to_vec()
} else {
std::slice::from_raw_parts(data, size as usize).to_vec()
};
let (pc_arc, channel_id) = match with_dc(id, |dc| (dc.pc.clone(), dc.channel_id)) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
// Blocking send — preserves message ordering (caller is always on a non-tokio thread)
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
match rt.block_on(pc_arc.send_data(channel_id, &bytes)) {
Ok(_) => RTC_ERR_SUCCESS,
Err(e) => {
log::error!("send_data failed: {e}");
RTC_ERR_FAILURE
}
}
}
#[no_mangle]
pub extern "C" fn rtcClose(id: c_int) -> c_int {
// Try as DC first
if let Some(_) = with_dc(id, |dc| {
dc.is_open.store(false, Ordering::Release);
// Close the underlying PC data channel
let pc = dc.pc.clone();
let channel_id = dc.channel_id;
if let Some(rt) = get_runtime() {
rt.spawn(async move {
// There's no explicit DC close in rustrtc; closing is done at PC level
let _ = (pc, channel_id);
});
}
}) {
return RTC_ERR_SUCCESS;
}
// Try as PC
if let Some(_) = with_pc(id, |pc| {
pc.pc.close();
}) {
return RTC_ERR_SUCCESS;
}
RTC_ERR_INVALID
}
#[no_mangle]
pub extern "C" fn rtcDelete(id: c_int) -> c_int {
let entry = entries().write().remove(&id);
match entry {
Some(Entry::Dc(dc_state)) => {
if let Some(t) = dc_state.task.lock().take() {
t.abort();
}
RTC_ERR_SUCCESS
}
Some(Entry::Pc(pc_state)) => {
for t in pc_state.tasks.lock().drain(..) {
t.abort();
}
pc_state.pc.close();
RTC_ERR_SUCCESS
}
None => RTC_ERR_INVALID,
}
}
#[no_mangle]
pub extern "C" fn rtcIsOpen(id: c_int) -> bool {
with_dc(id, |dc| dc.is_open.load(Ordering::Acquire)).unwrap_or(false)
}
#[no_mangle]
pub extern "C" fn rtcIsClosed(id: c_int) -> bool {
with_dc(id, |dc| dc.is_closed.load(Ordering::Acquire)).unwrap_or(true)
}
#[no_mangle]
pub extern "C" fn rtcGetBufferedAmount(id: c_int) -> c_int {
let pc_arc = match with_dc(id, |dc| dc.pc.clone()) {
Some(v) => v,
None => return RTC_ERR_INVALID,
};
let rt = match get_runtime() {
Some(rt) => rt,
None => return RTC_ERR_FAILURE,
};
// block_on is safe here because we're called from non-tokio threads
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
rt.block_on(pc_arc.sctp_buffered_amount()) as c_int
})) {
Ok(amount) => amount,
Err(_) => {
// If block_on panics (called from tokio context), try spawn + channel
let pc_clone = pc_arc.clone();
let (tx, rx) = std::sync::mpsc::channel();
rt.spawn(async move {
let amount = pc_clone.sctp_buffered_amount().await;
let _ = tx.send(amount as c_int);
});
rx.recv().unwrap_or(0)
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rtcReceiveMessage(
id: c_int,
buffer: *mut u8,
size: *mut c_int,
) -> c_int {
if buffer.is_null() || size.is_null() {
return RTC_ERR_INVALID;
}
match with_dc(id, |dc| {
let mut buf = dc.recv_buffer.lock();
buf.pop_front()
}) {
Some(Some(data)) => {
let available = *size as usize;
if data.len() > available {
*size = data.len() as c_int;
return RTC_ERR_TOO_SMALL;
}
std::ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len());
*size = data.len() as c_int;
RTC_ERR_SUCCESS
}
Some(None) => RTC_ERR_NOT_AVAIL,
None => RTC_ERR_INVALID,
}
}
// ===========================================================================
// SCTP settings (no-op — rustrtc has its own SCTP stack)
// ===========================================================================
#[no_mangle]
pub unsafe extern "C" fn rtcSetSctpSettings(_settings: *const RtcSctpSettings) -> c_int {
RTC_ERR_SUCCESS
}

338
deps/rustrtc-capi/src/monitors.rs vendored Normal file
View File

@@ -0,0 +1,338 @@
//! Async tasks that bridge rustrtc events → C callbacks.
//!
//! For each PeerConnection, we spawn monitor tasks for:
//! - ICE candidates (broadcast receiver)
//! - Peer connection state (watch receiver)
//! - ICE gathering state (watch receiver)
//! - Incoming DataChannels (pc.recv())
//!
//! For each DataChannel, we spawn one monitor task that handles
//! Open / Message / Close events.
use std::ffi::CString;
use std::sync::Arc;
use rustrtc::peer_connection::{
IceGatheringState, PeerConnection, PeerConnectionEvent, PeerConnectionState,
};
use rustrtc::transports::datachannel::{DataChannel, DataChannelEvent};
use tokio::task::JoinHandle;
use crate::state::*;
use crate::types::*;
// ---------------------------------------------------------------------------
// PeerConnection monitors
// ---------------------------------------------------------------------------
/// Spawn all monitoring tasks for a PeerConnection. Returns task handles.
pub fn spawn_pc_monitors(
rt: &tokio::runtime::Runtime,
pc_id: i32,
pc: &Arc<PeerConnection>,
) -> Vec<JoinHandle<()>> {
let mut tasks = Vec::with_capacity(4);
// 1. ICE candidate monitor (broadcast::Receiver)
let mut cand_rx = pc.subscribe_ice_candidates();
let pc_id1 = pc_id;
tasks.push(rt.spawn(async move {
loop {
match cand_rx.recv().await {
Ok(candidate) => {
let cand_str = candidate.to_sdp();
let cand_c = match CString::new(cand_str) {
Ok(c) => c,
Err(_) => continue,
};
let mid_c = CString::new("0").unwrap();
if let Some((Some(cb), ptr)) = get_pc_candidate_cb(pc_id1) {
unsafe { cb(pc_id1, cand_c.as_ptr(), mid_c.as_ptr(), ptr) };
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
}
}
}));
// 2. Peer connection state monitor (watch::Receiver)
let mut state_rx = pc.subscribe_peer_state();
let pc_id2 = pc_id;
tasks.push(rt.spawn(async move {
while state_rx.changed().await.is_ok() {
let state = *state_rx.borrow_and_update();
let c_state = map_peer_state(state);
if let Some((Some(cb), ptr)) = get_pc_state_change_cb(pc_id2) {
unsafe { cb(pc_id2, c_state, ptr) };
}
}
}));
// 3. ICE gathering state monitor (watch::Receiver)
let mut gather_rx = pc.subscribe_ice_gathering_state();
let pc_id3 = pc_id;
tasks.push(rt.spawn(async move {
while gather_rx.changed().await.is_ok() {
let state = *gather_rx.borrow_and_update();
let c_state = map_gathering_state(state);
if let Some((Some(cb), ptr)) = get_pc_gathering_state_cb(pc_id3) {
unsafe { cb(pc_id3, c_state, ptr) };
}
}
}));
// 4. Incoming DataChannel monitor (pc.recv())
let pc_clone = pc.clone();
let pc_id4 = pc_id;
tasks.push(rt.spawn(async move {
while let Some(event) = pc_clone.recv().await {
match event {
PeerConnectionEvent::DataChannel(dc) => {
handle_incoming_data_channel(pc_id4, &pc_clone, dc).await;
}
_ => {} // Ignore Track events for data-channel-only usage
}
}
}));
tasks
}
/// Handle an incoming DataChannel: register it, fire callback, then spawn monitor.
async fn handle_incoming_data_channel(
pc_id: i32,
pc: &Arc<PeerConnection>,
dc: Arc<DataChannel>,
) {
let dc_id = alloc_id();
let channel_id = dc.id;
let dc_state = DcState::new(pc_id, pc.clone(), channel_id);
// Insert into global registry
{
let mut map = entries().write();
map.insert(dc_id, Entry::Dc(dc_state));
}
// Fire DataChannel callback (synchronously — user sets DC callbacks inside)
if let Some((Some(cb), ptr)) = get_pc_data_channel_cb(pc_id) {
// Copy the PC's user pointer to the DC entry
let pc_ptr = get_user_ptr(pc_id);
set_user_ptr(dc_id, pc_ptr);
unsafe { cb(pc_id, dc_id, ptr) };
}
// Now spawn DC monitor (callbacks are set by this point)
let handle = spawn_dc_monitor(dc_id, dc);
with_dc(dc_id, |dc_state| {
*dc_state.task.lock() = Some(handle);
});
}
// ---------------------------------------------------------------------------
// DataChannel monitor
// ---------------------------------------------------------------------------
/// Spawn a monitor task for a DataChannel. Fires open/message/close callbacks.
pub fn spawn_dc_monitor(dc_id: i32, dc: Arc<DataChannel>) -> JoinHandle<()> {
let rt = get_runtime().expect("runtime not initialized");
rt.spawn(async move {
while let Some(event) = dc.recv().await {
match event {
DataChannelEvent::Open => {
// Mark as open
with_dc(dc_id, |dc_state| {
dc_state.is_open.store(true, std::sync::atomic::Ordering::Release);
dc_state.is_closed.store(false, std::sync::atomic::Ordering::Release);
});
if let Some((Some(cb), ptr)) = get_dc_open_cb(dc_id) {
unsafe { cb(dc_id, ptr) };
}
}
DataChannelEvent::Message(data) => {
let bytes = data.to_vec();
let len = bytes.len();
// Push to recv_buffer (for rtcReceiveMessage)
with_dc(dc_id, |dc_state| {
let mut buf = dc_state.recv_buffer.lock();
if buf.len() < 65536 {
buf.push_back(bytes.clone());
}
});
// Fire message callback
if let Some((Some(cb), ptr)) = get_dc_message_cb(dc_id) {
unsafe { cb(dc_id, bytes.as_ptr(), len as i32, ptr) };
}
}
DataChannelEvent::Close => {
with_dc(dc_id, |dc_state| {
dc_state.is_open.store(false, std::sync::atomic::Ordering::Release);
dc_state.is_closed.store(true, std::sync::atomic::Ordering::Release);
});
if let Some((Some(cb), ptr)) = get_dc_closed_cb(dc_id) {
unsafe { cb(dc_id, ptr) };
}
break;
}
}
}
})
}
// ---------------------------------------------------------------------------
// SDP generation helpers (spawned as async tasks)
// ---------------------------------------------------------------------------
/// Inject `a=max-message-size:1048576` into an SDP string if not already present.
/// Per RFC 8841 §4.3, absence of this attribute makes the remote peer assume a
/// default of 65536 bytes, which is too small for efficient file transfers.
pub fn inject_max_message_size(sdp: &str) -> String {
if sdp.contains("a=max-message-size") {
return sdp.to_string();
}
// Insert after `a=sctp-port` line (within the m= section)
if let Some(pos) = sdp.find("a=sctp-port") {
if let Some(eol) = sdp[pos..].find("\r\n") {
let insert_at = pos + eol + 2;
let mut result = String::with_capacity(sdp.len() + 30);
result.push_str(&sdp[..insert_at]);
result.push_str("a=max-message-size:1048576\r\n");
result.push_str(&sdp[insert_at..]);
return result;
}
}
sdp.to_string()
}
/// Trigger offer generation: create offer → set local description → fire callback.
/// Called after rtcCreateDataChannelEx when auto-negotiation is enabled.
pub fn trigger_offer(pc_id: i32, pc: Arc<PeerConnection>) {
let rt = get_runtime().expect("runtime not initialized");
let handle = rt.spawn(async move {
match pc.create_offer().await {
Ok(offer) => {
let sdp_string = inject_max_message_size(&offer.to_sdp_string());
if let Err(e) = pc.set_local_description(offer) {
log::error!("set_local_description failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string.clone()) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("offer").unwrap();
// Cache SDP
with_pc(pc_id, |pc_state| {
*pc_state.local_sdp.lock() = Some(sdp_c.clone());
*pc_state.local_sdp_type.lock() = Some(type_c.clone());
});
// Fire description callback
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) {
unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) };
}
}
Err(e) => {
log::error!("create_offer failed: {e}");
}
}
});
// Store task handle
with_pc(pc_id, |pc_state| {
pc_state.tasks.lock().push(handle);
});
}
/// Trigger answer generation after receiving a remote offer.
pub fn trigger_answer(pc_id: i32, pc: Arc<PeerConnection>, remote_sdp: String) {
let rt = get_runtime().expect("runtime not initialized");
let handle = rt.spawn(async move {
// Parse and set remote description
let desc = match rustrtc::sdp::SessionDescription::parse(
rustrtc::sdp::SdpType::Offer,
&remote_sdp,
) {
Ok(d) => d,
Err(e) => {
log::error!("parse remote SDP failed: {e}");
return;
}
};
if let Err(e) = pc.set_remote_description(desc).await {
log::error!("set_remote_description failed: {e}");
return;
}
// Cache remote SDP
if let Ok(remote_c) = CString::new(remote_sdp) {
with_pc(pc_id, |pc_state| {
*pc_state.remote_sdp.lock() = Some(remote_c);
});
}
// Create answer
match pc.create_answer().await {
Ok(answer) => {
let sdp_string = inject_max_message_size(&answer.to_sdp_string());
if let Err(e) = pc.set_local_description(answer) {
log::error!("set_local_description (answer) failed: {e}");
return;
}
let sdp_c = match CString::new(sdp_string) {
Ok(c) => c,
Err(_) => return,
};
let type_c = CString::new("answer").unwrap();
// Cache answer SDP
with_pc(pc_id, |pc_state| {
*pc_state.local_sdp.lock() = Some(sdp_c.clone());
*pc_state.local_sdp_type.lock() = Some(type_c.clone());
});
// Fire description callback
if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) {
unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) };
}
}
Err(e) => {
log::error!("create_answer failed: {e}");
}
}
});
with_pc(pc_id, |pc_state| {
pc_state.tasks.lock().push(handle);
});
}
// ---------------------------------------------------------------------------
// State mapping helpers
// ---------------------------------------------------------------------------
fn map_peer_state(state: PeerConnectionState) -> i32 {
match state {
PeerConnectionState::New => RTC_STATE_NEW,
PeerConnectionState::Connecting => RTC_STATE_CONNECTING,
PeerConnectionState::Connected => RTC_STATE_CONNECTED,
PeerConnectionState::Disconnected => RTC_STATE_DISCONNECTED,
PeerConnectionState::Failed => RTC_STATE_FAILED,
PeerConnectionState::Closed => RTC_STATE_CLOSED,
}
}
fn map_gathering_state(state: IceGatheringState) -> i32 {
match state {
IceGatheringState::New => RTC_GATHERING_NEW,
IceGatheringState::Gathering => RTC_GATHERING_IN_PROGRESS,
IceGatheringState::Complete => RTC_GATHERING_COMPLETE,
}
}

254
deps/rustrtc-capi/src/state.rs vendored Normal file
View File

@@ -0,0 +1,254 @@
//! Global ID registry, PcState, DcState.
use std::collections::{HashMap, VecDeque};
use std::ffi::CString;
use std::os::raw::c_void;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, Ordering};
use std::sync::{Arc, OnceLock};
use parking_lot::{Mutex, RwLock};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use rustrtc::peer_connection::PeerConnection;
use crate::types::*;
// ---------------------------------------------------------------------------
// Global statics
// ---------------------------------------------------------------------------
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
static ENTRIES: OnceLock<RwLock<HashMap<i32, Entry>>> = OnceLock::new();
static NEXT_ID: AtomicI32 = AtomicI32::new(1);
pub fn init_runtime() {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to create tokio runtime")
});
ENTRIES.get_or_init(|| RwLock::new(HashMap::new()));
}
pub fn get_runtime() -> Option<&'static Runtime> {
RUNTIME.get()
}
pub fn cleanup() {
if let Some(entries) = ENTRIES.get() {
let mut map = entries.write();
// Abort all tasks
for (_, entry) in map.drain() {
match entry {
Entry::Pc(pc) => {
let tasks = pc.tasks.lock();
for t in tasks.iter() {
t.abort();
}
}
Entry::Dc(dc) => {
if let Some(t) = dc.task.lock().take() {
t.abort();
}
}
}
}
}
// Note: We don't drop the runtime here because OnceLock doesn't support reset.
// The runtime will be cleaned up on process exit.
}
pub fn alloc_id() -> i32 {
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}
pub fn entries() -> &'static RwLock<HashMap<i32, Entry>> {
ENTRIES.get().expect("runtime not initialized")
}
// ---------------------------------------------------------------------------
// Entry types
// ---------------------------------------------------------------------------
pub enum Entry {
Pc(PcState),
Dc(DcState),
}
pub struct PcState {
pub pc: Arc<PeerConnection>,
pub user_ptr: AtomicPtr<c_void>,
pub disable_auto_negotiation: bool,
// Callback slots
pub on_local_description: Mutex<Option<DescriptionCallbackFn>>,
pub on_local_candidate: Mutex<Option<CandidateCallbackFn>>,
pub on_state_change: Mutex<Option<StateChangeCallbackFn>>,
pub on_gathering_state: Mutex<Option<GatheringStateCallbackFn>>,
pub on_data_channel: Mutex<Option<DataChannelCallbackFn>>,
// Cached SDP
pub local_sdp: Mutex<Option<CString>>,
pub local_sdp_type: Mutex<Option<CString>>,
pub remote_sdp: Mutex<Option<CString>>,
// Monitor task handles
pub tasks: Mutex<Vec<JoinHandle<()>>>,
}
pub struct DcState {
#[allow(dead_code)]
pub pc_id: i32,
pub pc: Arc<PeerConnection>,
pub channel_id: u16,
pub user_ptr: AtomicPtr<c_void>,
// Callback slots
pub on_open: Mutex<Option<OpenCallbackFn>>,
pub on_closed: Mutex<Option<ClosedCallbackFn>>,
pub on_error: Mutex<Option<ErrorCallbackFn>>,
pub on_message: Mutex<Option<MessageCallbackFn>>,
// State flags
pub is_open: AtomicBool,
pub is_closed: AtomicBool,
// Receive buffer (for rtcReceiveMessage polling)
pub recv_buffer: Mutex<VecDeque<Vec<u8>>>,
// Monitor task handle
pub task: Mutex<Option<JoinHandle<()>>>,
}
impl PcState {
pub fn new(pc: Arc<PeerConnection>, disable_auto_negotiation: bool) -> Self {
Self {
pc,
user_ptr: AtomicPtr::new(std::ptr::null_mut()),
disable_auto_negotiation,
on_local_description: Mutex::new(None),
on_local_candidate: Mutex::new(None),
on_state_change: Mutex::new(None),
on_gathering_state: Mutex::new(None),
on_data_channel: Mutex::new(None),
local_sdp: Mutex::new(None),
local_sdp_type: Mutex::new(None),
remote_sdp: Mutex::new(None),
tasks: Mutex::new(Vec::new()),
}
}
}
impl DcState {
pub fn new(pc_id: i32, pc: Arc<PeerConnection>, channel_id: u16) -> Self {
Self {
pc_id,
pc,
channel_id,
user_ptr: AtomicPtr::new(std::ptr::null_mut()),
on_open: Mutex::new(None),
on_closed: Mutex::new(None),
on_error: Mutex::new(None),
on_message: Mutex::new(None),
is_open: AtomicBool::new(false),
is_closed: AtomicBool::new(false),
recv_buffer: Mutex::new(VecDeque::new()),
task: Mutex::new(None),
}
}
}
// ---------------------------------------------------------------------------
// Helper accessors
// ---------------------------------------------------------------------------
/// Get user pointer for any entry (PC or DC).
pub fn get_user_ptr(id: i32) -> *mut c_void {
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => pc.user_ptr.load(Ordering::Acquire),
Some(Entry::Dc(dc)) => dc.user_ptr.load(Ordering::Acquire),
None => std::ptr::null_mut(),
}
}
/// Set user pointer for any entry.
pub fn set_user_ptr(id: i32, ptr: *mut c_void) {
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => pc.user_ptr.store(ptr, Ordering::Release),
Some(Entry::Dc(dc)) => dc.user_ptr.store(ptr, Ordering::Release),
None => {}
}
}
/// Execute a closure with read access to a PcState.
pub fn with_pc<F, R>(id: i32, f: F) -> Option<R>
where
F: FnOnce(&PcState) -> R,
{
let map = entries().read();
match map.get(&id) {
Some(Entry::Pc(pc)) => Some(f(pc)),
_ => None,
}
}
/// Execute a closure with read access to a DcState.
pub fn with_dc<F, R>(id: i32, f: F) -> Option<R>
where
F: FnOnce(&DcState) -> R,
{
let map = entries().read();
match map.get(&id) {
Some(Entry::Dc(dc)) => Some(f(dc)),
_ => None,
}
}
/// Get the PC Arc and user_ptr for a given PC id.
#[allow(dead_code)]
pub fn get_pc_arc(id: i32) -> Option<(Arc<PeerConnection>, *mut c_void)> {
with_pc(id, |pc| (pc.pc.clone(), pc.user_ptr.load(Ordering::Acquire)))
}
/// Get callback + user_ptr from a PC entry.
pub fn get_pc_description_cb(id: i32) -> Option<(Option<DescriptionCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_local_description.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_candidate_cb(id: i32) -> Option<(Option<CandidateCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_local_candidate.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_state_change_cb(id: i32) -> Option<(Option<StateChangeCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_state_change.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_gathering_state_cb(id: i32) -> Option<(Option<GatheringStateCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_gathering_state.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_pc_data_channel_cb(id: i32) -> Option<(Option<DataChannelCallbackFn>, *mut c_void)> {
with_pc(id, |pc| (*pc.on_data_channel.lock(), pc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_open_cb(id: i32) -> Option<(Option<OpenCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_open.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_closed_cb(id: i32) -> Option<(Option<ClosedCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_closed.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
#[allow(dead_code)]
pub fn get_dc_error_cb(id: i32) -> Option<(Option<ErrorCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_error.lock(), dc.user_ptr.load(Ordering::Acquire)))
}
pub fn get_dc_message_cb(id: i32) -> Option<(Option<MessageCallbackFn>, *mut c_void)> {
with_dc(id, |dc| (*dc.on_message.lock(), dc.user_ptr.load(Ordering::Acquire)))
}

107
deps/rustrtc-capi/src/types.rs vendored Normal file
View File

@@ -0,0 +1,107 @@
//! C ABI type definitions matching libdatachannel's rtc.h
use std::os::raw::{c_char, c_int, c_uint, c_void};
// ---------------------------------------------------------------------------
// Error codes
// ---------------------------------------------------------------------------
pub const RTC_ERR_SUCCESS: c_int = 0;
pub const RTC_ERR_INVALID: c_int = -1;
pub const RTC_ERR_FAILURE: c_int = -2;
pub const RTC_ERR_NOT_AVAIL: c_int = -3;
pub const RTC_ERR_TOO_SMALL: c_int = -4;
// ---------------------------------------------------------------------------
// State enum values (as c_int, matching Zig's enum(c_int))
// ---------------------------------------------------------------------------
// PeerConnection / ICE state
pub const RTC_STATE_NEW: c_int = 0;
pub const RTC_STATE_CONNECTING: c_int = 1;
pub const RTC_STATE_CONNECTED: c_int = 2;
pub const RTC_STATE_DISCONNECTED: c_int = 3;
pub const RTC_STATE_FAILED: c_int = 4;
pub const RTC_STATE_CLOSED: c_int = 5;
// ICE gathering state
pub const RTC_GATHERING_NEW: c_int = 0;
pub const RTC_GATHERING_IN_PROGRESS: c_int = 1;
pub const RTC_GATHERING_COMPLETE: c_int = 2;
// ---------------------------------------------------------------------------
// Callback function types
// ---------------------------------------------------------------------------
pub type DescriptionCallbackFn =
unsafe extern "C" fn(pc: c_int, sdp: *const c_char, sdp_type: *const c_char, ptr: *mut c_void);
pub type CandidateCallbackFn =
unsafe extern "C" fn(pc: c_int, cand: *const c_char, mid: *const c_char, ptr: *mut c_void);
pub type StateChangeCallbackFn =
unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void);
pub type GatheringStateCallbackFn =
unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void);
pub type DataChannelCallbackFn =
unsafe extern "C" fn(pc: c_int, dc: c_int, ptr: *mut c_void);
pub type OpenCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void);
pub type ClosedCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void);
pub type ErrorCallbackFn =
unsafe extern "C" fn(id: c_int, err_msg: *const c_char, ptr: *mut c_void);
pub type MessageCallbackFn =
unsafe extern "C" fn(id: c_int, message: *const u8, size: c_int, ptr: *mut c_void);
pub type LogCallbackFn = unsafe extern "C" fn(level: c_int, message: *const c_char);
// ---------------------------------------------------------------------------
// #[repr(C)] structs matching Zig extern structs
// ---------------------------------------------------------------------------
#[repr(C)]
pub struct RtcConfiguration {
pub ice_servers: *const *const c_char,
pub ice_servers_count: c_int,
pub proxy_server: *const c_char,
pub bind_address: *const c_char,
pub certificate_type: c_int,
pub ice_transport_policy: c_int,
pub enable_ice_tcp: bool,
pub enable_ice_udp_mux: bool,
pub disable_auto_negotiation: bool,
pub force_media_transport: bool,
pub port_range_begin: u16,
pub port_range_end: u16,
pub mtu: c_int,
pub max_message_size: c_int,
}
#[repr(C)]
pub struct RtcReliability {
pub unordered: bool,
pub unreliable: bool,
pub max_packet_life_time: c_uint,
pub max_retransmits: c_uint,
}
#[repr(C)]
pub struct RtcDataChannelInit {
pub reliability: RtcReliability,
pub protocol: *const c_char,
pub negotiated: bool,
pub manual_stream: bool,
pub stream: u16,
}
#[repr(C)]
pub struct RtcSctpSettings {
pub recv_buffer_size: c_int,
pub send_buffer_size: c_int,
pub max_chunks_on_queue: c_int,
pub initial_congestion_window: c_int,
pub max_burst: c_int,
pub congestion_control_module: c_int,
pub delayed_sack_time_ms: c_int,
pub min_retransmit_timeout_ms: c_int,
pub max_retransmit_timeout_ms: c_int,
pub initial_retransmit_timeout_ms: c_int,
pub max_retransmit_attempts: c_int,
pub heartbeat_interval_ms: c_int,
}

304
deps/rustrtc-capi/src/ws_signaling.rs vendored Normal file
View File

@@ -0,0 +1,304 @@
//! WebSocket signaling client for SDP/ICE exchange.
//!
//! Provides 5 C-callable functions that let the Zig bridge connect to a
//! signaling server, send/receive JSON messages, and disconnect.
use std::collections::VecDeque;
use std::os::raw::{c_char, c_int};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::OnceLock;
use futures_util::{SinkExt, StreamExt};
use parking_lot::Mutex;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::Message;
use crate::state;
// ============================================================================
// WebSocket State
// ============================================================================
static NEXT_WS_ID: AtomicI32 = AtomicI32::new(1);
static WS_ENTRIES: OnceLock<Mutex<Vec<Option<WsState>>>> = OnceLock::new();
const MAX_WS_CONNECTIONS: usize = 8;
const MAX_RECV_QUEUE: usize = 256;
struct WsState {
id: i32,
connected: AtomicBool,
/// Sender for outgoing messages (to the writer task)
tx: mpsc::UnboundedSender<String>,
/// Received messages waiting to be polled by C caller
recv_queue: Mutex<VecDeque<String>>,
/// Background reader task handle
reader_task: Mutex<Option<JoinHandle<()>>>,
/// Background writer task handle
writer_task: Mutex<Option<JoinHandle<()>>>,
}
fn get_entries() -> &'static Mutex<Vec<Option<WsState>>> {
WS_ENTRIES.get_or_init(|| {
let mut v = Vec::with_capacity(MAX_WS_CONNECTIONS);
for _ in 0..MAX_WS_CONNECTIONS {
v.push(None);
}
Mutex::new(v)
})
}
// ============================================================================
// C API Functions
// ============================================================================
/// Connect to a signaling server via WebSocket.
/// `url` and `peer_id` are null-terminated C strings.
/// Returns a ws_id > 0 on success, or negative error code.
#[no_mangle]
pub unsafe extern "C" fn rtcWsConnect(url: *const c_char, peer_id: *const c_char) -> c_int {
if url.is_null() || peer_id.is_null() {
return -1;
}
let url_str = match std::ffi::CStr::from_ptr(url).to_str() {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let peer_id_str = match std::ffi::CStr::from_ptr(peer_id).to_str() {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let rt = match state::get_runtime() {
Some(rt) => rt,
None => {
// Ensure runtime is initialized
state::init_runtime();
match state::get_runtime() {
Some(rt) => rt,
None => return -2,
}
}
};
let ws_id = NEXT_WS_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::unbounded_channel::<String>();
// Connect in a blocking fashion so the C caller gets immediate result
let connect_result = rt.block_on(async {
tokio_tungstenite::connect_async(&url_str).await
});
let ws_stream = match connect_result {
Ok((stream, _response)) => stream,
Err(e) => {
log::error!("WebSocket connect failed: {}", e);
return -2;
}
};
let (mut write, mut read) = ws_stream.split();
// Send register message immediately
let register_msg = serde_json::json!({
"type": "register",
"peerId": peer_id_str
}).to_string();
if let Err(e) = rt.block_on(write.send(Message::Text(register_msg))) {
log::error!("Failed to send register: {}", e);
return -2;
}
let recv_queue = Mutex::new(VecDeque::new());
let connected = AtomicBool::new(true);
// Create the state entry first so tasks can reference the ID
let ws_state = WsState {
id: ws_id,
connected,
tx,
recv_queue,
reader_task: Mutex::new(None),
writer_task: Mutex::new(None),
};
// Store in entries
{
let mut entries = get_entries().lock();
let slot = entries.iter().position(|e| e.is_none());
match slot {
Some(idx) => entries[idx] = Some(ws_state),
None => return -3, // No free slots
}
}
// Spawn reader task
let reader_ws_id = ws_id;
let reader_handle = rt.spawn(async move {
while let Some(msg_result) = read.next().await {
match msg_result {
Ok(Message::Text(text)) => {
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == reader_ws_id)
}) {
if let Some(ws) = slot.as_ref() {
let mut queue = ws.recv_queue.lock();
if queue.len() < MAX_RECV_QUEUE {
queue.push_back(text);
}
}
}
}
Ok(Message::Close(_)) => break,
Ok(_) => {} // Ignore binary/ping/pong
Err(e) => {
log::warn!("WebSocket read error: {}", e);
break;
}
}
}
// Mark as disconnected
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == reader_ws_id)
}) {
if let Some(ws) = slot.as_ref() {
ws.connected.store(false, Ordering::Release);
}
}
});
// Spawn writer task
let mut writer_rx = rx;
let writer_handle = rt.spawn(async move {
while let Some(msg) = writer_rx.recv().await {
if write.send(Message::Text(msg)).await.is_err() {
break;
}
}
});
// Store task handles
{
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
*ws.reader_task.lock() = Some(reader_handle);
*ws.writer_task.lock() = Some(writer_handle);
}
}
}
ws_id
}
/// Disconnect a WebSocket connection.
/// Returns 0 on success, negative on error.
#[no_mangle]
pub extern "C" fn rtcWsDisconnect(ws_id: c_int) -> c_int {
let mut entries = get_entries().lock();
if let Some(idx) = entries.iter().position(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = entries[idx].take() {
ws.connected.store(false, Ordering::Release);
// Abort tasks
if let Some(h) = ws.reader_task.lock().take() {
h.abort();
}
if let Some(h) = ws.writer_task.lock().take() {
h.abort();
}
}
return 0;
}
-1
}
/// Send a message on a WebSocket connection.
/// `message` points to a buffer of `size` bytes (not null-terminated).
/// Returns 0 on success, negative on error.
#[no_mangle]
pub unsafe extern "C" fn rtcWsSend(ws_id: c_int, message: *const c_char, size: c_int) -> c_int {
if message.is_null() || size <= 0 {
return -1;
}
let bytes = std::slice::from_raw_parts(message as *const u8, size as usize);
let text = match std::str::from_utf8(bytes) {
Ok(s) => s.to_string(),
Err(_) => return -1,
};
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
if !ws.connected.load(Ordering::Acquire) {
return -2;
}
match ws.tx.send(text) {
Ok(_) => return 0,
Err(_) => return -2,
}
}
}
-1
}
/// Non-blocking receive: polls for the next message.
/// If a message is available, copies it into `buffer` (up to `*size` bytes),
/// updates `*size` to the actual message length, and returns 0.
/// If no message is available, returns 1 (would-block).
/// On error returns negative.
#[no_mangle]
pub unsafe extern "C" fn rtcWsRecv(
ws_id: c_int,
buffer: *mut c_char,
size: *mut c_int,
) -> c_int {
if buffer.is_null() || size.is_null() {
return -1;
}
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
let mut queue = ws.recv_queue.lock();
if let Some(msg) = queue.pop_front() {
let buf_size = *size as usize;
let msg_bytes = msg.as_bytes();
let copy_len = msg_bytes.len().min(buf_size);
std::ptr::copy_nonoverlapping(msg_bytes.as_ptr(), buffer as *mut u8, copy_len);
*size = msg_bytes.len() as c_int;
return 0;
}
return 1; // Would-block: no messages
}
}
-1
}
/// Check if a WebSocket connection is still connected.
/// Returns 1 if connected, 0 if not, negative on error.
#[no_mangle]
pub extern "C" fn rtcWsIsConnected(ws_id: c_int) -> c_int {
let entries = get_entries().lock();
if let Some(slot) = entries.iter().find(|e| {
e.as_ref().map_or(false, |ws| ws.id == ws_id)
}) {
if let Some(ws) = slot.as_ref() {
return if ws.connected.load(Ordering::Acquire) { 1 } else { 0 };
}
}
-1
}

573
deps/rustrtc-capi/tests/loopback.rs vendored Normal file
View File

@@ -0,0 +1,573 @@
//! Rust-side integration test: two PeerConnections exchange SDP/ICE and
//! send messages over a DataChannel.
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::sync::Arc;
use std::time::Duration;
// Use the crate's C API functions directly (rlib link)
use datachannel::*;
// Re-declare the #[repr(C)] types for test use (must match types.rs layout)
#[repr(C)]
struct TestConfiguration {
ice_servers: *const *const c_char,
ice_servers_count: c_int,
proxy_server: *const c_char,
bind_address: *const c_char,
certificate_type: c_int,
ice_transport_policy: c_int,
enable_ice_tcp: bool,
enable_ice_udp_mux: bool,
disable_auto_negotiation: bool,
force_media_transport: bool,
port_range_begin: u16,
port_range_end: u16,
mtu: c_int,
max_message_size: c_int,
}
#[repr(C)]
struct TestReliability {
unordered: bool,
unreliable: bool,
max_packet_life_time: u32,
max_retransmits: u32,
}
#[repr(C)]
struct TestDataChannelInit {
reliability: TestReliability,
protocol: *const c_char,
negotiated: bool,
manual_stream: bool,
stream: u16,
}
impl Default for TestConfiguration {
fn default() -> Self {
Self {
ice_servers: std::ptr::null(),
ice_servers_count: 0,
proxy_server: std::ptr::null(),
bind_address: std::ptr::null(),
certificate_type: 0,
ice_transport_policy: 0,
enable_ice_tcp: false,
enable_ice_udp_mux: false,
disable_auto_negotiation: false,
force_media_transport: false,
port_range_begin: 0,
port_range_end: 0,
mtu: 0,
max_message_size: 0,
}
}
}
// ---------------------------------------------------------------------------
// Shared test state
// ---------------------------------------------------------------------------
struct TestState {
sdp: parking_lot::Mutex<Option<String>>,
sdp_type: parking_lot::Mutex<Option<String>>,
candidates: parking_lot::Mutex<Vec<String>>,
gathering_complete: AtomicBool,
dc_open: AtomicBool,
dc_id: AtomicI32,
recv_messages: parking_lot::Mutex<Vec<Vec<u8>>>,
}
impl TestState {
fn new() -> Self {
Self {
sdp: parking_lot::Mutex::new(None),
sdp_type: parking_lot::Mutex::new(None),
candidates: parking_lot::Mutex::new(Vec::new()),
gathering_complete: AtomicBool::new(false),
dc_open: AtomicBool::new(false),
dc_id: AtomicI32::new(-1),
recv_messages: parking_lot::Mutex::new(Vec::new()),
}
}
}
// ---------------------------------------------------------------------------
// C callbacks
// ---------------------------------------------------------------------------
unsafe extern "C" fn on_description(
_pc: c_int,
sdp: *const c_char,
sdp_type: *const c_char,
ptr: *mut c_void,
) {
let state = &*(ptr as *const TestState);
let s = CStr::from_ptr(sdp).to_str().unwrap().to_string();
let t = CStr::from_ptr(sdp_type).to_str().unwrap().to_string();
*state.sdp.lock() = Some(s);
*state.sdp_type.lock() = Some(t);
}
unsafe extern "C" fn on_candidate(
_pc: c_int,
cand: *const c_char,
_mid: *const c_char,
ptr: *mut c_void,
) {
let state = &*(ptr as *const TestState);
let c = CStr::from_ptr(cand).to_str().unwrap().to_string();
state.candidates.lock().push(c);
}
unsafe extern "C" fn on_state_change(_pc: c_int, _state: c_int, _ptr: *mut c_void) {}
unsafe extern "C" fn on_gathering_state(_pc: c_int, state: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
if state == 2 {
ts.gathering_complete.store(true, Ordering::Release);
}
}
unsafe extern "C" fn on_data_channel(_pc: c_int, dc: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
ts.dc_id.store(dc, Ordering::Release);
rtcSetOpenCallback(dc, Some(on_open));
rtcSetClosedCallback(dc, Some(on_closed));
rtcSetErrorCallback(dc, Some(on_error));
rtcSetMessageCallback(dc, Some(on_message));
rtcSetUserPointer(dc, ptr);
}
unsafe extern "C" fn on_open(_id: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
ts.dc_open.store(true, Ordering::Release);
}
unsafe extern "C" fn on_closed(_id: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
ts.dc_open.store(false, Ordering::Release);
}
unsafe extern "C" fn on_error(_id: c_int, _err: *const c_char, _ptr: *mut c_void) {}
unsafe extern "C" fn on_message(_id: c_int, data: *const u8, size: c_int, ptr: *mut c_void) {
let ts = &*(ptr as *const TestState);
if size > 0 {
let bytes = std::slice::from_raw_parts(data, size as usize).to_vec();
ts.recv_messages.lock().push(bytes);
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn wait_for(flag: &AtomicBool, timeout: Duration) -> bool {
let start = std::time::Instant::now();
while !flag.load(Ordering::Acquire) {
if start.elapsed() > timeout {
return false;
}
std::thread::sleep(Duration::from_millis(50));
}
true
}
fn wait_for_sdp(state: &TestState, timeout: Duration) -> bool {
let start = std::time::Instant::now();
loop {
if state.sdp.lock().is_some() {
return true;
}
if start.elapsed() > timeout {
return false;
}
std::thread::sleep(Duration::from_millis(50));
}
}
fn wait_for_recv(state: &TestState, timeout: Duration) -> bool {
let start = std::time::Instant::now();
loop {
if !state.recv_messages.lock().is_empty() {
return true;
}
if start.elapsed() > timeout {
return false;
}
std::thread::sleep(Duration::from_millis(50));
}
}
fn default_dc_init() -> TestDataChannelInit {
TestDataChannelInit {
reliability: TestReliability {
unordered: false,
unreliable: false,
max_packet_life_time: 0,
max_retransmits: 0,
},
protocol: std::ptr::null(),
negotiated: false,
manual_stream: false,
stream: 0,
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[test]
fn test_preload_cleanup() {
unsafe {
rtcPreload();
rtcCleanup();
}
}
#[test]
fn test_create_pc_and_dc() {
unsafe {
rtcPreload();
let config = TestConfiguration::default();
let pc = rtcCreatePeerConnection(&config as *const _ as *const _);
assert!(pc > 0, "PC ID should be positive, got {pc}");
let label = CString::new("test").unwrap();
let init = default_dc_init();
let dc = rtcCreateDataChannelEx(pc, label.as_ptr(), &init as *const _ as *const _);
assert!(dc > 0, "DC ID should be positive, got {dc}");
rtcDeleteDataChannel(dc);
rtcClosePeerConnection(pc);
rtcDeletePeerConnection(pc);
rtcCleanup();
}
}
#[test]
fn test_sdp_generation() {
unsafe {
rtcPreload();
let alice_state = Arc::new(TestState::new());
let config = TestConfiguration::default();
let pc = rtcCreatePeerConnection(&config as *const _ as *const _);
let ptr = Arc::as_ptr(&alice_state) as *mut c_void;
rtcSetUserPointer(pc, ptr);
rtcSetLocalDescriptionCallback(pc, Some(on_description));
rtcSetLocalCandidateCallback(pc, Some(on_candidate));
rtcSetGatheringStateChangeCallback(pc, Some(on_gathering_state));
let label = CString::new("data").unwrap();
let init = default_dc_init();
let dc = rtcCreateDataChannelEx(pc, label.as_ptr(), &init as *const _ as *const _);
assert!(dc > 0);
rtcSetUserPointer(dc, ptr);
rtcSetOpenCallback(dc, Some(on_open));
rtcSetMessageCallback(dc, Some(on_message));
// Wait for SDP offer
assert!(
wait_for_sdp(&alice_state, Duration::from_secs(10)),
"Should generate SDP offer"
);
let sdp = alice_state.sdp.lock().clone().unwrap();
let sdp_type = alice_state.sdp_type.lock().clone().unwrap();
println!("SDP type: {sdp_type}");
println!("SDP length: {}", sdp.len());
assert_eq!(sdp_type, "offer");
assert!(sdp.contains("v=0"), "SDP should contain v=0");
rtcDeleteDataChannel(dc);
rtcClosePeerConnection(pc);
rtcDeletePeerConnection(pc);
rtcCleanup();
}
}
#[test]
fn test_loopback_exchange() {
unsafe {
rtcPreload();
let timeout = Duration::from_secs(15);
// --- Alice (offerer) ---
let alice = Arc::new(TestState::new());
let alice_config = TestConfiguration::default();
let alice_pc = rtcCreatePeerConnection(&alice_config as *const _ as *const _);
let alice_ptr = Arc::as_ptr(&alice) as *mut c_void;
rtcSetUserPointer(alice_pc, alice_ptr);
rtcSetLocalDescriptionCallback(alice_pc, Some(on_description));
rtcSetLocalCandidateCallback(alice_pc, Some(on_candidate));
rtcSetStateChangeCallback(alice_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(alice_pc, Some(on_gathering_state));
let label = CString::new("data").unwrap();
let init = default_dc_init();
let alice_dc =
rtcCreateDataChannelEx(alice_pc, label.as_ptr(), &init as *const _ as *const _);
assert!(alice_dc > 0);
rtcSetUserPointer(alice_dc, alice_ptr);
rtcSetOpenCallback(alice_dc, Some(on_open));
rtcSetClosedCallback(alice_dc, Some(on_closed));
rtcSetErrorCallback(alice_dc, Some(on_error));
rtcSetMessageCallback(alice_dc, Some(on_message));
// Wait for Alice's offer
assert!(wait_for_sdp(&alice, timeout), "Alice should generate offer");
let alice_sdp = alice.sdp.lock().clone().unwrap();
assert_eq!(alice.sdp_type.lock().clone().unwrap(), "offer");
println!("Alice offer SDP ({} bytes)", alice_sdp.len());
// Wait for Alice's gathering to complete
assert!(
wait_for(&alice.gathering_complete, timeout),
"Alice gathering should complete"
);
println!(
"Alice candidates: {}",
alice.candidates.lock().len()
);
// --- Bob (answerer) ---
let bob = Arc::new(TestState::new());
let bob_config = TestConfiguration::default();
let bob_pc = rtcCreatePeerConnection(&bob_config as *const _ as *const _);
let bob_ptr = Arc::as_ptr(&bob) as *mut c_void;
rtcSetUserPointer(bob_pc, bob_ptr);
rtcSetLocalDescriptionCallback(bob_pc, Some(on_description));
rtcSetLocalCandidateCallback(bob_pc, Some(on_candidate));
rtcSetStateChangeCallback(bob_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(bob_pc, Some(on_gathering_state));
rtcSetDataChannelCallback(bob_pc, Some(on_data_channel));
// Bob sets Alice's offer as remote description
let alice_sdp_c = CString::new(alice_sdp).unwrap();
let offer_type = CString::new("offer").unwrap();
let res = rtcSetRemoteDescription(bob_pc, alice_sdp_c.as_ptr(), offer_type.as_ptr());
assert_eq!(res, 0, "setRemoteDescription should succeed");
// Wait for Bob's answer
assert!(wait_for_sdp(&bob, timeout), "Bob should generate answer");
let bob_sdp = bob.sdp.lock().clone().unwrap();
assert_eq!(bob.sdp_type.lock().clone().unwrap(), "answer");
println!("Bob answer SDP ({} bytes)", bob_sdp.len());
// Wait for Bob's gathering
assert!(
wait_for(&bob.gathering_complete, timeout),
"Bob gathering should complete"
);
println!("Bob candidates: {}", bob.candidates.lock().len());
// Exchange SDP: Alice receives Bob's answer
let bob_sdp_c = CString::new(bob_sdp).unwrap();
let answer_type = CString::new("answer").unwrap();
let res = rtcSetRemoteDescription(alice_pc, bob_sdp_c.as_ptr(), answer_type.as_ptr());
assert_eq!(res, 0);
// Exchange ICE candidates
let alice_cands: Vec<String> = alice.candidates.lock().clone();
let bob_cands: Vec<String> = bob.candidates.lock().clone();
for c in &alice_cands {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(bob_pc, cc.as_ptr(), std::ptr::null());
}
for c in &bob_cands {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(alice_pc, cc.as_ptr(), std::ptr::null());
}
// Wait for DataChannels to open
assert!(wait_for(&alice.dc_open, timeout), "Alice DC should open");
println!("Alice DC open");
let bob_dc = bob.dc_id.load(Ordering::Acquire);
assert!(bob_dc > 0, "Bob should receive incoming DC, got {bob_dc}");
assert!(wait_for(&bob.dc_open, timeout), "Bob DC should open");
println!("Bob DC open");
// --- Send message: Alice → Bob ---
let msg = b"hello from alice";
let res = rtcSendMessage(alice_dc, msg.as_ptr(), msg.len() as c_int);
assert_eq!(res, 0, "send should succeed");
assert!(wait_for_recv(&bob, timeout), "Bob should receive message");
let received = bob.recv_messages.lock().first().unwrap().clone();
assert_eq!(received, msg.to_vec());
println!("Bob received: {:?}", String::from_utf8_lossy(&received));
// --- Send message: Bob → Alice ---
let reply = b"hello from bob";
let res = rtcSendMessage(bob_dc, reply.as_ptr(), reply.len() as c_int);
assert_eq!(res, 0);
assert!(wait_for_recv(&alice, timeout), "Alice should receive reply");
let received = alice.recv_messages.lock().first().unwrap().clone();
assert_eq!(received, reply.to_vec());
println!(
"Alice received: {:?}",
String::from_utf8_lossy(&received)
);
// Cleanup
rtcDeleteDataChannel(alice_dc);
rtcDeleteDataChannel(bob_dc);
rtcClosePeerConnection(alice_pc);
rtcDeletePeerConnection(alice_pc);
rtcClosePeerConnection(bob_pc);
rtcDeletePeerConnection(bob_pc);
rtcCleanup();
}
}
/// Test large message delivery at various chunk sizes (32KB, 64KB, 128KB, 256KB).
/// Validates 100% delivery at each size to find the SCTP drop threshold.
#[test]
fn test_large_message_delivery() {
unsafe {
rtcPreload();
let timeout = Duration::from_secs(30);
// --- Alice (offerer) ---
let alice = Arc::new(TestState::new());
let alice_config = TestConfiguration::default();
let alice_pc = rtcCreatePeerConnection(&alice_config as *const _ as *const _);
let alice_ptr = Arc::as_ptr(&alice) as *mut c_void;
rtcSetUserPointer(alice_pc, alice_ptr);
rtcSetLocalDescriptionCallback(alice_pc, Some(on_description));
rtcSetLocalCandidateCallback(alice_pc, Some(on_candidate));
rtcSetStateChangeCallback(alice_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(alice_pc, Some(on_gathering_state));
let label = CString::new("data").unwrap();
let init = default_dc_init();
let alice_dc =
rtcCreateDataChannelEx(alice_pc, label.as_ptr(), &init as *const _ as *const _);
assert!(alice_dc > 0);
rtcSetUserPointer(alice_dc, alice_ptr);
rtcSetOpenCallback(alice_dc, Some(on_open));
rtcSetClosedCallback(alice_dc, Some(on_closed));
rtcSetMessageCallback(alice_dc, Some(on_message));
assert!(wait_for_sdp(&alice, timeout), "Alice should generate offer");
let alice_sdp = alice.sdp.lock().clone().unwrap();
assert!(
wait_for(&alice.gathering_complete, timeout),
"Alice gathering should complete"
);
// --- Bob (answerer) ---
let bob = Arc::new(TestState::new());
let bob_config = TestConfiguration::default();
let bob_pc = rtcCreatePeerConnection(&bob_config as *const _ as *const _);
let bob_ptr = Arc::as_ptr(&bob) as *mut c_void;
rtcSetUserPointer(bob_pc, bob_ptr);
rtcSetLocalDescriptionCallback(bob_pc, Some(on_description));
rtcSetLocalCandidateCallback(bob_pc, Some(on_candidate));
rtcSetStateChangeCallback(bob_pc, Some(on_state_change));
rtcSetGatheringStateChangeCallback(bob_pc, Some(on_gathering_state));
rtcSetDataChannelCallback(bob_pc, Some(on_data_channel));
let alice_sdp_c = CString::new(alice_sdp).unwrap();
let offer_type = CString::new("offer").unwrap();
rtcSetRemoteDescription(bob_pc, alice_sdp_c.as_ptr(), offer_type.as_ptr());
assert!(wait_for_sdp(&bob, timeout), "Bob should generate answer");
let bob_sdp = bob.sdp.lock().clone().unwrap();
assert!(
wait_for(&bob.gathering_complete, timeout),
"Bob gathering should complete"
);
let bob_sdp_c = CString::new(bob_sdp).unwrap();
let answer_type = CString::new("answer").unwrap();
rtcSetRemoteDescription(alice_pc, bob_sdp_c.as_ptr(), answer_type.as_ptr());
// Exchange ICE candidates
for c in alice.candidates.lock().iter() {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(bob_pc, cc.as_ptr(), std::ptr::null());
}
for c in bob.candidates.lock().iter() {
let cc = CString::new(c.as_str()).unwrap();
rtcAddRemoteCandidate(alice_pc, cc.as_ptr(), std::ptr::null());
}
assert!(wait_for(&alice.dc_open, timeout), "Alice DC should open");
let bob_dc = bob.dc_id.load(Ordering::Acquire);
assert!(bob_dc > 0);
assert!(wait_for(&bob.dc_open, timeout), "Bob DC should open");
// --- Test message delivery at various chunk sizes ---
let sizes: &[usize] = &[32 * 1024, 64 * 1024, 128 * 1024, 256 * 1024];
let msg_count = 100;
for &chunk_size in sizes {
// Clear previous messages
bob.recv_messages.lock().clear();
let payload: Vec<u8> = (0..chunk_size).map(|i| (i % 256) as u8).collect();
for _ in 0..msg_count {
let res = rtcSendMessage(alice_dc, payload.as_ptr(), payload.len() as c_int);
assert_eq!(res, 0, "send should succeed for {chunk_size}B messages");
}
// Wait for all messages to arrive (generous timeout)
let wait_start = std::time::Instant::now();
loop {
let count = bob.recv_messages.lock().len();
if count >= msg_count {
break;
}
if wait_start.elapsed() > Duration::from_secs(20) {
println!(
"SCTP drop threshold found: {chunk_size}B — only {count}/{msg_count} delivered"
);
break;
}
std::thread::sleep(Duration::from_millis(50));
}
let received = bob.recv_messages.lock().len();
println!(
"Chunk size {chunk_size}B: {received}/{msg_count} messages delivered ({}%)",
received * 100 / msg_count
);
// Verify payload integrity for received messages
for msg in bob.recv_messages.lock().iter() {
assert_eq!(msg.len(), chunk_size, "Message size mismatch");
assert_eq!(msg[0], 0u8, "First byte should be 0");
assert_eq!(msg[chunk_size - 1], ((chunk_size - 1) % 256) as u8);
}
}
// Cleanup
rtcDeleteDataChannel(alice_dc);
rtcDeleteDataChannel(bob_dc);
rtcClosePeerConnection(alice_pc);
rtcDeletePeerConnection(alice_pc);
rtcClosePeerConnection(bob_pc);
rtcDeletePeerConnection(bob_pc);
rtcCleanup();
}
}

View File

@@ -77,6 +77,6 @@ ENV FILE_SIZE_MB=10
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
CMD pgrep docker-peer || exit 1
CMD pgrep docker-peer > /dev/null && ss -tlnp | grep -q ":${PEER_PORT}" || exit 1
CMD ["docker-peer"]

View File

@@ -9,11 +9,11 @@ This directory contains Docker-based testing infrastructure for simulating cross
│ p2p-test-network │
│ (172.28.0.0/16) │
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ seeder │◄───│leecher-1│ │leecher-2│ ... │
│ │172.28.1.│ │ :8081 │ │ :8082 │ │
│ │ :8080 │ └─────────┘ └─────────┘ │
│ └─────────┘ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ seeder │◄───│leecher-1│ │leecher-2│ ... │
│ │172.28.1.│ │ :8081 │ │ :8082 │ │
│ │ :8080 │ └─────────┘ └─────────┘ │
│ └─────────┘ │
└─────────────────────────────────────────────────────────────┘
```

View File

@@ -48,7 +48,7 @@ services:
ports:
- "8080:8080" # Expose for debugging
healthcheck:
test: ["CMD", "pgrep", "docker-peer"]
test: ["CMD-SHELL", "pgrep docker-peer > /dev/null && ss -tlnp | grep -q ':8080'"]
interval: 10s
timeout: 5s
retries: 3

View File

@@ -0,0 +1,17 @@
# Peer container for NAT-PMP testing
# Uses pre-built binary from host (for faster iteration)
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y \
iproute2 \
procps \
&& rm -rf /var/lib/apt/lists/*
# Copy pre-built binary (build with: zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux)
COPY zig-out/bin/mwp-demo /usr/local/bin/
# Test script
COPY docker-tests/nat-pmp/peer-test.sh /test.sh
RUN chmod +x /test.sh
WORKDIR /app

View File

@@ -0,0 +1,17 @@
# NAT Router with miniupnpd (NAT-PMP + UPnP IGD)
FROM alpine:3.19
RUN apk add --no-cache \
miniupnpd \
iptables \
iptables-legacy \
iproute2 \
bash
# Startup script (generates miniupnpd config dynamically)
COPY router-entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
EXPOSE 5351/udp
ENTRYPOINT ["/entrypoint.sh"]

View File

@@ -0,0 +1,128 @@
# NAT-PMP Protocol Testing
This directory contains a Docker-based test environment for the NAT-PMP (RFC 6886) implementation.
## Overview
NAT-PMP allows clients behind a NAT to:
1. Discover their external (public) IP address
2. Request port mappings from the NAT gateway
This test uses `miniupnpd` as the NAT-PMP daemon running on a simulated router.
## Network Topology
```
┌─────────────────────────────────────────────────────┐
│ Internal (10.100.0.0/24) │
│ │
│ ┌─────────┐ ┌─────────┐ ┌───────┐ │
│ │ peer-a │ │ peer-b │ │router │ │
│ │ .10 │ │ .11 │ │ .1 │ │
│ └─────────┘ └─────────┘ └───┬───┘ │
└─────────────────────────────────────────────┼──────┘
│
┌─────────────────────────────────────────────┼──────┐
│ External (10.200.0.0/24) │ │
│ ┌─────┴────┐ │
│ │ router │ │
│ │ .1 │ │
│ └──────────┘ │
└────────────────────────────────────────────────────┘
```
The router:
- Runs `miniupnpd` (NAT-PMP + UPnP IGD daemon)
- Does NAT (iptables MASQUERADE) for internal clients
- Uses a public-looking "external" IP (93.184.216.34) added as alias on the external interface (miniupnpd rejects private IPs)
## Quick Start
```bash
# Build Linux binary first (from project root)
zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux
# Run the test
cd docker-tests/nat-pmp
./run-test.sh
```
## What This Tests
| Component | What's Tested |
|-----------|---------------|
| Gateway discovery | Finding the NAT-PMP daemon on the network |
| External address query | Retrieving the public IP from the gateway |
| Port mapping request | Requesting a port forwarding rule |
| MWP integration | Using NAT-PMP discovered address in MWP |
## Expected Results
### External Address Discovery: PASS
The NAT-PMP implementation correctly queries miniupnpd and receives the external IP address.
```
info: NAT-PMP: External address is 93.184.216.34
Using NAT-PMP: 93.184.216.34:18201
```
### Port Mapping: PASS
miniupnpd creates DNAT and masquerade rules via libiptc (iptables-legacy).
```
info: NAT-PMP: Mapped UDP port 18101 -> 93.184.216.34:18101 (lifetime: 3600s)
```
### Connection: PASS
Full MWP hole punch completes. Both peers establish a verified connection through
the NAT router using DNAT port forwarding and hairpin masquerade.
## Files
| File | Purpose |
|------|---------|
| `docker-compose.yml` | Network topology and service definitions |
| `Dockerfile.router` | Router image with miniupnpd |
| `Dockerfile.peer` | Peer image with mwp-demo binary |
| `router-entrypoint.sh` | Router startup (NAT setup, miniupnpd config) |
| `peer-test.sh` | Peer test script |
| `run-test.sh` | Main test orchestrator |
## Troubleshooting
### "miniupnpd not running"
Check router logs:
```bash
docker compose logs router
```
Common issues:
- Invalid config options (miniupnpd is picky about format)
- Interface detection problems
### "NAT-PMP: Gateway returned error: Network Failure"
miniupnpd needs the `MINIUPNPD-POSTROUTING` chain in the nat table for masquerade
rules. If missing, the DNAT rule is created but miniupnpd reports failure. Ensure
`router-entrypoint.sh` creates all three chains: `MINIUPNPD` (nat), `MINIUPNPD-POSTROUTING` (nat), `MINIUPNPD` (filter).
### "Cannot determine gateway"
The NAT-PMP client probes common gateway IPs. Ensure the router is at 10.100.0.1.
## Real-World Usage
On a real network with NAT-PMP support (e.g., Apple AirPort, many consumer routers):
```zig
// NAT-PMP is automatically tried during address discovery
const external_ip = p2p_node.tryNatPmpDiscovery(18000, 3600);
if (external_ip) |ip| {
// Port 18000 is now mapped externally
std.log.info("External address: {}.{}.{}.{}:18000", .{ip[0], ip[1], ip[2], ip[3]});
}
```
## See Also
- [RFC 6886 - NAT-PMP](https://tools.ietf.org/html/rfc6886)
- [miniupnpd](http://miniupnp.free.fr/)
- `src/network/nat_pmp.zig` - Implementation

View File

@@ -0,0 +1,95 @@
# NAT-PMP Test Environment
#
# Architecture:
# ┌─────────────────────────────────────────────────────┐
# │ Internal (10.100.0.0/24) │
# │ │
# │ ┌─────────┐ ┌─────────┐ ┌───────┐ │
# │ │ peer-a │ │ peer-b │ │router │ │
# │ │ .10 │ │ .11 │ │ .1 │ │
# │ └─────────┘ └─────────┘ └───┬───┘ │
# └─────────────────────────────────────────────┼──────┘
# │
# ┌─────────────────────────────────────────────┼──────┐
# │ External (10.200.0.0/24) │ │
# │ ┌─────┴────┐ │
# │ │ router │ │
# │ │ .1 │ │
# │ └──────────┘ │
# └────────────────────────────────────────────────────┘
#
# The router runs miniupnpd and does NAT for internal clients.
# Peers can use NAT-PMP to discover their external address and map ports.
services:
# NAT Router with miniupnpd
router:
build:
context: .
dockerfile: Dockerfile.router
cap_add:
- NET_ADMIN
sysctls:
- net.ipv4.ip_forward=1
networks:
internal:
ipv4_address: 10.100.0.1
external:
ipv4_address: 10.200.0.1
healthcheck:
test: ["CMD-SHELL", "pgrep miniupnpd > /dev/null && ss -ulnp | grep -q ':5351' && iptables-legacy -t nat -L MINIUPNPD > /dev/null 2>&1"]
interval: 2s
timeout: 2s
retries: 5
# Peer A (behind NAT)
peer-a:
build:
context: ../..
dockerfile: docker-tests/nat-pmp/Dockerfile.peer
depends_on:
router:
condition: service_healthy
cap_add:
- NET_ADMIN
networks:
internal:
ipv4_address: 10.100.0.10
environment:
- PEER_NAME=alice
- PEER_PORT=18100
- GATEWAY_IP=10.100.0.1
command: ["sleep", "infinity"]
# Peer B (behind NAT)
peer-b:
build:
context: ../..
dockerfile: docker-tests/nat-pmp/Dockerfile.peer
depends_on:
router:
condition: service_healthy
cap_add:
- NET_ADMIN
networks:
internal:
ipv4_address: 10.100.0.11
environment:
- PEER_NAME=bob
- PEER_PORT=18200
- GATEWAY_IP=10.100.0.1
command: ["sleep", "infinity"]
networks:
internal:
driver: bridge
ipam:
config:
- subnet: 10.100.0.0/24
gateway: 10.100.0.254
external:
driver: bridge
ipam:
config:
- subnet: 10.200.0.0/24
gateway: 10.200.0.254

View File

@@ -0,0 +1,25 @@
#!/bin/bash
set -e
echo "=== NAT-PMP Peer Test ==="
echo "Peer: $PEER_NAME"
echo "Port: $PEER_PORT"
echo "Gateway: $GATEWAY_IP"
# Set default route through the NAT router
echo "Setting default route through NAT router..."
ip route del default 2>/dev/null || true
ip route add default via $GATEWAY_IP
echo "Current routes:"
ip route
echo ""
echo "Testing NAT-PMP discovery..."
# Run MWP demo (it will try NAT-PMP automatically)
exec mwp-demo \
--name "$PEER_NAME" \
--port "$PEER_PORT" \
--deterministic \
"$@"

View File

@@ -0,0 +1,80 @@
#!/bin/bash
set -e
echo "=== NAT-PMP Router Starting ==="
# Wait for interfaces to be ready
sleep 1
# Detect interfaces by IP subnet
# Internal network: 10.100.0.0/24, External network: 10.200.0.0/24
ETH0_IP=$(ip -4 addr show eth0 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1)
ETH1_IP=$(ip -4 addr show eth1 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1)
echo "eth0: $ETH0_IP"
echo "eth1: $ETH1_IP"
# Determine which is internal (10.100.x.x) vs external (10.200.x.x)
if echo "$ETH0_IP" | grep -q "^10\.100\."; then
INTERNAL_IF="eth0"
INTERNAL_IP="$ETH0_IP"
EXTERNAL_IF="eth1"
EXTERNAL_IP="$ETH1_IP"
else
INTERNAL_IF="eth1"
INTERNAL_IP="$ETH1_IP"
EXTERNAL_IF="eth0"
EXTERNAL_IP="$ETH0_IP"
fi
echo "Internal interface: $INTERNAL_IF ($INTERNAL_IP)"
echo "External interface: $EXTERNAL_IF ($EXTERNAL_IP)"
# Set up NAT (masquerade internal traffic going out external interface)
echo "Setting up NAT..."
# miniupnpd uses libiptc (legacy iptables API), so all rules must use iptables-legacy
iptables-legacy -t nat -A POSTROUTING -o $EXTERNAL_IF -j MASQUERADE
iptables-legacy -A FORWARD -i $INTERNAL_IF -o $EXTERNAL_IF -j ACCEPT
iptables-legacy -A FORWARD -i $EXTERNAL_IF -o $INTERNAL_IF -m state --state RELATED,ESTABLISHED -j ACCEPT
# Create MINIUPNPD chains that miniupnpd needs for port mapping
# PREROUTING: DNAT rules to redirect external ports to internal clients
iptables-legacy -t nat -N MINIUPNPD
iptables-legacy -t nat -A PREROUTING -j MINIUPNPD
# POSTROUTING: masquerade rules for hairpin NAT (internal-to-internal via external IP)
iptables-legacy -t nat -N MINIUPNPD-POSTROUTING
iptables-legacy -t nat -A POSTROUTING -j MINIUPNPD-POSTROUTING
# FORWARD: filter rules for forwarded traffic
iptables-legacy -N MINIUPNPD
iptables-legacy -A FORWARD -j MINIUPNPD
# Create miniupnpd config with correct interfaces
# miniupnpd rejects private IPs for ext_ip, so we use a public-looking IP
# and add it as an alias on the external interface so it's actually routable
FAKE_PUBLIC_IP="93.184.216.34"
ip addr add $FAKE_PUBLIC_IP/32 dev $EXTERNAL_IF
echo "Added $FAKE_PUBLIC_IP as alias on $EXTERNAL_IF"
cat > /tmp/miniupnpd.conf << EOF
ext_ifname=$EXTERNAL_IF
ext_ip=$FAKE_PUBLIC_IP
listening_ip=$INTERNAL_IF
enable_natpmp=yes
enable_upnp=yes
secure_mode=no
system_uptime=yes
lease_file=/var/lib/miniupnpd/leases
allow 1024-65535 10.100.0.0/24 1024-65535
EOF
echo "miniupnpd config:"
cat /tmp/miniupnpd.conf
# Create lease directory
mkdir -p /var/lib/miniupnpd
echo ""
echo "Starting miniupnpd..."
echo "NAT-PMP will listen on $INTERNAL_IP:5351"
# Start miniupnpd in foreground with debug output
exec miniupnpd -d -f /tmp/miniupnpd.conf

134
docker-tests/nat-pmp/run-test.sh Executable file
View File

@@ -0,0 +1,134 @@
#!/bin/bash
# NAT-PMP Integration Test
#
# This test verifies that NAT-PMP works correctly for:
# 1. External address discovery
# 2. Port mapping
# 3. Full MWP connection through NAT
set -e
cd "$(dirname "$0")"
echo "=========================================="
echo " NAT-PMP Integration Test"
echo "=========================================="
# Cleanup function
cleanup() {
echo ""
echo "Cleaning up..."
docker compose down -v --remove-orphans 2>/dev/null || true
}
trap cleanup EXIT
# Build and start
echo ""
echo "[1/4] Building containers..."
docker compose build
echo ""
echo "[2/4] Starting NAT router..."
docker compose up -d router
sleep 3
# Check router is running
echo ""
echo "[3/4] Verifying NAT-PMP daemon..."
docker compose exec router pgrep miniupnpd > /dev/null || {
echo "ERROR: miniupnpd not running!"
docker compose logs router
exit 1
}
echo "miniupnpd is running"
# Show router state
echo ""
echo "Router NAT table:"
docker compose exec router iptables-legacy -t nat -L -n | head -20
echo ""
echo "[4/4] Running peer tests..."
# Start peer-a in background
echo ""
echo "--- Starting peer-a (alice) ---"
docker compose run -d --name test-peer-a peer-a /test.sh --connect-to bob
sleep 2
# Get alice's DHT ID from logs
ALICE_DHT=$(docker logs test-peer-a 2>&1 | grep -o 'DHT Node ID: [0-9a-f]*' | head -1 | cut -d' ' -f4)
if [ -z "$ALICE_DHT" ]; then
echo "ERROR: Could not get Alice's DHT ID"
docker logs test-peer-a
exit 1
fi
echo "Alice DHT ID: $ALICE_DHT"
# Check if NAT-PMP worked for alice
echo ""
echo "Alice's NAT-PMP status:"
docker logs test-peer-a 2>&1 | grep -i "nat-pmp" || echo "(no NAT-PMP messages)"
# Start peer-b connecting to alice
echo ""
echo "--- Starting peer-b (bob) ---"
docker compose run --name test-peer-b peer-b /test.sh \
--connect-to alice \
--bootstrap 10.100.0.10:18100 \
--dht-id "$ALICE_DHT" &
# Wait for connection
echo ""
echo "Waiting for MWP connection..."
sleep 15
# Check results
echo ""
echo "=========================================="
echo " Test Results"
echo "=========================================="
echo ""
echo "--- Alice logs ---"
docker logs test-peer-a 2>&1 | tail -30
echo ""
echo "--- Bob logs ---"
docker logs test-peer-b 2>&1 | tail -30
# Check for success indicators
ALICE_NATPMP=$(docker logs test-peer-a 2>&1 | grep -c "NAT-PMP:" || true)
BOB_NATPMP=$(docker logs test-peer-b 2>&1 | grep -c "NAT-PMP:" || true)
CONNECTION=$(docker logs test-peer-b 2>&1 | grep -c "CONNECTION ESTABLISHED" || true)
echo ""
echo "=========================================="
echo " Summary"
echo "=========================================="
echo "Alice NAT-PMP messages: $ALICE_NATPMP"
echo "Bob NAT-PMP messages: $BOB_NATPMP"
echo "Connection established: $([ $CONNECTION -gt 0 ] && echo 'YES' || echo 'NO')"
# Check for external address discovery
if docker logs test-peer-a 2>&1 | grep -q "Using NAT-PMP:"; then
echo ""
echo "SUCCESS: NAT-PMP address discovery working!"
EXTERNAL=$(docker logs test-peer-a 2>&1 | grep "Using NAT-PMP:" | head -1)
echo "$EXTERNAL"
else
echo ""
echo "NOTE: NAT-PMP address discovery not confirmed"
echo "(This may be expected if miniupnpd configuration needs adjustment)"
fi
echo ""
# Final pass/fail
ALICE_CONNECTED=$(docker logs test-peer-a 2>&1 | grep -c "CONNECTION ESTABLISHED" || true)
if [ $ALICE_CONNECTED -gt 0 ] && [ $CONNECTION -gt 0 ]; then
echo "PASS: Both peers established connection through NAT"
elif [ $ALICE_CONNECTED -gt 0 ] || [ $CONNECTION -gt 0 ]; then
echo "PASS: At least one peer established connection through NAT"
else
echo "FAIL: No connection established"
exit 1
fi

View File

@@ -0,0 +1,64 @@
# Dockerfile for MWP NAT Traversal Testing
#
# Build context should be the project root (zig-p2p/)
# Run: docker build -f docker-tests/nat/Dockerfile -t mwp-peer .
FROM debian:bookworm-slim AS builder
# Install dependencies
RUN apt-get update && apt-get install -y \
curl \
xz-utils \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Install Zig
ARG ZIG_VERSION=0.15.2
ARG TARGETARCH
RUN set -ex; \
case "${TARGETARCH}" in \
amd64) ZIG_ARCH="x86_64" ;; \
arm64) ZIG_ARCH="aarch64" ;; \
*) echo "Unsupported architecture: ${TARGETARCH}"; exit 1 ;; \
esac; \
curl -fsSL "https://ziglang.org/download/${ZIG_VERSION}/zig-${ZIG_ARCH}-linux-${ZIG_VERSION}.tar.xz" -o /tmp/zig.tar.xz && \
tar -xJf /tmp/zig.tar.xz -C /opt && \
mv /opt/zig-${ZIG_ARCH}-linux-${ZIG_VERSION} /opt/zig && \
rm /tmp/zig.tar.xz
ENV PATH="/opt/zig:${PATH}"
# Copy source and build
WORKDIR /build
COPY src ./src
COPY build.zig ./build.zig
COPY examples ./examples
COPY docker-tests ./docker-tests
COPY tests ./tests
# Build all targets (needed for install step)
RUN zig build && \
cp zig-out/bin/mwp-demo /build/mwp-demo && \
ls -la /build/mwp-demo
# =============================================================================
# Runtime Stage
# =============================================================================
FROM debian:bookworm-slim AS runtime
RUN apt-get update && apt-get install -y \
ca-certificates \
iproute2 \
iputils-ping \
net-tools \
tcpdump \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /build/mwp-demo /usr/local/bin/mwp-demo
RUN chmod +x /usr/local/bin/mwp-demo
WORKDIR /app
# Default command shows help
CMD ["mwp-demo", "--help"]

113
docker-tests/nat/README.md Normal file
View File

@@ -0,0 +1,113 @@
# NAT Traversal Testing for MWP
This directory contains a Docker-based NAT simulation environment for testing the Mutual Witness Protocol (MWP) NAT traversal capabilities.
## Network Topology
```
┌─────────────────── public (10.200.0.0/24) ───────────────────┐
│ │
│ bootstrap (10.200.0.10) - Rendezvous/DHT node │
│ │ │
│ ┌────┴────┐ ┌─────────┐ │
│ │ nat1 │ 10.200.0.2 │ nat2 │ 10.200.0.3 │
│ │ gateway │ │ gateway │ │
│ └────┬────┘ └────┬────┘ │
└───────┼────────────────────────────────────┼─────────────────┘
│ │
│ NAT (MASQUERADE) │ NAT (MASQUERADE)
│ │
┌───────┴───────┐ ┌───────┴───────┐
│ private_alice │ │ private_bob │
│ (10.201.0.0) │ │ (10.202.0.0) │
│ │ │ │
│ alice │ │ bob │
│ 10.201.0.10 │ │ 10.202.0.10 │
└───────────────┘ └───────────────┘
```
## Quick Start
```bash
# Run the full NAT traversal test
./run-nat-test.sh
```
## Manual Testing
```bash
# Build the image
docker-compose build
# Start NAT gateways
docker-compose up -d nat1 nat2
# Start bootstrap node
docker-compose up -d bootstrap
# Get bootstrap DHT ID
docker-compose logs bootstrap | grep "DHT Node ID"
# Start peers with the DHT ID
export BOOTSTRAP_DHT_ID=<id-from-above>
docker-compose up alice bob
# View logs
docker-compose logs -f alice bob
```
## What This Tests
1. **DHT Discovery**: Can Alice and Bob find each other's publications through the DHT when they're behind different NATs?
2. **IP Reflection**: Does the bootstrap node correctly report the NAT's public IP:port to each peer?
3. **Hole Punching**: Can Alice and Bob establish a direct UDP connection through both NATs?
## Expected Results
### DHT Discovery: Should PASS
Both peers should be able to publish and find each other's MWP publications via the DHT through the bootstrap node.
### Hole Punching: May FAIL
Docker's iptables-based NAT typically implements **symmetric NAT** or **port-restricted cone NAT**, which makes UDP hole punching difficult or impossible without:
- A relay server (TURN)
- Protocol extensions for symmetric NAT traversal
This is expected behavior and matches real-world scenarios where some NAT types require relay fallback.
## NAT Types
| NAT Type | Hole Punch Success Rate |
|----------|------------------------|
| Full Cone | ~100% |
| Restricted Cone | ~90% |
| Port-Restricted Cone | ~60% |
| Symmetric | ~10% (needs prediction) |
Docker's NAT is typically port-restricted cone or symmetric.
## Troubleshooting
### "Cannot connect to bootstrap"
- Check that nat1/nat2 gateways are running and healthy
- Verify routing tables in alice/bob containers:
```bash
docker-compose exec alice ip route
```
### "DHT FIND_VALUE not found"
- Ensure bootstrap node has the publications stored
- Check that both peers are using the correct bootstrap DHT ID
- Verify `p2p.update()` is being called (see CLAUDE.md)
### "Hole punch timeout"
- This is expected for symmetric NAT
- The DHT discovery should still work
- Future: implement relay fallback
## Files
- `Dockerfile` - Builds the mwp-demo binary
- `docker-compose.yml` - Defines the network topology
- `run-nat-test.sh` - Automated test script

View File

@@ -0,0 +1,287 @@
# NAT Traversal Test Environment for MWP
#
# Network Topology:
#
# ┌─────────────────── public (10.200.0.0/24) ──────────────────┐
# │ │
# │ bootstrap (10.200.0.10) │
# │ │ │
# │ ┌────┴────┐ ┌─────────┐ │
# │ │ nat1 │ 10.200.0.2 │ nat2 │ 10.200.0.3│
# │ │ gateway │ │ gateway │ │
# │ └────┬────┘ └────┬────┘ │
# └───────┼────────────────────────────────────┼────────────────┘
# │ │
# ┌───────┴───────┐ ┌────────┴──────┐
# │ private_alice │ │ private_bob │
# │ (10.201.0.0) │ │ (10.202.0.0) │
# │ │ │ │
# │ alice │ │ bob │
# │ 10.201.0.10 │ │ 10.202.0.10 │
# └───────────────┘ └───────────────┘
#
# Usage:
# docker-compose up --build
# docker-compose logs -f alice bob
networks:
public:
driver: bridge
ipam:
config:
- subnet: 10.200.0.0/24
private_alice:
driver: bridge
internal: false
ipam:
config:
- subnet: 10.201.0.0/24
private_bob:
driver: bridge
internal: false
ipam:
config:
- subnet: 10.202.0.0/24
services:
# ==========================================================================
# NAT Gateway 1 (for Alice)
# ==========================================================================
nat1:
image: alpine:latest
container_name: nat1
cap_add:
- NET_ADMIN
sysctls:
- net.ipv4.ip_forward=1
networks:
public:
ipv4_address: 10.200.0.2
private_alice:
ipv4_address: 10.201.0.2
command:
- sh
- -c
- |
echo 'Installing iptables...'
apk add --no-cache iptables
echo 'Setting up NAT gateway 1...'
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush existing rules
iptables -t nat -F
iptables -F FORWARD
# NAT: Masquerade traffic from private network going to public
iptables -t nat -A POSTROUTING -s 10.201.0.0/24 -o eth0 -j MASQUERADE
# Allow forwarding
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
echo 'NAT1 gateway ready'
iptables -t nat -L -n -v
# Keep container running
sleep infinity
healthcheck:
test: ["CMD", "sh", "-c", "iptables -t nat -L >/dev/null 2>&1"]
interval: 5s
timeout: 10s
retries: 5
start_period: 30s
# ==========================================================================
# NAT Gateway 2 (for Bob)
# ==========================================================================
nat2:
image: alpine:latest
container_name: nat2
cap_add:
- NET_ADMIN
sysctls:
- net.ipv4.ip_forward=1
networks:
public:
ipv4_address: 10.200.0.3
private_bob:
ipv4_address: 10.202.0.2
command:
- sh
- -c
- |
echo 'Installing iptables...'
apk add --no-cache iptables
echo 'Setting up NAT gateway 2...'
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Flush existing rules
iptables -t nat -F
iptables -F FORWARD
# NAT: Masquerade traffic from private network going to public
iptables -t nat -A POSTROUTING -s 10.202.0.0/24 -o eth0 -j MASQUERADE
# Allow forwarding
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
echo 'NAT2 gateway ready'
iptables -t nat -L -n -v
# Keep container running
sleep infinity
healthcheck:
test: ["CMD", "sh", "-c", "iptables -t nat -L >/dev/null 2>&1"]
interval: 5s
timeout: 10s
retries: 5
start_period: 30s
# ==========================================================================
# Bootstrap Node (on public network - acts as rendezvous point)
# This node just runs MWP and serves DHT requests - it doesn't connect to anyone
# ==========================================================================
bootstrap:
build:
context: ../..
dockerfile: docker-tests/nat/Dockerfile
container_name: bootstrap
networks:
public:
ipv4_address: 10.200.0.10
command:
- sh
- -c
- |
echo '=========================================='
echo 'Starting bootstrap node on public network'
echo 'IP: 10.200.0.10, Port: 18100'
echo '=========================================='
mwp-demo --name bootstrap --port 18100 --deterministic
healthcheck:
test: ["CMD", "sh", "-c", "netstat -tuln | grep 18100"]
interval: 5s
timeout: 10s
retries: 5
start_period: 30s
# ==========================================================================
# Alice (behind NAT1)
# ==========================================================================
alice:
build:
context: ../..
dockerfile: docker-tests/nat/Dockerfile
container_name: alice
cap_add:
- NET_ADMIN
depends_on:
nat1:
condition: service_healthy
bootstrap:
condition: service_healthy
networks:
private_alice:
ipv4_address: 10.201.0.20
environment:
- BOOTSTRAP_DHT_ID=${BOOTSTRAP_DHT_ID:-}
command:
- sh
- -c
- |
echo '=========================================='
echo 'Configuring Alice network'
echo '=========================================='
# Set default route through NAT gateway
ip route del default 2>/dev/null || true
ip route add default via 10.201.0.2
echo 'Alice routing table:'
ip route
echo 'Testing connectivity to bootstrap...'
ping -c 2 10.200.0.10 || echo 'Ping failed (may be blocked)'
echo 'Waiting for bootstrap node...'
sleep 5
if [ -z "$BOOTSTRAP_DHT_ID" ]; then
echo 'ERROR: BOOTSTRAP_DHT_ID not set!'
exit 1
fi
echo '=========================================='
echo 'Starting Alice'
echo 'Bootstrap: 10.200.0.10:18100'
echo "DHT ID: $BOOTSTRAP_DHT_ID"
echo '=========================================='
mwp-demo --name alice --port 18100 --deterministic --connect-to bob \
--bootstrap 10.200.0.10:18100 \
--dht-id "$BOOTSTRAP_DHT_ID"
# ==========================================================================
# Bob (behind NAT2)
# ==========================================================================
bob:
build:
context: ../..
dockerfile: docker-tests/nat/Dockerfile
container_name: bob
cap_add:
- NET_ADMIN
depends_on:
nat2:
condition: service_healthy
bootstrap:
condition: service_healthy
networks:
private_bob:
ipv4_address: 10.202.0.20
environment:
- BOOTSTRAP_DHT_ID=${BOOTSTRAP_DHT_ID:-}
command:
- sh
- -c
- |
echo '=========================================='
echo 'Configuring Bob network'
echo '=========================================='
# Set default route through NAT gateway
ip route del default 2>/dev/null || true
ip route add default via 10.202.0.2
echo 'Bob routing table:'
ip route
echo 'Testing connectivity to bootstrap...'
ping -c 2 10.200.0.10 || echo 'Ping failed (may be blocked)'
echo 'Waiting for network setup...'
sleep 8
if [ -z "$BOOTSTRAP_DHT_ID" ]; then
echo 'ERROR: BOOTSTRAP_DHT_ID not set!'
exit 1
fi
echo '=========================================='
echo 'Starting Bob'
echo 'Bootstrap: 10.200.0.10:18100'
echo "DHT ID: $BOOTSTRAP_DHT_ID"
echo '=========================================='
mwp-demo --name bob --port 18100 --deterministic --connect-to alice \
--bootstrap 10.200.0.10:18100 \
--dht-id "$BOOTSTRAP_DHT_ID"

186
docker-tests/nat/run-nat-test.sh Executable file
View File

@@ -0,0 +1,186 @@
#!/bin/bash
#
# NAT Traversal Test Script for MWP
#
# This script sets up a simulated NAT environment using Docker and tests
# whether two peers (Alice and Bob) behind different NATs can discover
# each other and establish a connection.
#
# Network topology:
# - Bootstrap node on public network (172.20.0.10)
# - Alice behind NAT1 (172.18.0.10 -> 172.20.0.2)
# - Bob behind NAT2 (172.19.0.10 -> 172.20.0.3)
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
cleanup() {
log_info "Cleaning up..."
cd "$SCRIPT_DIR"
docker compose down --volumes --remove-orphans 2>/dev/null || true
}
trap cleanup EXIT
# =============================================================================
# Main
# =============================================================================
log_info "=========================================="
log_info "MWP NAT Traversal Test"
log_info "=========================================="
cd "$SCRIPT_DIR"
# Step 1: Build the Docker image
log_info "Building MWP Docker image..."
docker compose build --quiet
# Step 2: Start NAT gateways first
log_info "Starting NAT gateways..."
docker compose up -d nat1 nat2
sleep 2
# Step 3: Start bootstrap node
log_info "Starting bootstrap node..."
docker compose up -d bootstrap
sleep 3
# Step 4: Get bootstrap node's DHT ID
log_info "Getting bootstrap node DHT ID..."
BOOTSTRAP_DHT_ID=""
for i in {1..10}; do
BOOTSTRAP_DHT_ID=$(docker compose logs bootstrap 2>/dev/null | grep -o "DHT Node ID: [a-f0-9]*" | head -1 | cut -d' ' -f4)
if [ -n "$BOOTSTRAP_DHT_ID" ]; then
break
fi
log_info "Waiting for bootstrap DHT ID... (attempt $i/10)"
sleep 2
done
if [ -z "$BOOTSTRAP_DHT_ID" ]; then
log_error "Failed to get bootstrap DHT ID"
docker compose logs bootstrap
exit 1
fi
log_success "Bootstrap DHT ID: $BOOTSTRAP_DHT_ID"
# Step 5: Export DHT ID and start Alice and Bob
export BOOTSTRAP_DHT_ID
log_info "Starting Alice and Bob with bootstrap DHT ID..."
# Start Alice and Bob
docker compose up -d alice bob
# Step 6: Monitor for results (60 second timeout)
log_info "Monitoring for NAT traversal results..."
log_info "(Timeout: 60 seconds)"
TIMEOUT=60
START_TIME=$(date +%s)
ALICE_FOUND=false
BOB_FOUND=false
HOLE_PUNCH_SUCCESS=false
while true; do
CURRENT_TIME=$(date +%s)
ELAPSED=$((CURRENT_TIME - START_TIME))
if [ $ELAPSED -ge $TIMEOUT ]; then
log_warn "Timeout reached after ${TIMEOUT}s"
break
fi
# Check Alice's logs
if ! $ALICE_FOUND; then
if docker compose logs alice 2>/dev/null | grep -q "FOUND PEER PUBLICATION"; then
log_success "Alice found Bob's publication!"
ALICE_FOUND=true
fi
fi
# Check Bob's logs
if ! $BOB_FOUND; then
if docker compose logs bob 2>/dev/null | grep -q "FIND_VALUE.*found=true"; then
log_success "Bob found Alice's publication via DHT!"
BOB_FOUND=true
fi
fi
# Check for hole punch success
if docker compose logs alice bob 2>/dev/null | grep -q "Hole punch.*success\|Connection established"; then
log_success "Hole punch succeeded!"
HOLE_PUNCH_SUCCESS=true
break
fi
# Check for hole punch failure (expected in some NAT types)
if docker compose logs bob 2>/dev/null | grep -q "Hole punch failed"; then
log_warn "Hole punch failed (may be expected for symmetric NAT)"
break
fi
sleep 2
done
# Step 7: Print results
echo ""
log_info "=========================================="
log_info "Test Results"
log_info "=========================================="
echo ""
if $ALICE_FOUND && $BOB_FOUND; then
log_success "DHT Discovery: PASSED"
echo " - Alice found Bob's publication"
echo " - Bob found Alice's publication"
else
log_error "DHT Discovery: FAILED"
if ! $ALICE_FOUND; then echo " - Alice did NOT find Bob"; fi
if ! $BOB_FOUND; then echo " - Bob did NOT find Alice"; fi
fi
echo ""
if $HOLE_PUNCH_SUCCESS; then
log_success "Hole Punch: PASSED"
else
log_warn "Hole Punch: FAILED (expected for symmetric NAT)"
echo " - Docker's iptables NAT is typically symmetric/port-restricted"
echo " - This makes hole punching difficult without relay"
fi
echo ""
log_info "=========================================="
# Step 8: Show detailed logs on failure
if ! $ALICE_FOUND || ! $BOB_FOUND; then
echo ""
log_info "Alice logs (last 30 lines):"
docker compose logs --tail=30 alice
echo ""
log_info "Bob logs (last 30 lines):"
docker compose logs --tail=30 bob
fi
# Exit with appropriate code
if $ALICE_FOUND && $BOB_FOUND; then
exit 0
else
exit 1
fi

View File

@@ -0,0 +1,17 @@
# Peer container for UPnP IGD testing
# Uses pre-built binary from host (for faster iteration)
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y \
iproute2 \
procps \
&& rm -rf /var/lib/apt/lists/*
# Copy pre-built binary (build with: zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux)
COPY zig-out/bin/mwp-demo /usr/local/bin/
# Test script
COPY docker-tests/upnp/peer-test.sh /test.sh
RUN chmod +x /test.sh
WORKDIR /app

View File

@@ -0,0 +1,18 @@
# NAT Router with miniupnpd (UPnP IGD only, NAT-PMP disabled)
FROM alpine:3.19
RUN apk add --no-cache \
miniupnpd \
iptables \
iptables-legacy \
iproute2 \
bash
# Startup script (generates miniupnpd config dynamically)
COPY router-entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
# UPnP SSDP multicast + HTTP control port
EXPOSE 1900/udp
ENTRYPOINT ["/entrypoint.sh"]

117
docker-tests/upnp/README.md Normal file
View File

@@ -0,0 +1,117 @@
# UPnP IGD Protocol Testing
This directory contains a Docker-based test environment for the UPnP IGD (Internet Gateway Device) implementation.
## Overview
UPnP IGD allows clients behind a NAT to:
1. Discover the gateway via SSDP multicast (239.255.255.250:1900)
2. Fetch the gateway's XML device description
3. Use SOAP to query the external (public) IP address
4. Use SOAP to request port mappings from the NAT gateway
This test uses `miniupnpd` as the UPnP daemon with **NAT-PMP disabled**, so the mwp-demo is forced to use the UPnP IGD path.
## Network Topology
```
┌─────────────────────────────────────────────────────┐
│ Internal (10.100.0.0/24) │
│ │
│ ┌─────────┐ ┌─────────┐ ┌───────┐ │
│ │ peer-a │ │ peer-b │ │router │ │
│ │ .10 │ │ .11 │ │ .1 │ │
│ └─────────┘ └─────────┘ └───┬───┘ │
└─────────────────────────────────────────────┼──────┘
│
┌─────────────────────────────────────────────┼──────┐
│ External (10.200.0.0/24) │ │
│ ┌─────┴────┐ │
│ │ router │ │
│ │ .1 │ │
│ └──────────┘ │
└────────────────────────────────────────────────────┘
```
The router:
- Runs `miniupnpd` with UPnP IGD enabled, NAT-PMP disabled
- Does NAT (iptables MASQUERADE) for internal clients
- Uses a public-looking "external" IP (93.184.216.34) added as alias on the external interface (miniupnpd rejects private IPs)
## Quick Start
```bash
# Build Linux binary first (from project root)
zig build -Doptimize=ReleaseFast -Dtarget=aarch64-linux
# Run the test
cd docker-tests/upnp
./run-test.sh
```
## What This Tests
| Component | What's Tested |
|-----------|---------------|
| SSDP discovery | M-SEARCH multicast finds the UPnP gateway |
| XML description | Fetching and parsing the gateway's device XML |
| GetExternalIPAddress | SOAP request to retrieve the public IP |
| AddPortMapping | SOAP request for port forwarding |
| MWP integration | Using UPnP-discovered address in MWP |
| NAT-PMP fallthrough | NAT-PMP fails (disabled), UPnP is tried next |
## Expected Results
### External Address Discovery: PASS
The UPnP implementation discovers the gateway via SSDP, fetches its XML description, and queries the external IP via SOAP.
```
UPnP: External address is 93.184.216.34
Using UPnP IGD: 93.184.216.34:18101
```
### Port Mapping: PASS
miniupnpd creates DNAT and masquerade rules via libiptc (iptables-legacy).
```
info: UPnP: Mapped UDP port 18101 -> 93.184.216.34:18101 (lifetime: 3600s)
```
### Connection: PASS
Full MWP hole punch completes. Both peers establish a verified connection through
the NAT router using DNAT port forwarding and hairpin masquerade.
### NAT-PMP: SKIPPED
NAT-PMP is disabled on the router (`enable_natpmp=no`), so the mwp-demo's NAT-PMP attempt fails silently and falls through to UPnP.
## Files
| File | Purpose |
|------|---------|
| `docker-compose.yml` | Network topology and service definitions |
| `Dockerfile.router` | Router image with miniupnpd (UPnP only) |
| `Dockerfile.peer` | Peer image with mwp-demo binary |
| `router-entrypoint.sh` | Router startup (NAT setup, miniupnpd config with NAT-PMP disabled) |
| `peer-test.sh` | Peer test script |
| `run-test.sh` | Main test orchestrator |
## Troubleshooting
### "miniupnpd not running"
Check router logs:
```bash
docker compose logs router
```
### "UPnP: Gateway discovery failed"
SSDP multicast may not work on all Docker network configurations. Check that the internal bridge network allows multicast traffic.
### "No UPnP messages"
The mwp-demo tries NAT-PMP first. If NAT-PMP somehow succeeds (shouldn't with `enable_natpmp=no`), UPnP will be skipped. Check for `Using NAT-PMP:` in logs.
## See Also
- [UPnP IGD Specification](http://upnp.org/specs/gw/UPnP-gw-WANIPConnection-v1-Service.pdf)
- [miniupnpd](http://miniupnp.free.fr/)
- `src/network/upnp.zig` - Implementation
- `docker-tests/nat-pmp/` - NAT-PMP test (same topology, different protocol)

View File

@@ -0,0 +1,95 @@
# UPnP IGD Test Environment
#
# Architecture:
# ┌─────────────────────────────────────────────────────┐
# │ Internal (10.100.0.0/24) │
# │ │
# │ ┌─────────┐ ┌─────────┐ ┌───────┐ │
# │ │ peer-a │ │ peer-b │ │router │ │
# │ │ .10 │ │ .11 │ │ .1 │ │
# │ └─────────┘ └─────────┘ └───┬───┘ │
# └─────────────────────────────────────────────┼──────┘
# │
# ┌─────────────────────────────────────────────┼──────┐
# │ External (10.200.0.0/24) │ │
# │ ┌─────┴────┐ │
# │ │ router │ │
# │ │ .1 │ │
# │ └──────────┘ │
# └────────────────────────────────────────────────────┘
#
# The router runs miniupnpd with UPnP enabled and NAT-PMP disabled.
# Peers discover external address via SSDP multicast + SOAP.
services:
# NAT Router with miniupnpd (UPnP only, no NAT-PMP)
router:
build:
context: .
dockerfile: Dockerfile.router
cap_add:
- NET_ADMIN
sysctls:
- net.ipv4.ip_forward=1
networks:
internal:
ipv4_address: 10.100.0.1
external:
ipv4_address: 10.200.0.1
healthcheck:
test: ["CMD-SHELL", "pgrep miniupnpd > /dev/null && iptables-legacy -t nat -L MINIUPNPD > /dev/null 2>&1"]
interval: 2s
timeout: 2s
retries: 5
# Peer A (behind NAT)
peer-a:
build:
context: ../..
dockerfile: docker-tests/upnp/Dockerfile.peer
depends_on:
router:
condition: service_healthy
cap_add:
- NET_ADMIN
networks:
internal:
ipv4_address: 10.100.0.10
environment:
- PEER_NAME=alice
- PEER_PORT=18100
- GATEWAY_IP=10.100.0.1
command: ["sleep", "infinity"]
# Peer B (behind NAT)
peer-b:
build:
context: ../..
dockerfile: docker-tests/upnp/Dockerfile.peer
depends_on:
router:
condition: service_healthy
cap_add:
- NET_ADMIN
networks:
internal:
ipv4_address: 10.100.0.11
environment:
- PEER_NAME=bob
- PEER_PORT=18200
- GATEWAY_IP=10.100.0.1
command: ["sleep", "infinity"]
networks:
internal:
driver: bridge
ipam:
config:
- subnet: 10.100.0.0/24
gateway: 10.100.0.254
external:
driver: bridge
ipam:
config:
- subnet: 10.200.0.0/24
gateway: 10.200.0.254

25
docker-tests/upnp/peer-test.sh Executable file
View File

@@ -0,0 +1,25 @@
#!/bin/bash
set -e
echo "=== UPnP IGD Peer Test ==="
echo "Peer: $PEER_NAME"
echo "Port: $PEER_PORT"
echo "Gateway: $GATEWAY_IP"
# Set default route through the NAT router
echo "Setting default route through NAT router..."
ip route del default 2>/dev/null || true
ip route add default via $GATEWAY_IP
echo "Current routes:"
ip route
echo ""
echo "Testing UPnP IGD discovery..."
# Run MWP demo (NAT-PMP will fail since it's disabled, then UPnP will be tried)
exec mwp-demo \
--name "$PEER_NAME" \
--port "$PEER_PORT" \
--deterministic \
"$@"

View File

@@ -0,0 +1,82 @@
#!/bin/bash
set -e
echo "=== UPnP IGD Router Starting ==="
# Wait for interfaces to be ready
sleep 1
# Detect interfaces by IP subnet
# Internal network: 10.100.0.0/24, External network: 10.200.0.0/24
ETH0_IP=$(ip -4 addr show eth0 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1)
ETH1_IP=$(ip -4 addr show eth1 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1)
echo "eth0: $ETH0_IP"
echo "eth1: $ETH1_IP"
# Determine which is internal (10.100.x.x) vs external (10.200.x.x)
if echo "$ETH0_IP" | grep -q "^10\.100\."; then
INTERNAL_IF="eth0"
INTERNAL_IP="$ETH0_IP"
EXTERNAL_IF="eth1"
EXTERNAL_IP="$ETH1_IP"
else
INTERNAL_IF="eth1"
INTERNAL_IP="$ETH1_IP"
EXTERNAL_IF="eth0"
EXTERNAL_IP="$ETH0_IP"
fi
echo "Internal interface: $INTERNAL_IF ($INTERNAL_IP)"
echo "External interface: $EXTERNAL_IF ($EXTERNAL_IP)"
# Set up NAT (masquerade internal traffic going out external interface)
echo "Setting up NAT..."
# miniupnpd uses libiptc (legacy iptables API), so all rules must use iptables-legacy
iptables-legacy -t nat -A POSTROUTING -o $EXTERNAL_IF -j MASQUERADE
iptables-legacy -A FORWARD -i $INTERNAL_IF -o $EXTERNAL_IF -j ACCEPT
iptables-legacy -A FORWARD -i $EXTERNAL_IF -o $INTERNAL_IF -m state --state RELATED,ESTABLISHED -j ACCEPT
# Create MINIUPNPD chains that miniupnpd needs for port mapping
# PREROUTING: DNAT rules to redirect external ports to internal clients
iptables-legacy -t nat -N MINIUPNPD
iptables-legacy -t nat -A PREROUTING -j MINIUPNPD
# POSTROUTING: masquerade rules for hairpin NAT (internal-to-internal via external IP)
iptables-legacy -t nat -N MINIUPNPD-POSTROUTING
iptables-legacy -t nat -A POSTROUTING -j MINIUPNPD-POSTROUTING
# FORWARD: filter rules for forwarded traffic
iptables-legacy -N MINIUPNPD
iptables-legacy -A FORWARD -j MINIUPNPD
# Create miniupnpd config with UPnP ENABLED and NAT-PMP DISABLED
# This forces peers to use UPnP IGD (SSDP + SOAP) instead of NAT-PMP
# miniupnpd rejects private IPs for ext_ip, so we use a public-looking IP
# and add it as an alias on the external interface so it's actually routable
FAKE_PUBLIC_IP="93.184.216.34"
ip addr add $FAKE_PUBLIC_IP/32 dev $EXTERNAL_IF
echo "Added $FAKE_PUBLIC_IP as alias on $EXTERNAL_IF"
cat > /tmp/miniupnpd.conf << EOF
ext_ifname=$EXTERNAL_IF
ext_ip=$FAKE_PUBLIC_IP
listening_ip=$INTERNAL_IF
enable_natpmp=no
enable_upnp=yes
secure_mode=no
system_uptime=yes
lease_file=/var/lib/miniupnpd/leases
allow 1024-65535 10.100.0.0/24 1024-65535
EOF
echo "miniupnpd config:"
cat /tmp/miniupnpd.conf
# Create lease directory
mkdir -p /var/lib/miniupnpd
echo ""
echo "Starting miniupnpd..."
echo "UPnP IGD will listen on $INTERNAL_IF (SSDP multicast + SOAP HTTP)"
echo "NAT-PMP is DISABLED"
# Start miniupnpd in foreground with debug output
exec miniupnpd -d -f /tmp/miniupnpd.conf

152
docker-tests/upnp/run-test.sh Executable file
View File

@@ -0,0 +1,152 @@
#!/bin/bash
# UPnP IGD Integration Test
#
# This test verifies that UPnP IGD works correctly for:
# 1. SSDP multicast discovery of the gateway
# 2. SOAP GetExternalIPAddress
# 3. SOAP AddPortMapping
# 4. Full MWP address discovery through UPnP
#
# NAT-PMP is DISABLED on the router so the mwp-demo falls through to UPnP.
set -e
cd "$(dirname "$0")"
echo "=========================================="
echo " UPnP IGD Integration Test"
echo "=========================================="
# Cleanup function
cleanup() {
echo ""
echo "Cleaning up..."
docker compose down -v --remove-orphans 2>/dev/null || true
}
trap cleanup EXIT
# Build and start
echo ""
echo "[1/4] Building containers..."
docker compose build
echo ""
echo "[2/4] Starting NAT router (UPnP enabled, NAT-PMP disabled)..."
docker compose up -d router
sleep 3
# Check router is running
echo ""
echo "[3/4] Verifying UPnP daemon..."
docker compose exec router pgrep miniupnpd > /dev/null || {
echo "ERROR: miniupnpd not running!"
docker compose logs router
exit 1
}
echo "miniupnpd is running (UPnP mode)"
# Show router state
echo ""
echo "Router NAT table:"
docker compose exec router iptables-legacy -t nat -L -n | head -20
echo ""
echo "[4/4] Running peer tests..."
# Start peer-a in background
echo ""
echo "--- Starting peer-a (alice) ---"
docker compose run -d --name test-peer-a peer-a /test.sh --connect-to bob
sleep 2
# Get alice's DHT ID from logs
ALICE_DHT=$(docker logs test-peer-a 2>&1 | grep -o 'DHT Node ID: [0-9a-f]*' | head -1 | cut -d' ' -f4)
if [ -z "$ALICE_DHT" ]; then
echo "ERROR: Could not get Alice's DHT ID"
docker logs test-peer-a
exit 1
fi
echo "Alice DHT ID: $ALICE_DHT"
# Check if UPnP worked for alice
echo ""
echo "Alice's UPnP status:"
docker logs test-peer-a 2>&1 | grep -i "upnp" || echo "(no UPnP messages yet)"
# Start peer-b connecting to alice
echo ""
echo "--- Starting peer-b (bob) ---"
docker compose run --name test-peer-b peer-b /test.sh \
--connect-to alice \
--bootstrap 10.100.0.10:18100 \
--dht-id "$ALICE_DHT" &
# Wait for connection
echo ""
echo "Waiting for MWP connection..."
sleep 15
# Check results
echo ""
echo "=========================================="
echo " Test Results"
echo "=========================================="
echo ""
echo "--- Alice logs ---"
docker logs test-peer-a 2>&1 | tail -30
echo ""
echo "--- Bob logs ---"
docker logs test-peer-b 2>&1 | tail -30
# Check for success indicators
ALICE_UPNP=$(docker logs test-peer-a 2>&1 | grep -c "UPnP" || true)
BOB_UPNP=$(docker logs test-peer-b 2>&1 | grep -c "UPnP" || true)
ALICE_NATPMP=$(docker logs test-peer-a 2>&1 | grep -c "Using NAT-PMP:" || true)
BOB_NATPMP=$(docker logs test-peer-b 2>&1 | grep -c "Using NAT-PMP:" || true)
CONNECTION=$(docker logs test-peer-b 2>&1 | grep -c "CONNECTION ESTABLISHED" || true)
echo ""
echo "=========================================="
echo " Summary"
echo "=========================================="
echo "Alice UPnP messages: $ALICE_UPNP"
echo "Bob UPnP messages: $BOB_UPNP"
echo "Alice NAT-PMP used: $([ $ALICE_NATPMP -gt 0 ] && echo 'YES (unexpected!)' || echo 'NO (correct)')"
echo "Bob NAT-PMP used: $([ $BOB_NATPMP -gt 0 ] && echo 'YES (unexpected!)' || echo 'NO (correct)')"
echo "Connection established: $([ $CONNECTION -gt 0 ] && echo 'YES' || echo 'NO')"
# Check for UPnP external address discovery
if docker logs test-peer-a 2>&1 | grep -q "Using UPnP IGD:"; then
echo ""
echo "SUCCESS: UPnP IGD address discovery working!"
EXTERNAL=$(docker logs test-peer-a 2>&1 | grep "Using UPnP IGD:" | head -1)
echo "$EXTERNAL"
else
echo ""
echo "NOTE: UPnP IGD address discovery not confirmed in mwp-demo output"
# Check lower-level UPnP messages
if docker logs test-peer-a 2>&1 | grep -q "UPnP: External address is"; then
echo "But UPnP SOAP GetExternalIPAddress succeeded:"
docker logs test-peer-a 2>&1 | grep "UPnP: External address is" | head -1
fi
fi
# Verify NAT-PMP was NOT used (since it's disabled)
if [ $ALICE_NATPMP -gt 0 ] || [ $BOB_NATPMP -gt 0 ]; then
echo ""
echo "WARNING: NAT-PMP was used despite being disabled on the router!"
echo "This suggests the NAT-PMP disable config is not working correctly."
fi
echo ""
# Final pass/fail
ALICE_CONNECTED=$(docker logs test-peer-a 2>&1 | grep -c "CONNECTION ESTABLISHED" || true)
if [ $ALICE_CONNECTED -gt 0 ] && [ $CONNECTION -gt 0 ]; then
echo "PASS: Both peers established connection through NAT"
elif [ $ALICE_CONNECTED -gt 0 ] || [ $CONNECTION -gt 0 ]; then
echo "PASS: At least one peer established connection through NAT"
else
echo "FAIL: No connection established"
exit 1
fi

View File

@@ -4,6 +4,7 @@ Complete API reference for the P2P file sharing library. This documentation cove
## Table of Contents
- [Event Loop Architecture](#event-loop-architecture) ⚠️ **Read First**
- [Core Module](#core-module)
- [Network Module](#network-module)
- [Protocol Module](#protocol-module)
@@ -11,6 +12,91 @@ Complete API reference for the P2P file sharing library. This documentation cove
- [Error Types](#error-types)
- [Data Structures](#data-structures)
---
## Event Loop Architecture
> ⚠️ **CRITICAL**: This library uses a poll-based architecture. You MUST call `p2p.update()` periodically for the library to function.
### Why Poll-Based?
This design choice enables:
- **WASM compatibility** - WebAssembly has no threading support
- **Single-threaded simplicity** - No mutex/synchronization complexity
- **Application control** - You decide when I/O happens (useful for games, simulations)
- **Consistency with rust-libp2p** - Same proven architecture pattern
### Basic Usage Pattern
```zig
const p2p_mod = @import("p2p");
pub fn main() !void {
var p2p = try p2p_mod.P2P.init(allocator, config);
defer p2p.deinit();
try p2p.start();
// Main application loop
while (running) {
// REQUIRED: Process network I/O
try p2p.update();
// Your application logic here
handleEvents();
// Control loop timing
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
```
### Common Mistake
```zig
// ❌ WRONG - Will never receive responses!
fn waitForPeer(p2p: *P2P, target: [32]u8) !?Publication {
const deadline = now() + timeout;
while (now() < deadline) {
if (try findPeer(target)) |pub| return pub;
std.Thread.sleep(100 * std.time.ns_per_ms);
// BUG: Network messages are never processed!
}
return null;
}
// ✅ CORRECT - Call update() in the loop
fn waitForPeer(p2p: *P2P, target: [32]u8) !?Publication {
const deadline = now() + timeout;
while (now() < deadline) {
try p2p.update(); // Process incoming messages
if (try findPeer(target)) |pub| return pub;
std.Thread.sleep(100 * std.time.ns_per_ms);
}
return null;
}
```
### What `update()` Does
Each call to `p2p.update()` performs:
1. Accept incoming connections
2. Process received network data
3. Dispatch messages to handlers
4. Process file transfer operations
5. Send queued outgoing messages
### High-Level APIs
High-level APIs like MWP handle `update()` internally:
```zig
// MWP.connect() handles update() for you
const result = try mwp.connect(target_pubkey, .{ .timeout_ms = 30_000 });
```
---
## Module Import Guide
The library uses a module-based import system. Import modules as follows:

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
@@ -12,6 +12,7 @@ Comprehensive guide for using the P2P file sharing library. This guide covers tu
- [Best Practices](#best-practices)
- [Performance Optimization](#performance-optimization)
- [Security Considerations](#security-considerations)
- [NAT Traversal](#nat-traversal)
- [Troubleshooting](#troubleshooting)
- [Migration Guide](#migration-guide)
@@ -19,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
@@ -33,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**:
@@ -914,6 +915,49 @@ var p2p_instance = try p2p.P2P.init(allocator, config);
defer p2p_instance.deinit();
```
## NAT Traversal
The library automatically discovers your public address and maps ports through NAT gateways. No manual configuration is needed for most networks — the system tries multiple strategies in order and uses the first one that succeeds.
### Address Discovery Priority
| Priority | Method | Protocol | How It Works |
|----------|--------|----------|-------------|
| 1 | Explicit IP | Manual | `--public-ip` flag (for known static IPs or Docker) |
| 2 | NAT-PMP | RFC 6886 | 2-packet UDP exchange with the gateway on port 5351 |
| 3 | UPnP IGD | SSDP + SOAP | Multicast discovery (239.255.255.250:1900), then HTTP/SOAP for port mapping |
| 4 | IP Reflection | DHT-bundled | Every DHT response includes the requester's observed address (zero-infrastructure STUN) |
Each method both discovers the external IP and requests a port mapping (where applicable). If a method fails (e.g., router doesn't support NAT-PMP), the next one is tried automatically.
### What Happens Automatically
When a P2P node starts and needs to advertise a reachable address (e.g., for MWP hole punching):
1. **NAT-PMP** — Sends a UDP request to the default gateway. If the router supports NAT-PMP (Apple AirPort, many consumer routers), the external IP and port mapping are returned in ~10ms.
2. **UPnP IGD** — If NAT-PMP fails, sends an SSDP M-SEARCH multicast to find UPnP-enabled routers, fetches the XML device description, then uses SOAP to query the external IP and request a port mapping. Works on most consumer routers.
3. **IP Reflection** — If both NAT-PMP and UPnP fail (e.g., on a VPS or network without gateway support), the node learns its public IP from DHT peers. Every DHT response includes an `observed_addr` field containing the sender's view of the requester's IP. Multiple observers build consensus for reliability.
### When You Might Need Manual Configuration
- **Carrier-grade NAT (CGNAT)**: Double-NAT scenarios where your router's "external" IP is still private. Port mapping succeeds but the mapped address isn't publicly reachable.
- **Strict corporate firewalls**: UDP may be blocked entirely. The library is UDP-only (no TCP fallback).
- **Symmetric NAT**: Port mapping works, but hole punching may fail because the NAT assigns different external ports per destination.
In these cases, use `--public-ip` with a known reachable address, or set up a relay node on a public server.
### Implementation Details
| Component | Source File |
|-----------|------------|
| NAT-PMP client | `src/network/nat_pmp.zig` |
| UPnP IGD client | `src/network/upnp.zig` |
| IP Reflection | Built into DHT responses (`src/p2p/dht.zig`) |
| Address discovery orchestration | `src/p2p/p2p.zig` (`tryNatPmpDiscovery`, `tryUpnpDiscovery`) |
| Docker E2E tests | `docker-tests/nat-pmp/`, `docker-tests/upnp/` |
## Troubleshooting
### Common Issues
@@ -1040,4 +1084,4 @@ defer p2p_instance.deinit();
---
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).

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.

239
docs/ip-reflection-trust.md Normal file
View File

@@ -0,0 +1,239 @@
# IP Reflection Trust Model
## Overview
This document explains how zig-p2p discovers external addresses through IP Reflection (Bundled STUN), the trust model for observed addresses, and how the Noise protocol provides the actual security guarantees.
## Key Insight: Address Discovery vs Identity Verification
**IP Reflection solves reachability, not security.**
| Concern | Mechanism | Trust Level |
|---------|-----------|-------------|
| "What is my external address?" | IP Reflection | Varies (see below) |
| "Is this really the peer I want?" | Noise Protocol | Cryptographic proof |
Even if a malicious peer lies about your address, the Noise handshake will fail when you try to connect to the wrong peer because they won't have the correct private key.
## How IP Reflection Works
### Unidirectional (Response-only)
Traditional approach: You query a peer, they include your observed address in their response.
```
Alice → Bob: DHT FIND_VALUE (query)
Bob → Alice: DHT FIND_VALUE_RESPONSE + "I see you at 203.0.113.5:12345"
```
**Problem:** Alice must initiate a query to learn her address. If Alice is a listener waiting for connections, she never queries anyone and never learns her address.
### Bidirectional (Request + Response)
Our enhancement: Requests also include the target's observed address.
```
Bob → Alice: DHT FIND_VALUE + "I see you at 203.0.113.5:12345" (query)
Alice → Bob: DHT FIND_VALUE_RESPONSE + "I see you at 198.51.100.10:54321"
```
**Benefit:** Alice learns her address from incoming requests, even as a pure listener.
## Trust Levels
```zig
pub const AddressConfidence = enum {
none, // No observers yet
single_source, // One peer reported this address
consensus, // Multiple peers agree
conflict, // Peers disagree (using majority)
};
```
### None
No peers have reported an observed address yet.
**Application guidance:** Cannot publish reachable address. Use fallback (localhost, manual config, or STUN server).
### Single Source
One peer reported this address. Common in:
- Two-peer networks
- Initial bootstrap phase
- Sparse networks
**Application guidance:**
- Address is likely correct but unverified
- Acceptable for most use cases
- The Noise handshake protects against connecting to wrong peer
- Consider logging/warning for security-sensitive applications
### Consensus
Multiple independent peers report the same address.
**Application guidance:**
- High confidence the address is correct
- Safe to publish and advertise
- Recommended for public-facing services
### Conflict
Peers report different addresses. Possible causes:
- NAT with multiple exit points
- Network reconfiguration
- Malicious peer(s)
**Application guidance:**
- Majority address is used
- Consider investigating the discrepancy
- May want to avoid publishing until resolved
- Check if you're behind symmetric NAT
## API Usage
### Getting Consensus Address
```zig
const p2p = @import("p2p");
// Get address with trust information
const result = p2p_node.getConsensusAddress();
switch (result.confidence) {
.none => {
// No address available
log.warn("No observed address yet", .{});
},
.single_source => {
// One peer reported - use with awareness
log.info("Address from single source (unverified): {}", .{result.address});
// Application decides: proceed or wait for more observers?
},
.consensus => {
// Multiple peers agree - high confidence
log.info("Verified address ({}/{} observers agree): {}",
.{result.observer_count, result.total_observers, result.address});
},
.conflict => {
// Peers disagree - investigate
log.warn("Address conflict! Using majority ({}/{} agree): {}",
.{result.observer_count, result.total_observers, result.address});
// Application may want to alert user or use fallback
},
}
```
### Example: Conservative Publishing
```zig
fn publishService(p2p_node: *p2p.P2P, service_info: []const u8) !void {
const result = p2p_node.getConsensusAddress();
// Require at least single source
if (result.confidence == .none) {
return error.NoAddressAvailable;
}
// Warn on low confidence
if (result.confidence == .single_source) {
log.warn("Publishing with unverified address", .{});
}
// Refuse to publish on conflict
if (result.confidence == .conflict) {
log.err("Address conflict detected - refusing to publish", .{});
return error.AddressConflict;
}
// Proceed with publication
try dht.store(service_key, service_info);
}
```
### Example: Wait for Consensus
```zig
fn waitForVerifiedAddress(p2p_node: *p2p.P2P, timeout_ms: i64) !p2p.ObservedAddress {
const start = std.time.milliTimestamp();
while (std.time.milliTimestamp() - start < timeout_ms) {
const result = p2p_node.getConsensusAddress();
if (result.confidence == .consensus) {
return result.address.?;
}
try p2p_node.update();
std.Thread.sleep(100 * std.time.ns_per_ms);
}
// Timeout - return best available or error
const final = p2p_node.getConsensusAddress();
return final.address orelse error.NoAddressAvailable;
}
```
## Why Noise Protocol is the Real Security
IP Reflection only answers: "What address should I advertise?"
It does NOT guarantee:
- The address is correct
- No one is lying
- The peer at that address is who you want
**The Noise Protocol XX handshake provides:**
1. **Mutual Authentication**: Both peers prove they hold their private keys
2. **Forward Secrecy**: Compromising keys later doesn't decrypt past sessions
3. **Identity Binding**: Connection is bound to specific public keys
### Attack Scenario: Malicious IP Reflection
```
Mallory (malicious) tells Alice: "Your IP is 192.0.2.99" (wrong)
Alice publishes wrong address to DHT
Bob tries to connect to 192.0.2.99 (Mallory's server)
```
**What happens:**
1. Bob initiates Noise handshake with 192.0.2.99
2. Mallory cannot complete handshake (doesn't have Alice's private key)
3. Bob's connection fails with authentication error
4. Bob knows something is wrong
**Result:** Mallory caused a denial of service (Bob can't reach Alice), but could NOT:
- Impersonate Alice
- Read Alice's messages
- Inject messages as Alice
### Defense in Depth
| Layer | Protects Against |
|-------|-----------------|
| IP Reflection Consensus | Accidental misconfiguration, single malicious peer |
| Noise Protocol | Impersonation, MITM, eavesdropping |
| MWP Signatures | Wrong peer at correct address |
| DHT Key Verification | DHT poisoning attacks |
## Recommendations
### For Most Applications
- Accept `single_source` confidence
- Rely on Noise handshake for security
- Log confidence level for debugging
### For High-Security Applications
- Wait for `consensus` before publishing sensitive services
- Alert on `conflict` detection
- Consider supplementing with trusted STUN servers
- Implement address pinning (remember verified addresses)
### For Two-Peer Scenarios
- Accept that consensus is impossible with only one observer
- Trust the Noise handshake
- Consider pre-shared address configuration for critical deployments
## Summary
1. **IP Reflection** discovers your external address by asking peers what they see
2. **Bidirectional IP Reflection** allows listeners to learn their address from incoming requests
3. **Consensus** provides confidence but is not always achievable (two-peer networks)
4. **Noise Protocol** is the real security layer - cryptographic proof of identity
5. **Applications** should use confidence levels to make informed decisions, not as security enforcement

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

466
docs/mwp/COMPARISON.md Normal file
View File

@@ -0,0 +1,466 @@
# MWP vs Existing Solutions: Detailed Comparison
**Version:** 1.0.0
**Created:** February 2026
---
## Executive Summary
| Solution | Infrastructure | Latency | Success Rate | Decentralization |
|----------|---------------|---------|--------------|------------------|
| **MWP** | DHT only | ~1-2s | ~70% | **Full** |
| DCUtR | Relay nodes | ~2s | ~70% | Partial |
| STUN+Signaling | 2 servers | ~1-2s | ~80% | Low |
| ICE/TURN | 3+ servers | ~2-5s | ~95% | Low |
---
## 1. Protocol Flow Comparison
### 1.1 DCUtR (libp2p)
```
┌─────────────────────────────────────────────────────────────┐
│ DCUtR FLOW │
│ │
│ Alice Relay Bob │
│ │ │ │ │
│ │─── Connect ───────────>│ │ │
│ │ │<─── Connect ───────────│ │
│ │ │ │ │
│ │─── CONNECT msg ───────>│ │ │
│ │ │─── CONNECT msg ───────>│ │
│ │ │<─── CONNECT msg ───────│ │
│ │<─── CONNECT msg ───────│ │ │
│ │ │ │ │
│ │ (Relay measures RTT between messages) │ │
│ │ │ │ │
│ │─── SYNC msg ──────────>│ │ │
│ │ (wait RTT/2) │ │ │
│ │ │─── SYNC msg ──────────>│ │
│ │ │ │ │
│ │<════════════ hole punch attempt ═══════════════>│ │
│ │ │ │ │
│ │
│ Messages: 6 (via relay) │
│ Round trips: 3 │
│ Infrastructure: Relay node(s) │
└─────────────────────────────────────────────────────────────┘
```
### 1.2 STUN + Signaling Server
```
┌─────────────────────────────────────────────────────────────┐
│ STUN + SIGNALING FLOW │
│ │
│ Alice STUN Signaling STUN Bob │
│ │ │ │ │ │ │
│ │─ Binding ───>│ │ │ │ │
│ │<─ Response ──│ │ │ │ │
│ │ │ │ │<─ Bind ─│ │
│ │ │ │ │─ Resp ─>│ │
│ │ │ │ │ │ │
│ │───────── SDP Offer ─────>│ │ │ │
│ │ │ │──── Offer ──────────> │ │
│ │ │ │<─── Answer ───────────│ │
│ │<──────── SDP Answer ─────│ │ │ │
│ │ │ │ │ │ │
│ │<══════════════ hole punch ══════════════════════>│ │
│ │ │ │ │ │ │
│ │
│ Messages: 8 (4 STUN + 4 signaling) │
│ Round trips: 3 │
│ Infrastructure: STUN server + Signaling server │
└─────────────────────────────────────────────────────────────┘
```
### 1.3 Full ICE with TURN
```
┌─────────────────────────────────────────────────────────────┐
│ FULL ICE FLOW │
│ │
│ Alice STUN TURN Signal TURN STUN Bob │
│ │ │ │ │ │ │ │ │
│ │─ Bind ───>│ │ │ │ │ │ │
│ │<─ Resp ───│ │ │ │ │<Bind─│ │
│ │─ Alloc ─────────>│ │ │ │ │ │
│ │<─ Relay ─────────│ │ │ │ │ │
│ │ │ │ │ │<─ Alloc ─────│ │
│ │ │ │ │ │─ Relay ─────>│ │
│ │ │ │ │ │ │ │ │
│ │─────────── SDP Offer ─────>│ │ │ │ │
│ │ │ │ │──────────────────────>│ │
│ │ │ │ │<──────────────────────│ │
│ │<────────── SDP Answer ─────│ │ │ │ │
│ │ │ │ │ │ │ │ │
│ │ (ICE connectivity checks - multiple paths) │ │
│ │ │ │ │ │ │ │ │
│ │<══════════════ connection (direct or relayed) ═══>│ │
│ │ │ │ │ │ │ │ │
│ │
│ Messages: 10+ (STUN + TURN + Signaling + ICE checks) │
│ Round trips: 5+ │
│ Infrastructure: STUN + TURN + Signaling │
└─────────────────────────────────────────────────────────────┘
```
### 1.4 Mutual Witness Protocol
```
┌─────────────────────────────────────────────────────────────┐
│ MWP FLOW │
│ │
│ Alice DHT Bob │
│ │ │ │ │
│ │─── PUT(key, pub_A) ────>│ │ │
│ │ │<─── PUT(key, pub_B) ────│ │
│ │ │ │ │
│ │<─── GET(key) ──────────>│<─────── GET(key) ──────>│ │
│ │ (returns pub_A, pub_B) │ │ │
│ │ │ │ │
│ │ (compute shared params locally) │ │
│ │ (wait until rendezvous_time) │ │
│ │ │ │ │
│ │<══════════════ hole punch attempt ═══════════════>│ │
│ │ │ │ │
│ │
│ Messages: 4 (2 PUT + 2 GET) │
│ Round trips: 1-2 │
│ Infrastructure: DHT only (already exists in P2P network) │
└─────────────────────────────────────────────────────────────┘
```
---
## 2. Infrastructure Comparison
### 2.1 Required Components
| Component | DCUtR | STUN+Signal | ICE/TURN | **MWP** |
|-----------|-------|-------------|----------|---------|
| DHT | Yes | No | No | **Yes** |
| Relay nodes | Yes | No | Yes (TURN) | **No** |
| STUN server | No | Yes | Yes | **No** |
| Signaling server | No | Yes | Yes | **No** |
| Bootstrap nodes | Yes | N/A | N/A | Yes |
### 2.2 Operational Costs
| Cost Factor | DCUtR | STUN+Signal | ICE/TURN | **MWP** |
|-------------|-------|-------------|----------|---------|
| Server hosting | High (relay BW) | Medium | High | **Zero** |
| Bandwidth | Relay traffic | Minimal | Relay traffic | **Zero** |
| Maintenance | Relay health | Server uptime | All servers | **DHT only** |
| Scaling | Per-user relay | Central bottleneck | Per-user TURN | **Distributed** |
### 2.3 Who Pays?
| Solution | Who Runs Infrastructure | Who Pays |
|----------|-------------------------|----------|
| DCUtR | Protocol developers, volunteers | Unclear (altruism) |
| STUN+Signal | Application developers | Application owner |
| ICE/TURN | Cloud providers (Twilio, etc.) | Per-minute fees |
| **MWP** | **P2P participants** | **Nobody (self-sustaining)** |
---
## 3. Performance Comparison
### 3.1 Latency Breakdown
**DCUtR:**
```
Connect to relay: 100-500ms
CONNECT exchange: 2 × RTT to relay (~200ms)
SYNC + wait: RTT/2 (~100ms)
Hole punch: 50-200ms
────────────────────────────────────────
Total: ~1-2 seconds
```
**STUN + Signaling:**
```
STUN binding (both): 2 × 50ms = 100ms
SDP offer/answer: 2 × RTT to server (~200ms)
Hole punch: 50-200ms
────────────────────────────────────────
Total: ~500ms - 1.5 seconds
```
**MWP:**
```
DHT PUT: 100-500ms
DHT GET (poll): 100-500ms
Wait for rendezvous: 500ms (configurable)
Hole punch: 50-200ms
────────────────────────────────────────
Total: ~1-2 seconds
```
### 3.2 Latency by Scenario
| Scenario | DCUtR | STUN+Signal | MWP |
|----------|-------|-------------|-----|
| Best case (fast network) | 800ms | **400ms** | 600ms |
| Typical | 2s | 1.5s | **1.5s** |
| Slow DHT/relay | 5s | 3s | **3s** |
| Retry needed | 4s | 3s | **3s** |
### 3.3 Success Rates
| NAT Type | DCUtR | STUN+Signal | ICE/TURN | MWP |
|----------|-------|-------------|----------|-----|
| Full Cone | 95% | 95% | 99% | **95%** |
| Restricted Cone | 85% | 85% | 99% | **85%** |
| Port Restricted | 70% | 75% | 99% | **70%** |
| Symmetric | 50%* | 30% | 99%* | **30%** |
*DCUtR and ICE fall back to relay for symmetric NAT
### 3.4 Bandwidth Usage
| Solution | Control Overhead | Data Path |
|----------|------------------|-----------|
| DCUtR | ~2KB via relay | Direct |
| STUN+Signal | ~3KB (SDP) | Direct |
| ICE/TURN | ~5KB + relay | Direct or relayed |
| **MWP** | **~500 bytes** | **Direct** |
---
## 4. Security & Privacy Comparison
### 4.1 Trust Requirements
| Solution | Who You Trust |
|----------|---------------|
| DCUtR | Relay nodes (see connection metadata) |
| STUN+Signal | STUN server, Signaling server |
| ICE/TURN | All of above + TURN operator |
| **MWP** | **DHT nodes (see meeting key only)** |
### 4.2 Metadata Exposure
| Data | DCUtR | STUN+Signal | MWP |
|------|-------|-------------|-----|
| Your IP | Relay sees | Servers see | DHT sees |
| Peer's IP | Relay sees | Servers see | DHT sees |
| Connection timing | Relay sees | Servers see | DHT sees |
| Who connects to whom | Relay knows | Signaling knows | **Hashed (meeting key)** |
| Connection content | Encrypted | Encrypted | Encrypted |
### 4.3 Attack Resistance
| Attack | DCUtR | STUN+Signal | MWP |
|--------|-------|-------------|-----|
| Server compromise | Metadata leak | Metadata leak | **N/A** |
| Relay DoS | Connection fails | N/A | **N/A** |
| DHT eclipse | Works (relay) | Works | **Degraded** |
| Meeting point squat | N/A | N/A | Signatures protect |
---
## 5. Decentralization Analysis
### 5.1 Centralization Points
```
DCUtR:
├── Relay nodes (must be online)
├── Relay selection (could be gamed)
└── Relay operators (trust required)
STUN+Signaling:
├── STUN server (Google's, etc.)
├── Signaling server (you run)
└── Single point of failure each
ICE/TURN:
├── STUN servers
├── TURN servers (expensive, central)
├── Signaling server
└── Maximum centralization
MWP:
└── DHT (distributed among all participants)
└── No single point of failure
```
### 5.2 Censorship Resistance
| Solution | Blocking Difficulty |
|----------|---------------------|
| DCUtR | Block relay IPs |
| STUN+Signal | Block server IPs |
| ICE/TURN | Block any server |
| **MWP** | **Must block all DHT nodes** |
### 5.3 Failure Modes
| If This Fails... | DCUtR | STUN+Signal | MWP |
|------------------|-------|-------------|-----|
| One relay | Use another | N/A | N/A |
| All relays | **Total failure** | N/A | N/A |
| STUN server | N/A | **Total failure** | N/A |
| Signaling server | N/A | **Total failure** | N/A |
| Some DHT nodes | Works | Works | **Works** |
| DHT partitioned | Works (relay) | Works | **Degraded** |
---
## 6. Implementation Complexity
### 6.1 Lines of Code (Estimated)
| Component | DCUtR | STUN+Signal | MWP |
|-----------|-------|-------------|-----|
| Core protocol | 2000 | 1500 | **1000** |
| Server/relay | 3000 | 2000 | 0 |
| DHT integration | 500 | 0 | 500 |
| NAT detection | 500 | 1000 | 300 |
| **Total** | 6000 | 4500 | **1800** |
### 6.2 Dependencies
| Solution | External Dependencies |
|----------|----------------------|
| DCUtR | libp2p, relay protocol |
| STUN+Signal | STUN lib, WebSocket, SDP parser |
| ICE/TURN | libnice/pion, full ICE stack |
| **MWP** | **DHT (already in P2P stack)** |
### 6.3 Testing Complexity
| Aspect | DCUtR | STUN+Signal | MWP |
|--------|-------|-------------|-----|
| Unit testing | Medium | Medium | **Easy** |
| Integration testing | Hard (relay) | Hard (servers) | **Medium** |
| E2E testing | Hard | Hard | **Medium** |
| Reproducing NAT | Hard | Hard | Hard |
---
## 7. Use Case Suitability
### 7.1 When to Use Each
**Use DCUtR when:**
- Already using libp2p
- Have relay infrastructure
- Need proven solution
- 70% success rate acceptable
**Use STUN+Signaling when:**
- Building WebRTC application
- Have server infrastructure
- Need browser support
- Can run signaling server
**Use ICE/TURN when:**
- Need 95%+ success rate
- Can pay for TURN servers
- Symmetric NAT support critical
- Browser + native interop needed
**Use MWP when:**
- **Zero infrastructure requirement**
- **True decentralization priority**
- **Building censorship-resistant app**
- **Already have DHT**
- **Privacy important (minimal metadata)**
### 7.2 Application Fit
| Application | Best Solution |
|-------------|---------------|
| Video calling | ICE/TURN |
| WebRTC P2P | STUN+Signaling |
| libp2p apps | DCUtR |
| **Decentralized apps** | **MWP** |
| **Censorship-resistant** | **MWP** |
| **Zero-server P2P** | **MWP** |
| **IoT mesh** | **MWP** |
---
## 8. Migration Path
### 8.1 From STUN+Signaling to MWP
```
Step 1: Add DHT to your stack
Step 2: Implement MWP alongside existing
Step 3: Try MWP first, fall back to STUN
Step 4: Gradually remove STUN dependency
Step 5: Pure MWP (optional)
```
### 8.2 From DCUtR to MWP
```
Step 1: Already have DHT (libp2p includes it)
Step 2: Implement MWP
Step 3: Try MWP first, fall back to DCUtR
Step 4: Keep DCUtR for symmetric NAT fallback
```
### 8.3 Hybrid Approach (Recommended)
```zig
fn connect(target: PeerId) !*Connection {
// 1. Try MWP (no infrastructure needed)
if (mwp.connect(target)) |conn| return conn;
// 2. Fall back to DCUtR (if relays available)
if (dcutr.connect(target)) |conn| return conn;
// 3. Last resort: TURN relay (if configured)
if (turn.connect(target)) |conn| return conn;
return error.AllMethodsFailed;
}
```
---
## 9. Conclusion
### 9.1 Summary Matrix
| Criterion | DCUtR | STUN+Signal | ICE/TURN | **MWP** |
|-----------|-------|-------------|----------|---------|
| No servers | No | No | No | **Yes** |
| Decentralized | Partial | No | No | **Yes** |
| Success rate | 70% | 80% | 95% | 70% |
| Latency | 2s | 1.5s | 2-5s | 1.5s |
| Complexity | Medium | Medium | High | **Low** |
| Battle-tested | Yes | Yes | Yes | No |
| Privacy | Medium | Low | Low | **High** |
### 9.2 Recommendation
**For new decentralized P2P applications:**
1. Implement MWP as primary connection method
2. Add DCUtR fallback for symmetric NAT
3. Consider TURN only if 95%+ success required
**For existing applications:**
1. Add MWP alongside existing solution
2. Use MWP when both peers support it
3. Fall back to existing method otherwise
### 9.3 Future Work
| Enhancement | Impact |
|-------------|--------|
| Symmetric NAT prediction | Higher success rate |
| DHT privacy (onion routing) | Better privacy |
| Multi-path probing | Faster connection |
| Machine learning NAT prediction | Better port guessing |
---
*End of Comparison Document*

View File

@@ -0,0 +1,245 @@
# IP Reflection Performance Analysis
**Status: OPTIMIZED** (Variable-length encoding implemented)
## Implementation (Optimized)
### Wire Format (per DHT response)
```
observed_addr_len: 1 byte
observed_addr: 0-18 bytes (only len bytes transmitted)
--------
Total: 1-19 bytes per response (variable)
```
### Actual Data Usage
| Address Type | IP Size | Port Size | Total Needed | Wire Bytes | Efficiency |
|--------------|---------|-----------|--------------|------------|------------|
| IPv4 | 4 bytes | 2 bytes | 6 bytes | **7** | 86% |
| IPv6 | 16 bytes| 2 bytes | 18 bytes | **19** | 95% |
| None | 0 | 0 | 0 | **1** | 100% |
### Impact on DHT Message Sizes
| Message Type | Base Size | IP Reflection (IPv4) | IP Reflection (None) |
|--------------|-----------|---------------------|---------------------|
| FIND_NODE_RESPONSE | 13 + 79×N nodes | +7 bytes | +1 byte |
| STORE_RESPONSE | 10 bytes | +7 bytes (+70%) | +1 byte (+10%) |
| FIND_VALUE_RESPONSE | 18 + value + 79×N | +7 bytes | +1 byte |
Where N = number of nodes returned (typically 3-20)
---
## Optimization Options
### Option 1: Variable-Length Encoding (Recommended)
**Format:**
```
[len:1][addr:len]
len = 0 → no address (1 byte total)
len = 6 → IPv4 (7 bytes total)
len = 18 → IPv6 (19 bytes total)
```
**Savings:**
- IPv4: 19 → 7 bytes = **12 bytes saved (63%)**
- IPv6: 19 → 19 bytes = 0 saved
- None: 19 → 1 byte = **18 bytes saved (95%)**
**Implementation complexity:** Low
- Change serialization to write `len` first, then only `len` bytes
- Change deserialization to read `len`, then exactly `len` bytes
- Struct stays the same (18-byte buffer + len field)
**Backwards compatibility:** Breaking change (version bump required)
---
### Option 2: Type-Prefixed Compact Format
**Format:**
```
[type:1][data:variable]
type = 0x00 → no address (1 byte total)
type = 0x04 → IPv4 follows (1 + 6 = 7 bytes total)
type = 0x06 → IPv6 follows (1 + 18 = 19 bytes total)
```
**Savings:** Same as Option 1
**Advantages:**
- Explicit type makes parsing clearer
- Easy to extend (e.g., 0x10 for future address types)
**Disadvantages:**
- Slightly more complex parsing logic
---
### Option 3: Bit-Packed Header
**Format:**
```
[flags:1][addr:variable]
flags bit 0: has_addr (0 = no address)
flags bit 1: is_ipv6 (0 = IPv4, 1 = IPv6)
flags bits 2-7: reserved
```
**Savings:**
- IPv4: 1 + 6 = 7 bytes
- IPv6: 1 + 18 = 19 bytes
- None: 1 byte
**Advantages:**
- 6 reserved bits for future flags (NAT type hints, confidence score, etc.)
**Disadvantages:**
- More complex bit manipulation
- Reserved bits may never be used
---
### Option 4: Embed in Existing Fields (Zero-Overhead)
**Concept:** Reuse the first NodeInfo slot in FIND_NODE_RESPONSE to carry the observer's view of the requester.
**Current NodeInfo format:**
```
node_id: 32 bytes
address: 46 bytes
address_len: 1 byte
--------
Total: 79 bytes per node
```
**Modification:** Add a special `node_id` value (all zeros or all ones) to indicate "this is your observed address, not a real node."
**Savings:**
- Complete elimination of the 19-byte overhead
- BUT: Reduces returned node count by 1
**Disadvantages:**
- Semantic overloading is confusing
- Breaks the "NodeInfo is always a real node" invariant
- Complicates client parsing
---
## Implementation (Completed)
**Variable-Length Encoding** was chosen and implemented:
- 12 bytes saved per IPv4 response (63% reduction)
- 18 bytes saved when no address present (95% reduction)
- Minimal implementation complexity
- Clean semantics
### Wire Format
```zig
// Serialization
buffer[offset] = resp.observed_addr_len;
offset += 1;
const addr_len: usize = @min(resp.observed_addr_len, 18);
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], resp.observed_addr[0..addr_len]);
offset += addr_len;
}
// Deserialization
const observed_addr_len = data[offset];
offset += 1;
var observed_addr: [18]u8 = [_]u8{0} ** 18;
if (observed_addr_len > 0 and observed_addr_len <= 18) {
@memcpy(observed_addr[0..observed_addr_len], data[offset..][0..observed_addr_len]);
offset += observed_addr_len;
}
```
---
## Network Impact Analysis
### Typical DHT Session
A peer joining a 1000-node network typically:
- Sends ~10-20 FIND_NODE requests during bootstrap
- Receives ~10-20 FIND_NODE_RESPONSE messages
- Sends periodic STORE requests (1 per minute for presence)
- Receives STORE_RESPONSE for each
**Overhead per session (IPv4, optimized):**
```
Bootstrap: 20 responses × 7 bytes = 140 bytes
Hourly store: 60 responses × 7 bytes = 420 bytes
Daily total: ≈ 10 KB
```
**Comparison with fixed 19-byte format:**
```
Fixed format: 20 responses × 19 bytes = 380 bytes (bootstrap)
Variable: 20 responses × 7 bytes = 140 bytes (bootstrap)
Savings: 63% reduction in IP Reflection overhead
```
### At Scale
For a network of 10,000 active peers with variable-length encoding:
- IPv4 traffic: ~100 MB/day in IP Reflection overhead
- Compared to fixed 19-byte: ~270 MB/day
- **Network-wide savings: ~170 MB/day**
---
## Conclusion
Variable-length encoding has been implemented, providing:
1. **12 bytes saved per IPv4 response** (most common case)
2. **18 bytes saved when no address** (bootstrap/initial responses)
3. **No changes to internal data structures** (still uses 18-byte buffer internally)
4. **Clean wire format** that's easy to document and debug
The implementation is fully tested and backwards-compatible within MWP v1.0.0.
---
## Appendix: Wire Format (Implemented)
### STORE_RESPONSE
**IPv4 (17 bytes total):**
```
[type:1][request_id:8][success:1][len:1=6][addr:6]
```
**IPv6 (29 bytes total):**
```
[type:1][request_id:8][success:1][len:1=18][addr:18]
```
**No address (11 bytes total):**
```
[type:1][request_id:8][success:1][len:1=0]
```
### FIND_NODE_RESPONSE
**With IPv4 (14 + 79×N + 7 bytes):**
```
[type:1][request_id:8][node_count:4][nodes:79×N][len:1=6][addr:6]
```
### FIND_VALUE_RESPONSE
**With IPv4 and value (19 + value_len + 79×N + 7 bytes):**
```
[type:1][request_id:8][found:1][value_len:4][value:V][node_count:4][nodes:79×N][len:1=6][addr:6]
```

146
docs/mwp/README.md Normal file
View File

@@ -0,0 +1,146 @@
# Mutual Witness Protocol (MWP)
**Version:** 1.0.0
**Status:** Implemented
**Created:** February 2026
---
## Overview
The Mutual Witness Protocol (MWP) is a novel NAT traversal and peer discovery protocol that requires **zero external infrastructure** beyond a DHT.
```
┌─────────────────────────────────────────────────────────────┐
│ MUTUAL WITNESS PROTOCOL │
│ │
│ Two parties who know each other's public keys can │
│ establish a direct P2P connection with: │
│ │
│ - No STUN servers │
│ - No relay servers │
│ - No signaling servers │
│ - No beacon chain │
│ - Only DHT (which P2P networks already have) │
│ │
│ Each party contributes randomness and timing. │
│ Neither can cheat. Neither needs to trust third parties. │
└─────────────────────────────────────────────────────────────┘
```
## Key Innovation
Traditional NAT traversal requires:
- **STUN**: External server to discover your public IP
- **Signaling**: Server to exchange connection offers
- **Relay**: Fallback when direct connection fails
MWP eliminates all three by having peers **witness each other**:
1. Both peers publish to a deterministic DHT meeting point
2. Each contributes randomness (nonce) and timing (timestamp)
3. Shared parameters computed from both contributions
4. Simultaneous connection attempt at computed rendezvous time
### Bundled STUN (IP Reflection)
MWP includes a novel **Bundled STUN** mechanism that eliminates STUN servers entirely:
**Unidirectional (Response-based):** Every DHT response includes the requester's observed address.
```
Alice ── DHT_REQUEST ──> DHT Node (src: 192.0.2.1:54321)
Alice <── DHT_RESPONSE ── DHT Node (observed_addr: 192.0.2.1:54321)
```
**Bidirectional (Request-based):** Every DHT request includes the target's observed address.
```
Bob ── DHT_REQUEST ──> Alice (target_observed_addr: 203.0.113.5:18100)
Alice learns her address from Bob's request, even as a pure listener!
```
This solves the "listener problem" where a peer waiting for connections has no one to query.
## Quick Start
```zig
const mwp = @import("mwp");
// Your addresses (discovered via IP Reflection or configured)
const our_addresses = [_]mwp.Address{
mwp.Address.initV4(.{192, 168, 1, 100}, 9000),
};
// Initialize with your DHT, keypair, and addresses
var witness = mwp.MutualWitness.init(allocator, dht, keypair, &our_addresses);
// Connect to peer by their public key
const result = witness.connect(target_pubkey, .{
.timeout_ms = 5000,
});
switch (result) {
.success => |info| std.debug.print("Connected to {}:{}\n", .{info.remote_address}),
.timeout => std.debug.print("Timeout\n", .{}),
.peer_not_found => std.debug.print("Peer not found\n", .{}),
else => std.debug.print("Failed\n", .{}),
}
```
## Protocol Flow
```
Alice DHT Bob
│ │ │
│ 1. meeting_key = hash(sort(A_pk, B_pk)) │
│ │ │
│──────── PUT(key, pub_A) ────>│<──── PUT(key, pub_B) ───────│
│ │ │
│<─────── GET(key) ───────────>│<──────── GET(key) ──────────│
│ returns [pub_A, pub_B] │
│ │ │
│ 2. shared_randomness = hash(sort(nonce_A, nonce_B)) │
│ 3. rendezvous_time = computed from timestamps │
│ │ │
│ 4. Wait until rendezvous_time │
│ │ │
│<──────────── simultaneous connection attempt ──────────────>│
│ │ │
▼ ▼ ▼
CONNECTED (direct P2P)
```
## Comparison
| Metric | DCUtR | STUN+Signaling | **MWP** |
|--------|-------|----------------|---------|
| External servers | 1+ relays | 2 servers | **0** |
| IP discovery | STUN servers | STUN servers | **Bundled in DHT** |
| Latency (typical) | ~2s | ~1-2s | **~1-2s** |
| Centralization | Relay operators | Server operators | **None** |
| Infrastructure | Must run relays | Must run servers | **DHT only** |
## Documentation
- [SPEC.md](./SPEC.md) - Complete protocol specification
- [COMPARISON.md](./COMPARISON.md) - Detailed comparison with existing solutions
- [IP_REFLECTION_PERFORMANCE.md](./IP_REFLECTION_PERFORMANCE.md) - Wire format optimization details
- [../ip-reflection-trust.md](../ip-reflection-trust.md) - Trust model and security analysis
- [src/mwp/](../../src/mwp/) - Implementation
## Use Cases
1. **Truly decentralized P2P** - No external dependencies
2. **Censorship-resistant** - No servers to block
3. **Privacy-focused** - Only DHT sees metadata
4. **Resource-constrained** - Minimal infrastructure
5. **Offline-first** - Works when peers are online, no always-on servers needed
## Limitations
- Requires both peers to know each other's public keys
- Symmetric NAT success rate may be lower than relay-based approaches
- DHT latency affects connection setup time
- Novel/unproven (needs real-world testing)
## License
Same as parent zig-p2p project.

View File

@@ -0,0 +1,164 @@
# Request ID and Replay Protection Design
This document explains the roles of `request_id` and replay protection in the zigp2p protocol, their distinct purposes, and how they work together to provide security.
## Overview
The zigp2p protocol uses a layered replay protection architecture:
1. **Noise AEAD** (primary): Transport-level authentication prevents replay and forgery
2. **Per-peer msg_id dedup**: Application-level dedup keyed by (peer_prefix, msg_id, msg_type)
3. **Wire envelope** (non-DHT messages): Random salt + timestamp prepended to custom messages
4. **Sequence windows** (ordered types): Sliding window for topology_update, data_chunk, etc.
5. **Timestamp validation** (where available): Rejects stale/future messages
---
## Request ID (DHT Layer)
### Purpose
Request IDs are used in the **DHT (Distributed Hash Table) layer** to correlate requests with their responses.
### Location
- Defined in: `src/network/dht.zig`
- Used in: `DhtFindNode`, `DhtStore`, `DhtFindValue`, and their response messages
- Generated by: `DhtCoordinator.getNextRequestId()`
### Characteristics
- **Type**: `u64` (64-bit unsigned integer)
- **Scope**: DHT operations only
- **Generation**: Randomized starting point + monotonic increment
- **Thread-safety**: Atomic operations for concurrent generation
- **Purpose**: Match DHT responses to their originating requests
### Why Randomized Initialization?
Prior to the fix, `request_id` was initialized to 1 and incremented sequentially. When multiple nodes started simultaneously, they would all generate the same sequence (1, 2, 3, ...). With per-peer dedup this is no longer a problem (different peers can reuse msg_ids), but randomization is still good practice to avoid correlation.
---
## Replay Protection (Protocol Layer)
### Purpose
Replay protection prevents attackers from replaying captured messages to cause duplicate processing.
### Location
- Defined in: `src/protocol/replay_protection.zig`
- Checked by: `ReplayProtector.checkMessage()`
- Tracked in: `seen_messages` hash map (keyed by `PeerMessageKey`)
### Architecture: Per-Peer Message ID Dedup
The replay protector uses **per-peer, per-type** dedup. The dedup key is:
```zig
const PeerMessageKey = struct {
peer_id_prefix: [16]u8, // First 16 bytes of 32-byte peer ID
msg_id: u64,
msg_type: u8,
};
```
This means:
- **Same msg_id from different peers**: Accepted (each peer has independent ID space)
- **Same msg_id from same peer, same type**: Rejected as `DuplicateMessageId`
- **Same msg_id from same peer, different type**: Accepted (request/response pairs share IDs)
### checkMessage Signature
```zig
pub fn checkMessage(
self: *ReplayProtector,
msg_id: u64, // Per-peer message identifier
timestamp: i64, // Sender's timestamp (for staleness check)
sequence: u64, // Ordered message sequence (0 = unordered)
peer_id: [32]u8, // Source peer identity
msg_type: u8, // Message type discriminator
) !void
```
### Defense Layers (ordered by check priority)
1. **Timestamp validation**: Rejects messages older than TTL (10s) or further than clock skew (5s) into the future
2. **Per-peer msg_id dedup**: Rejects duplicate (peer_prefix, msg_id, msg_type) tuples
3. **Sequence windows**: For ordered types, rejects out-of-window or replayed sequences
### Why No Global Nonce?
An earlier design tracked nonces globally across all peers (`seen_nonces` HashMap). This was removed because:
- **Cross-peer false positives**: Two different peers sending identical content would collide
- **Redundant with Noise AEAD**: In production, Noise prevents wire-level replay
- **Masked per-peer dedup bugs**: Global nonce caught replays before per-peer dedup, hiding test issues
- **Single point of memory growth**: One HashMap growing with all traffic across all peers
Per-peer dedup is the correct granularity — each peer's ID space is independent.
---
## Wire Envelope (Non-DHT Messages)
Non-DHT, non-file-transfer messages get a 16-byte wire envelope:
```
[app_id:1][salt:8 LE][timestamp:8 LE][payload:N]
```
### Noise ON (Production)
The salt, timestamp, app_id, and payload are hashed together using a **per-session SipHash-2-4 key** derived from the Noise handshake hash. This produces a replay nonce bound to the specific Noise session — an attacker who captures traffic cannot forge envelopes without the session key.
### Noise OFF (Dev/Testing Only)
Without a shared secret, the raw 8-byte salt is used as the replay nonce. This stops passive replay (exact byte replay) but provides no authentication. **Not secure for production.**
---
## MWP Protocol Nonces
The **Mutual Witness Protocol (MWP)** uses a different kind of nonce for **rendezvous coordination**, not replay protection.
- **Type**: `[32]u8` (256-bit random value)
- **Purpose**: Compute shared rendezvous parameters (time, port) between peers
- **Generation**: Cryptographically random per publication
- **Tracking**: Not tracked for replay — serves coordination only
---
## Summary Table
| Aspect | DHT Request ID | Replay Protection | Wire Envelope | MWP Nonce |
|--------|---------------|-------------------|---------------|-----------|
| **Size** | 64 bits | Per-peer msg_id (64 bits) | 128 bits (salt+ts) | 256 bits |
| **Layer** | DHT Application | Protocol | Transport | MWP Application |
| **Purpose** | Request/response correlation | Duplicate detection | Session-bound replay nonce | Rendezvous coordination |
| **Scope** | Per-DHT-node | Per-peer, per-type | Per-session (Noise) | Per-publication |
| **Tracking** | In `pending_responses` | In `seen_messages` | Via `checkMessage` | Not tracked |
---
## Message Path Security Summary
| Message Path | Replay Protection | Timestamp Check | Noise AEAD |
|---|---|---|---|
| DHT (app_id=0x02) | wire_nonce+wire_timestamp → processMessage → per-peer msg_id dedup | Yes (wire_timestamp) | Yes |
| Non-DHT custom (app_id != 0x01/0x02) | wire envelope → handleNetworkMessageImpl → per-peer msg_id dedup | Yes (wire_timestamp) | Yes |
| File transfer (app_id=0x01) | Own piece hashing + session tracking | No | Yes |
| Internal protocol msgs | processMessage → per-peer msg_id dedup + sequence windows | No-op (receiver clock) | Yes |
---
## Related Files
- `src/network/dht.zig` - DHT request ID generation and tracking
- `src/protocol/replay_protection.zig` - Per-peer message dedup and sequence windows
- `src/p2p/messaging.zig` - Wire envelope send/receive, `handleNetworkMessageImpl`
- `src/protocol/handler.zig` - `processMessage` with replay checks
- `src/protocol/message.zig` - `getIdForReplay`, `getTimestamp`, `getSequence`
- `src/protocol/encryption.zig` - Encryption nonce tracking (separate system, orthogonal)
- `src/mwp/types.zig` - MWP nonce for rendezvous coordination

860
docs/mwp/SPEC.md Normal file
View File

@@ -0,0 +1,860 @@
# Mutual Witness Protocol Specification
**Version:** 1.0.0
**Status:** Implemented
**Created:** February 2026
---
## Table of Contents
1. [Introduction](#1-introduction)
2. [Design Goals](#2-design-goals)
3. [Protocol Overview](#3-protocol-overview)
4. [Data Structures](#4-data-structures)
5. [Protocol Flow](#5-protocol-flow)
6. [Algorithms](#6-algorithms)
7. [Edge Cases & Mitigations](#7-edge-cases--mitigations)
8. [Security Considerations](#8-security-considerations)
9. [Comparison with Existing Solutions](#9-comparison-with-existing-solutions)
10. [Implementation Notes](#10-implementation-notes)
---
## 1. Introduction
### 1.1 Problem Statement
Traditional NAT traversal requires external infrastructure:
- **STUN servers**: To discover public IP:port mappings
- **Signaling servers**: To exchange connection offers between peers
- **Relay servers (TURN)**: As fallback when direct connection fails
This creates:
- Centralization points
- Infrastructure costs
- Privacy concerns (servers see connection metadata)
- Potential for censorship
### 1.2 Solution
The Mutual Witness Protocol (MWP) eliminates external infrastructure by having peers **witness each other**:
- Peers meet at a deterministic DHT location computed from their public keys
- Each peer contributes randomness and timing information
- Shared connection parameters are derived from both contributions
- Neither peer can cheat or bias the outcome
- **Bundled STUN**: DHT responses include the requester's observed IP address, eliminating STUN servers
### 1.3 Requirements
MWP requires:
- A functioning DHT (Kademlia or similar)
- Both peers know each other's public keys (Ed25519)
- Both peers online during connection attempt
- Basic clock synchronization (NTP-level, ~100ms accuracy)
---
## 2. Design Goals
| Goal | Description |
|------|-------------|
| Zero Infrastructure | No servers beyond DHT |
| Decentralized | No single points of failure |
| Trustless | Neither peer trusts the other |
| Privacy | Minimal metadata exposure |
| Simplicity | Easy to implement and verify |
| Compatibility | Works with existing P2P stacks |
---
## 3. Protocol Overview
### 3.1 High-Level Flow
```
┌─────────────────────────────────────────────────────────────┐
│ MUTUAL WITNESS PROTOCOL │
│ │
│ Phase 1: Meeting Point Discovery │
│ ├── Both peers compute: key = hash(sort(A_pk, B_pk)) │
│ └── Deterministic, both compute same key │
│ │
│ Phase 2: Publication │
│ ├── Each peer publishes to DHT[key] │
│ └── Publication contains: address, nonce, timestamp, sig │
│ │
│ Phase 3: Discovery │
│ ├── Each peer queries DHT[key] │
│ └── Finds other peer's publication │
│ │
│ Phase 4: Rendezvous Computation │
│ ├── shared_randomness = hash(sort(nonce_A, nonce_B)) │
│ ├── rendezvous_time = derived from timestamps │
│ └── port_hint = derived from randomness │
│ │
│ Phase 5: Connection Attempt │
│ ├── Both wait until rendezvous_time │
│ └── Simultaneous hole punch attempt │
└─────────────────────────────────────────────────────────────┘
```
### 3.2 Key Properties
| Property | Mechanism |
|----------|-----------|
| Unbiasable randomness | Hash of both nonces (neither controls output) |
| Synchronized timing | Derived from publication timestamps |
| Mutual authentication | Signatures verify peer identity |
| NAT traversal | Simultaneous connection attempts |
| IP discovery | Bundled STUN - DHT responses include observed address |
---
## 4. Data Structures
### 4.1 Meeting Publication
The core data structure published to the DHT:
```
MeetingPublication {
// Identity (32 bytes)
peer_id: [32]u8 // Ed25519 public key
// Connection addresses (variable)
addresses: []Address // Multiple addresses for fallback
// Mutual witness data
nonce: [32]u8 // Cryptographically random
timestamp: i64 // Milliseconds since Unix epoch
// Validity control
ttl: u32 // Seconds until expiry
sequence: u64 // Monotonic, for updates
// Authentication (64 bytes)
signature: [64]u8 // Ed25519 signature over all above
}
```
**Wire format (binary):**
```
+--------+--------+--------+--------+--------+--------+--------+--------+
| 0x01 | peer_id (32 bytes) |
+--------+--------+--------+--------+--------+--------+--------+--------+
| addr_count (1 byte) | addresses (variable) |
+--------+--------+--------+--------+--------+--------+--------+--------+
| nonce (32 bytes) |
+--------+--------+--------+--------+--------+--------+--------+--------+
| timestamp (8 bytes, big-endian) |
+--------+--------+--------+--------+--------+--------+--------+--------+
| ttl (4 bytes) | sequence (8 bytes) |
+--------+--------+--------+--------+--------+--------+--------+--------+
| signature (64 bytes) |
+--------+--------+--------+--------+--------+--------+--------+--------+
```
### 4.2 Address Format
```
Address {
type: AddressType // IPv4, IPv6, DNS
ip: [4]u8 or [16]u8 // IP address bytes
port: u16 // Port number
}
```
### 4.3 Rendezvous Parameters
Computed locally by each peer (not transmitted):
```
RendezvousParams {
shared_randomness: [32]u8 // hash(sort(nonce_A, nonce_B))
rendezvous_time: i64 // Computed from timestamps
port_hint: u16 // Derived from randomness
connection_id: [16]u8 // Unique per attempt
}
```
### 4.4 Hole Punch Packet
Initial packet sent during hole punch:
```
HolePunchPacket {
magic: [4]u8 // "MWP1"
connection_id: [16]u8 // From RendezvousParams
sender_id: [32]u8 // Sender's public key
timestamp: i64 // Send time
signature: [64]u8 // Signs above fields
}
```
---
## 5. Protocol Flow
### 5.1 Initiator Flow (Alice wants to connect to Bob)
```
Alice Bob
│ │
│ 1. COMPUTE MEETING KEY │
│ key = hash("mwp-v1" || sort(A_pk, B_pk)) │
│ │
│ 2. CREATE PUBLICATION │
│ pub_A = { │
│ peer_id: A_pk, │
│ addresses: [addr1, addr2, ...], │
│ nonce: random_bytes(32), │
│ timestamp: now_ms(), │
│ ttl: 300, │
│ sequence: next_seq++, │
│ signature: sign(above) │
│ } │
│ │
│ 3. PUBLISH TO DHT │
│────────────── DHT.PUT(key, pub_A) ──────────────────>│
│ │
│ 4. POLL FOR PEER'S PUBLICATION │
│<───────────── DHT.GET(key) ─────────────────────────>│
│ │
│ (wait until pub_B found or timeout) │
│ │
│ 5. VERIFY PEER'S PUBLICATION │
│ - Check signature matches B_pk │
│ - Check not expired │
│ - Extract addresses, nonce, timestamp │
│ │
│ 6. COMPUTE RENDEZVOUS PARAMETERS │
│ shared_random = hash(sort(nonce_A, nonce_B)) │
│ rendezvous_time = see algorithm │
│ port_hint = shared_random[0:2] mod 16384 + 49152 │
│ │
│ 7. WAIT UNTIL RENDEZVOUS TIME │
│ sleep(rendezvous_time - now()) │
│ │
│ 8. ATTEMPT CONNECTION │
│<═══════════════ simultaneous hole punch ═════════════>│
│ │
│ 9. HANDSHAKE (Noise Protocol) │
│<═══════════════════ encrypted channel ═══════════════>│
```
### 5.2 Responder Flow (Bob)
Bob follows the identical flow. The protocol is symmetric - there is no distinguished initiator or responder at the MWP layer.
### 5.3 Timing Diagram
```
Time
│
│ T=0 Alice publishes to DHT
│ T=50ms Bob publishes to DHT
│ T=100ms Alice sees Bob's publication
│ T=150ms Bob sees Alice's publication
│
│ Both compute rendezvous_time = max(0, 50) + 500 = 550
│
│ T=550ms Alice sends hole punch
│ T=550ms Bob sends hole punch
│
│ T=560ms Packets cross NATs
│ T=600ms Connection established
▼
```
---
## 6. Algorithms
### 6.1 Meeting Key Computation
```python
def compute_meeting_key(our_pk: bytes, their_pk: bytes) -> bytes:
# Deterministic ordering
if our_pk < their_pk:
combined = our_pk + their_pk
else:
combined = their_pk + our_pk
# Include version for future compatibility
return blake2b(b"mwp-v1" + combined, digest_size=32)
```
### 6.2 Rendezvous Time Computation
```python
def compute_rendezvous_time(
our_pub: Publication,
their_pub: Publication,
our_seen_time: int, # When we first saw their publication
) -> int:
# Option 1: Absolute time based
# (Simpler but sensitive to clock skew)
base_time = max(our_pub.timestamp, their_pub.timestamp)
return base_time + 500 # 500ms buffer
# Option 2: Relative time based (recommended)
# (More robust to clock skew)
return our_seen_time + 500 # 500ms after seeing peer
```
### 6.3 Shared Randomness Computation
```python
def compute_shared_randomness(nonce_a: bytes, nonce_b: bytes) -> bytes:
# Deterministic ordering
if nonce_a < nonce_b:
combined = nonce_a + nonce_b
else:
combined = nonce_b + nonce_a
return blake2b(combined, digest_size=32)
```
### 6.4 Port Hint Derivation
```python
def derive_port_hint(shared_randomness: bytes) -> int:
# Use first 2 bytes of randomness
offset = int.from_bytes(shared_randomness[0:2], 'little')
# Map to ephemeral port range (49152-65535)
return 49152 + (offset % 16384)
```
### 6.5 Address Gathering
```python
def gather_addresses() -> List[Address]:
addresses = []
# 1. Local bound address
addresses.append(get_local_address())
# 2. DHT-observed external address (Bundled STUN)
# Every DHT response includes the requester's observed IP:port
if dht_observed := get_dht_observed_address():
addresses.append(dht_observed)
# 3. Previously observed external addresses
# (From successful past connections)
addresses.extend(get_observed_addresses())
# 4. Predicted addresses
# (From NAT behavior learning)
if predicted := nat_predictor.predict():
addresses.append(predicted)
# 5. UPnP-mapped address (if available)
if upnp_addr := get_upnp_address():
addresses.append(upnp_addr)
return addresses
```
### 6.6 Bundled STUN (IP Reflection)
MWP eliminates the need for external STUN servers through **IP Reflection**:
```
┌─────────────────────────────────────────────────────────────┐
│ BUNDLED STUN │
│ │
│ UNIDIRECTIONAL (Response-based): │
│ Every DHT response includes the requester's observed │
│ source address. │
│ │
│ Alice ──── DHT_REQUEST ───────────────> DHT Node │
│ src: 192.0.2.1:54321 │
│ │
│ Alice <─── DHT_RESPONSE ─────────────── DHT Node │
│ observed_addr: 192.0.2.1:54321 │
│ │
│ BIDIRECTIONAL (Request-based): │
│ Every DHT request includes the target's observed address. │
│ This solves the "listener problem". │
│ │
│ Bob ──── DHT_REQUEST ────────────────> Alice │
│ target_observed_addr: 203.0.113.5:18100 │
│ │
│ Alice learns her address from Bob's request! │
│ No need to query anyone - just receive requests. │
└─────────────────────────────────────────────────────────────┘
```
**Wire Format (Response - Unidirectional):**
Each DHT response (FIND_NODE_RESPONSE, STORE_RESPONSE, FIND_VALUE_RESPONSE)
includes the requester's observed address:
```
+--------+--------+--------+
| addr_len (1 byte) | observed_addr (0-18 bytes, variable) |
+--------+--------+--------+
IPv4: addr_len=6, then 4 bytes IP + 2 bytes port
IPv6: addr_len=18, then 16 bytes IP + 2 bytes port
None: addr_len=0 (no address data follows)
```
**Wire Format (Request - Bidirectional):**
Each DHT request (FIND_NODE, STORE, FIND_VALUE) includes the target's
observed address:
```
+--------+--------+--------+
| target_addr_len (1 byte) | target_observed_addr (0-18 bytes) |
+--------+--------+--------+
Same encoding as response observed_addr.
```
This bidirectional approach ensures that listeners (who never send requests)
can still discover their public address from incoming requests.
**Benefits:**
| Aspect | Traditional STUN | Bundled STUN |
|--------|------------------|--------------|
| Extra servers | Required | None |
| Extra round trips | 1-2 | 0 |
| Infrastructure | Must maintain STUN servers | DHT already exists |
| Availability | STUN server must be up | Works if any DHT node responds |
| Privacy | STUN server sees your IP | DHT nodes already see your IP |
**Implementation:**
```python
# DHT response handler (server side)
def handle_dht_request(request, source_addr):
response = process_request(request)
# Bundled STUN: include requester's observed address
response.observed_addr = source_addr.ip
response.observed_addr_port = source_addr.port
return response
# MWP address gathering (client side)
def on_dht_response(response):
if response.observed_addr_len > 0:
# We learned our public IP from the DHT response!
my_public_addr = parse_observed_addr(response)
address_cache.update(my_public_addr)
```
### 6.7 IP Reflection Trust Model
IP Reflection provides address discovery, not security. Applications should
understand the trust implications:
| Observers | Confidence | Meaning |
|-----------|------------|---------|
| 0 | `none` | No address discovered yet |
| 1 | `single_source` | One peer reported; likely correct but unverified |
| 2+ agree | `consensus` | Multiple peers agree; high confidence |
| 2+ disagree | `conflict` | Peers disagree; using majority |
**API Usage:**
```zig
const result = p2p_node.getConsensusAddress();
switch (result.confidence) {
.none => // Wait for peers
.single_source => // Works but unverified
.consensus => // High confidence
.conflict => // Investigate or use fallback
}
```
**Important:** IP Reflection only answers "what address should I advertise?"
The Noise protocol handshake provides the actual security - cryptographic
proof of identity. Even with a wrong address, an attacker cannot impersonate
a peer without their private key.
See [IP Reflection Trust Model](../ip-reflection-trust.md) for detailed
security analysis and application guidance.
---
## 7. Edge Cases & Mitigations
### 7.1 Clock Skew
**Problem:** Alice's clock is 5 seconds ahead of Bob's.
```
Alice publishes: timestamp = 1000
Bob publishes: timestamp = 995 (his clock is behind)
Absolute method:
rendezvous = max(1000, 995) + 500 = 1500
Alice waits until 1500 on her clock (500ms)
Bob waits until 1500 on his clock (505ms + 5s skew = 5.5s)
They're 5 seconds apart!
```
**Solution:** Use relative timing.
```python
def compute_rendezvous_relative(seen_time: int) -> int:
# Wait 500ms after seeing peer's publication
# This is clock-independent
return seen_time + 500
```
### 7.2 DHT Latency Asymmetry
**Problem:** Alice's DHT responds in 50ms, Bob's in 500ms.
**Solution:** Multiple retry attempts with increasing delays.
```python
def attempt_with_retries(params: RendezvousParams):
retry_intervals = [0, 500, 1000, 2000]
for delay in retry_intervals:
sleep(delay)
if try_connection(params):
return SUCCESS
return FAILURE
```
### 7.3 Meeting Point Squatting
**Problem:** Attacker knows Alice and Bob's public keys, pre-computes meeting key, and publishes garbage.
**Solutions:**
1. **Signature verification** (implemented)
- Publications signed by peer's key
- Attacker can't forge signatures
2. **Mutual authentication** (at handshake layer)
- Noise protocol verifies both sides
- Even if wrong address, handshake fails
3. **Session salt** (optional)
- `key = hash(A_pk || B_pk || session_secret)`
- Requires out-of-band secret sharing
### 7.4 Address Change After Publishing
**Problem:** NAT remaps our address after we publish.
**Solution:** Monitor and republish.
```python
def address_monitor_loop():
while True:
current = detect_current_address()
if current != published_address:
republish_with_new_address(current)
sleep(5000) # Check every 5 seconds
```
### 7.5 One Peer Offline
**Problem:** Alice publishes, Bob is offline.
**Solution:** Long TTL + notification mechanism.
```python
# Alice's publication has 1-hour TTL
pub.ttl = 3600
# When Bob comes online and publishes:
# 1. Bob sees Alice's old publication
# 2. Bob's publication triggers DHT notification
# 3. Alice (if online) sees notification, refreshes
# 4. Connection proceeds
```
### 7.6 Simultaneous Publish Race
**Problem:** Alice and Bob publish at exact same moment.
**Solution:** Not a problem - both publications coexist at meeting point, both peers will find both.
### 7.7 NAT Mapping Timeout
**Problem:** NAT mapping expires before peer's packet arrives.
**Solution:** Send keepalive packets during wait period.
```python
def wait_with_keepalive(rendezvous_time: int, target: Address):
while now() < rendezvous_time:
# Send STUN-like binding to keep NAT mapping alive
send_keepalive(target)
sleep(10000) # Every 10 seconds
```
---
## 8. Security Considerations
### 8.1 Threat Model
| Threat | Mitigation |
|--------|------------|
| Attacker intercepts DHT | Publications are signed |
| Attacker modifies publication | Signature verification fails |
| Attacker replays old publication | Timestamp + sequence number |
| Attacker discovers meeting point | Can DoS but not impersonate |
| MITM on connection | Noise handshake authenticates |
### 8.2 Privacy Considerations
| Data | Exposure |
|------|----------|
| Public keys | DHT nodes see meeting key (hash) |
| IP addresses | DHT nodes see publication content |
| Connection timing | DHT nodes see access patterns |
| Connection content | E2E encrypted (not visible) |
**Privacy improvement options:**
1. Encrypt publication body to recipient's key
2. Use onion routing to access DHT
3. Pad publications to fixed size
### 8.3 DoS Resistance
| Attack | Impact | Mitigation |
|--------|--------|------------|
| Flood meeting point | Publication lookup slower | DHT rate limiting |
| Exhaust DHT storage | Peer can't publish | TTL expiry, proof-of-work |
| Block DHT access | Can't find peer | Multiple DHT entry points |
---
## 9. Comparison with Existing Solutions
### 9.1 vs DCUtR (libp2p)
```
DCUtR:
Alice ──── Relay ──── Bob
1. Alice connects to Relay
2. Bob connects to Relay
3. Exchange addresses via Relay
4. Relay measures RTT
5. Relay coordinates timing
6. Hole punch attempt
MWP:
Alice ──── DHT ──── Bob
1. Alice publishes to DHT
2. Bob publishes to DHT
3. Both find each other
4. Compute timing from publications
5. Hole punch attempt
Difference: No relay needed for coordination
```
| Aspect | DCUtR | MWP |
|--------|-------|-----|
| Infrastructure | Relay nodes | DHT only |
| RTT measurement | Yes (via relay) | No (relative timing) |
| Works if relay down | No | Yes (no relay) |
| Latency | ~2s | ~1-2s |
| Success rate | ~70% | ~70% (estimated) |
| Maturity | Battle-tested | Novel |
### 9.2 vs STUN + Signaling
```
STUN + Signaling:
1. Alice queries STUN → learns public IP
2. Bob queries STUN → learns public IP
3. Alice sends offer to Signaling Server
4. Bob receives offer from Server
5. Bob sends answer via Server
6. Both attempt connection
MWP (with Bundled STUN):
1. Alice queries DHT → learns public IP from response (bundled STUN)
2. Bob queries DHT → learns public IP from response (bundled STUN)
3. Alice publishes to DHT (includes addresses)
4. Bob publishes to DHT (includes addresses)
5. Both find each other in DHT
6. Both attempt connection
Difference: No STUN (bundled into DHT responses), no signaling (DHT is signaling)
```
| Aspect | STUN+Signaling | MWP |
|--------|----------------|-----|
| Servers needed | 2 (STUN + Signal) | 0 |
| Address discovery | STUN server | Self/peer observation |
| Signaling | Dedicated server | DHT |
| ICE framework | Yes | No (simpler) |
| Browser support | WebRTC | Requires native |
### 9.3 Message Count Comparison
| Protocol | Control Messages | Round Trips |
|----------|------------------|-------------|
| DCUtR | 6 (via relay) | 3 |
| STUN+Signaling | 6 (2 STUN + 4 signal) | 2-3 |
| **MWP** | **4 (2 PUT + 2 GET)** | **1-2** |
### 9.4 Failure Mode Comparison
| Failure | DCUtR | STUN+Signal | MWP |
|---------|-------|-------------|-----|
| Relay offline | Fatal | N/A | N/A |
| STUN offline | N/A | Fatal | N/A |
| Signaling offline | N/A | Fatal | N/A |
| DHT degraded | Works (relay) | Works | Slower |
| Symmetric NAT | Relay fallback | TURN needed | May fail |
---
## 10. Implementation Notes
### 10.1 Recommended Parameters
| Parameter | Value | Rationale |
|-----------|-------|-----------|
| Meeting key hash | BLAKE2b-256 | Fast, secure |
| Nonce size | 32 bytes | 256-bit security |
| Signature | Ed25519 | Fast, compact |
| Default TTL | 300 seconds | 5 minute window |
| Rendezvous buffer | 500ms | Allows for DHT latency |
| Retry count | 4 | [0, 500, 1000, 2000]ms |
| Hole punch timeout | 2000ms | Per attempt |
### 10.2 DHT Requirements
MWP requires the following DHT operations:
- `PUT(key, value)` - Store publication
- `GET(key) -> []value` - Retrieve all publications at key
- Optional: `SUBSCRIBE(key)` - Notify on changes
Compatible DHT implementations:
- Kademlia
- Chord
- S/Kademlia
- libp2p DHT
### 10.3 Integration Points
```
┌─────────────────────────────────────────────────────────────┐
│ APPLICATION │
├─────────────────────────────────────────────────────────────┤
│ MWP LAYER │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Meeting │ │ Rendezvous │ │ Hole Punch │ │
│ │ Point │ │ Computation │ │ Engine │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ DHT LAYER │
├─────────────────────────────────────────────────────────────┤
│ TRANSPORT (UDP) │
└─────────────────────────────────────────────────────────────┘
```
### 10.4 File Structure
```
mwp/
├── README.md # Overview
├── SPEC.md # This specification
├── COMPARISON.md # Detailed comparisons
└── src/
├── mutual_witness.zig # Main API
├── types.zig # Data structures
├── meeting_point.zig # DHT meeting point logic
├── publication.zig # Publication create/verify
├── rendezvous.zig # Parameter computation
├── hole_punch.zig # Connection attempts
└── tests.zig # Unit tests
```
---
## Appendix A: Wire Format Details
### A.1 Publication Serialization
```
Byte offset | Size | Field
------------|------|------
0 | 1 | Version (0x01)
1 | 32 | peer_id
33 | 1 | address_count
34 | var | addresses (6 bytes each for IPv4)
var | 32 | nonce
var+32 | 8 | timestamp (big-endian)
var+40 | 4 | ttl (big-endian)
var+44 | 8 | sequence (big-endian)
var+52 | 64 | signature
```
### A.2 Hole Punch Packet
```
Byte offset | Size | Field
------------|------|------
0 | 4 | magic ("MWP1")
4 | 16 | connection_id
20 | 32 | sender_id
52 | 8 | timestamp
60 | 64 | signature
```
---
## Appendix B: Example Trace
```
[T=0ms] Alice: Computing meeting key for Bob (pubkey=0xABC...)
[T=0ms] Alice: meeting_key = 0xDEF...
[T=1ms] Alice: Creating publication
[T=1ms] Alice: nonce = 0x111... (random)
[T=1ms] Alice: timestamp = 1707350400000
[T=2ms] Alice: Publishing to DHT at 0xDEF...
[T=52ms] Alice: DHT PUT complete
[T=100ms] Alice: Querying DHT for peer publications
[T=150ms] Alice: Found Bob's publication
[T=150ms] Alice: Bob's nonce = 0x222...
[T=150ms] Alice: Bob's timestamp = 1707350400050
[T=150ms] Alice: Computing rendezvous
[T=150ms] Alice: shared_randomness = hash(0x111..., 0x222...) = 0x333...
[T=150ms] Alice: rendezvous_time = 1707350400650 (seen_time + 500ms)
[T=150ms] Alice: port_hint = 52481
[T=150ms] Alice: Waiting 500ms until rendezvous...
[T=650ms] Alice: Sending hole punch to Bob's addresses
[T=650ms] Alice: -> 192.0.2.1:9000
[T=650ms] Alice: -> 192.0.2.1:52481 (port hint)
[T=660ms] Alice: Received hole punch from Bob
[T=660ms] Alice: Connection established!
[T=661ms] Alice: Starting Noise handshake...
[T=700ms] Alice: Secure channel established
```
---
*End of Specification*

Binary file not shown.

View File

@@ -28,7 +28,7 @@ pub fn main() !void {
// Run benchmarks
try benchmarkAddressParsing(iterations);
try benchmarkBufferOperations(allocator, iterations, buffer_size);
try benchmarkBufferOperations(allocator, 500, buffer_size); // Stay under BufferManager rate limit (1000/s)
try benchmarkSocketCreation(allocator, iterations);
try benchmarkConnectionCreation(allocator, iterations);
try benchmarkAddressConversion(allocator, iterations);

363
examples/bootstrap_node.zig Normal file
View File

@@ -0,0 +1,363 @@
//! Headless Bootstrap / MWP Peer Node
//!
//! Can act as a DHT bootstrap relay OR as a peer that discovers and connects
//! via MWP hole punching. No TUI — just stdout logging.
//!
//! Bootstrap mode:
//! bootstrap-node --port 19000
//!
//! Peer mode (connects via MWP):
//! bootstrap-node --port 19001 --name alice --bootstrap VPS:19000 --mwp-connect bob
const std = @import("std");
const p2p_lib = @import("p2p");
const core = @import("core");
const network = @import("network");
const mwp_mod = @import("mwp");
const P2P = p2p_lib.P2P;
const P2PConfig = p2p_lib.P2PConfig;
const coreAddress = core.Address;
const APP_ID_DHT_EXCHANGE: u8 = 0x30;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
var port: u16 = 19000;
var bootstrap_addr: ?[]const u8 = null;
var name: []const u8 = "bootstrap";
var mwp_target_name: ?[]const u8 = null;
var i: usize = 1;
while (i < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--port") and i + 1 < args.len) {
i += 1;
port = std.fmt.parseInt(u16, args[i], 10) catch {
std.debug.print("Invalid port\n", .{});
return;
};
} else if (std.mem.eql(u8, args[i], "--bootstrap") and i + 1 < args.len) {
i += 1;
bootstrap_addr = args[i];
} else if (std.mem.eql(u8, args[i], "--name") and i + 1 < args.len) {
i += 1;
name = args[i];
} else if (std.mem.eql(u8, args[i], "--mwp-connect") and i + 1 < args.len) {
i += 1;
mwp_target_name = args[i];
} else if (std.mem.eql(u8, args[i], "--help") or std.mem.eql(u8, args[i], "-h")) {
std.debug.print(
\\Bootstrap / MWP Peer Node — Headless DHT/MWP for zig-p2p
\\
\\Usage: bootstrap-node [OPTIONS]
\\
\\Options:
\\ --port PORT Listen port (default: 19000)
\\ --name NAME Peer name for MWP keypair (default: bootstrap)
\\ --bootstrap HOST:PORT Connect to bootstrap node
\\ --mwp-connect NAME Target peer name for MWP discovery
\\
, .{});
return;
}
}
// P2P init
var config = P2PConfig.default();
config.network.listen_port = 0; // UDP on ephemeral port
config.network.enable_noise_encryption = true;
var p2p = try P2P.init(allocator, config);
defer p2p.deinit();
try p2p.start();
const listen_addr = coreAddress.ipv4(.{ 0, 0, 0, 0 }, port);
try p2p.startListening(listen_addr);
std.debug.print("bootstrap listening on :{d} (name={s})\n", .{ port, name });
// Connect to another bootstrap if specified
if (bootstrap_addr) |addr| {
if (parseHostPort(addr)) |hp| {
const boot_addr = coreAddress.ipv4(hp.host, hp.port);
std.debug.print("connecting to {s}...\n", .{addr});
if (p2p.connectToPeer(boot_addr)) |cpid| {
if (p2p.getDhtLocalId()) |our_id| {
_ = p2p.sendMessage(cpid, APP_ID_DHT_EXCHANGE, &our_id) catch {};
}
// Wait for DHT exchange
var got_it = false;
for (0..60) |_| {
p2p.update() catch {};
while (p2p.getNextEvent()) |ev| {
var event = ev;
defer event.deinit();
switch (event.data) {
.message_received => |msg| {
if (msg.message_type == APP_ID_DHT_EXCHANGE and msg.data.len == 32) {
var remote_id: [32]u8 = undefined;
@memcpy(&remote_id, msg.data[0..32]);
p2p.registerDhtNodeId(remote_id, msg.source) catch {};
p2p.dhtAddPeer(remote_id, boot_addr) catch {};
got_it = true;
}
},
else => {},
}
}
if (got_it) break;
std.Thread.sleep(50 * std.time.ns_per_ms);
}
// Trigger IP Reflection via DHT lookup
if (got_it) {
std.debug.print("connected + DHT exchange OK, triggering IP reflection\n", .{});
const dummy_key: [32]u8 = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ++ [_]u8{0} ** 28;
_ = p2p.dhtFindValue(dummy_key) catch {};
for (0..30) |_| {
p2p.update() catch {};
std.Thread.sleep(50 * std.time.ns_per_ms);
}
} else {
std.debug.print("connected but no DHT exchange\n", .{});
}
} else |err| {
std.debug.print("connection failed: {}\n", .{err});
}
}
}
// Initialize MWP if --mwp-connect is set
var mwp_node: ?*mwp_mod.MWP = null;
var mwp_target_pubkey: ?[32]u8 = null;
const mwp_port: u16 = if (port > 0) port + 1 else 9001;
var mwp_addrs: [1]mwp_mod.Address = .{mwp_mod.Address.initV4(.{ 127, 0, 0, 1 }, mwp_port)};
defer if (mwp_node) |m| m.deinit();
if (mwp_target_name != null or bootstrap_addr != null) {
const keypair = deterministicKeypair(name);
if (mwp_target_name) |target_name| {
const target_kp = deterministicKeypair(target_name);
mwp_target_pubkey = target_kp.public;
}
// Try to get observed public address from IP Reflection
if (p2p.getObservedPublicAddress()) |observed| {
switch (observed.ip) {
.v4 => |ip| {
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
std.debug.print("MWP: Using IP Reflection address {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], mwp_port });
},
.v6 => {},
}
} else {
std.debug.print("MWP: No public address yet, using 127.0.0.1:{d}\n", .{mwp_port});
}
mwp_node = mwp_mod.MWP.init(allocator, &p2p, .{
.keypair = keypair,
.addresses = &mwp_addrs,
}) catch |err| blk: {
std.debug.print("MWP init failed: {s}\n", .{@errorName(err)});
break :blk null;
};
if (mwp_node != null) {
var pk_hex: [64]u8 = undefined;
_ = formatHex(&keypair.public, &pk_hex);
std.debug.print("MWP initialized, pubkey: {s}\n", .{pk_hex});
}
}
// MWP state machine
const MwpState = enum { idle, published, searching, done };
var mwp_state: MwpState = .idle;
var mwp_publication: ?mwp_mod.MeetingPublication = null;
var mwp_last_search: i64 = 0;
var peer_count: usize = 0;
// Main loop
while (true) {
p2p.update() catch {};
while (p2p.getNextEvent()) |ev| {
var event = ev;
defer event.deinit();
switch (event.data) {
.peer_connected => |pc| {
peer_count += 1;
if (p2p.getDhtLocalId()) |our_id| {
_ = p2p.sendMessage(pc.peer_id, APP_ID_DHT_EXCHANGE, &our_id) catch {};
}
std.debug.print("[+] peer connected (total: {d})\n", .{peer_count});
},
.connection_established => |ce| {
peer_count += 1;
if (p2p.getDhtLocalId()) |our_id| {
_ = p2p.sendMessage(ce.peer_id, APP_ID_DHT_EXCHANGE, &our_id) catch {};
}
std.debug.print("[+] peer connected outbound (total: {d})\n", .{peer_count});
},
.message_received => |msg| {
if (msg.message_type == APP_ID_DHT_EXCHANGE and msg.data.len == 32) {
var remote_id: [32]u8 = undefined;
@memcpy(&remote_id, msg.data[0..32]);
p2p.registerDhtNodeId(remote_id, msg.source) catch {};
std.debug.print("[dht] registered peer\n", .{});
}
},
.peer_disconnected => |pd| {
if (peer_count > 0) peer_count -= 1;
std.debug.print("[-] peer disconnected: {s} (total: {d})\n", .{ pd.reason, peer_count });
},
else => {},
}
}
// MWP peer discovery state machine
if (mwp_node) |m| {
if (mwp_target_pubkey) |target_pk| {
const now = std.time.milliTimestamp();
switch (mwp_state) {
.idle => {
// Update MWP address from IP Reflection before publishing
if (p2p.getObservedPublicAddress()) |observed| {
switch (observed.ip) {
.v4 => |ip| {
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
std.debug.print("MWP: Updated address to {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], mwp_port });
},
.v6 => {},
}
}
// Publish our availability
if (m.publishFor(target_pk, 300)) |pub_data| {
mwp_publication = pub_data;
mwp_state = .published;
std.debug.print("MWP: Published availability, searching for peer...\n", .{});
} else |err| {
std.debug.print("MWP: Failed to publish: {s}\n", .{@errorName(err)});
}
},
.published, .searching => {
mwp_state = .searching;
if (now - mwp_last_search >= 2000) {
mwp_last_search = now;
if (m.findPeer(target_pk) catch null) |peer_pub| {
std.debug.print("MWP: Found peer! Attempting hole punch...\n", .{});
const result = m.connectWithPublication(
mwp_publication.?,
peer_pub,
.{ .timeout_ms = 10_000 },
);
var pub_copy = peer_pub;
pub_copy.deinit(allocator);
switch (result) {
.success => |info| {
const remote = coreAddress.ipv4(
info.remote_address.ip.v4,
info.remote_address.port,
);
std.debug.print("MWP: Hole punch OK! Connecting to {d}.{d}.{d}.{d}:{d}\n", .{
info.remote_address.ip.v4[0],
info.remote_address.ip.v4[1],
info.remote_address.ip.v4[2],
info.remote_address.ip.v4[3],
info.remote_address.port,
});
p2p.startNonBlockingConnect(remote) catch {};
mwp_state = .done;
},
.timeout => {
std.debug.print("MWP: Hole punch timeout, retrying...\n", .{});
if (m.publishFor(target_pk, 300)) |new_pub| {
mwp_publication = new_pub;
mwp_state = .published;
} else |_| {}
},
.hole_punch_failed => |err| {
std.debug.print("MWP: Hole punch failed: {s}\n", .{@tagName(err)});
},
.peer_not_found => {
std.debug.print("MWP: Peer not found\n", .{});
},
.other_error => |err| {
std.debug.print("MWP: Error: {s}\n", .{@errorName(err)});
},
}
}
}
},
.done => {},
}
}
}
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
fn deterministicKeypair(seed: []const u8) mwp_mod.KeyPair {
var seed_hash: [32]u8 = undefined;
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
hasher.update("mwp-test-keypair-v1");
hasher.update(seed);
hasher.final(&seed_hash);
const kp = std.crypto.sign.Ed25519.KeyPair.generateDeterministic(seed_hash) catch unreachable;
return .{
.public = kp.public_key.toBytes(),
.secret = kp.secret_key.toBytes(),
};
}
fn formatHex(bytes: []const u8, buf: []u8) []u8 {
const charset = "0123456789abcdef";
for (bytes, 0..) |b, idx| {
buf[idx * 2] = charset[b >> 4];
buf[idx * 2 + 1] = charset[b & 0x0f];
}
return buf[0 .. bytes.len * 2];
}
fn parseHostPort(s: []const u8) ?struct { host: [4]u8, port: u16 } {
const colon_idx = std.mem.lastIndexOfScalar(u8, s, ':') orelse return null;
const host_str = s[0..colon_idx];
const port_str = s[colon_idx + 1 ..];
const port = std.fmt.parseInt(u16, port_str, 10) catch return null;
// Try IPv4 dotted notation first
var parts: [4]u8 = undefined;
var iter = std.mem.splitScalar(u8, host_str, '.');
var idx: usize = 0;
var is_ip = true;
while (iter.next()) |part| {
if (idx >= 4) { is_ip = false; break; }
parts[idx] = std.fmt.parseInt(u8, part, 10) catch { is_ip = false; break; };
idx += 1;
}
if (is_ip and idx == 4) return .{ .host = parts, .port = port };
// Fall back to DNS resolution
var gpa_alloc = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_alloc.deinit();
const list = std.net.getAddressList(gpa_alloc.allocator(), host_str, port) catch return null;
defer list.deinit();
for (list.addrs) |addr| {
if (addr.any.family == std.posix.AF.INET) {
const bytes = @as(*const [4]u8, @ptrCast(&addr.in.sa.addr));
return .{ .host = bytes.*, .port = port };
}
}
return null;
}

View File

@@ -156,6 +156,7 @@ pub fn main() !void {
resume_file,
total_size,
piece_size,
null,
.rarest_first,
);

View File

@@ -123,6 +123,7 @@ pub fn main() !void {
const port = base_port + @as(u16, @intCast(i));
var config = P2PConfig.default();
config.network.listen_port = port;
config.network.enable_noise_encryption = false;
config.protocol.enable_encryption = false;
config.events.enable_logging = false;
config.file_sharing.piece_size = PIECE_SIZE;

View File

@@ -85,6 +85,7 @@ fn initPeerThread(ctx: *PeerInitContext) void {
var config = p2p_lib.P2PConfig.default();
config.network.listen_port = peer_port;
config.network.enable_noise_encryption = false;
config.events.enable_logging = false;
config.file_sharing.max_concurrent_uploads = 64;
config.file_sharing.piece_size = PIECE_SIZE;
@@ -346,6 +347,7 @@ pub fn main() !void {
var client_config = p2p_lib.P2PConfig.default();
client_config.network.listen_port = client_port;
client_config.network.enable_noise_encryption = false;
client_config.events.enable_logging = false;
client_config.file_sharing.max_concurrent_downloads = 512;
client_config.file_sharing.piece_size = PIECE_SIZE;

555
examples/mwp_demo.zig Normal file
View File

@@ -0,0 +1,555 @@
//! MWP (Mutual Witness Protocol) Demo
//!
//! Demonstrates NAT traversal and peer discovery using MWP with zig-p2p's DHT.
//!
//! Usage:
//! # Terminal 1 (Alice - starts network):
//! zig-out/bin/mwp-demo --name alice --port 9000
//!
//! # Terminal 2 (Bob - joins and connects to Alice):
//! zig-out/bin/mwp-demo --name bob --port 9010 \
//! --bootstrap 127.0.0.1:9000 --peer <alice_mwp_pubkey>
//!
//! How it works:
//! 1. Both peers join the same P2P/DHT network
//! 2. Each publishes their MWP availability to the DHT
//! 3. MWP coordinates simultaneous hole punch attempts
//! 4. Direct connection established without central servers!
const std = @import("std");
const p2p = @import("p2p");
const mwp = @import("mwp");
const Allocator = std.mem.Allocator;
const P2P = p2p.P2P;
/// Generate deterministic keypair from seed (for testing)
fn deterministicKeypair(seed: []const u8) mwp.KeyPair {
var seed_hash: [32]u8 = undefined;
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
hasher.update("mwp-test-keypair-v1");
hasher.update(seed);
hasher.final(&seed_hash);
// Use seed to generate Ed25519 keypair
const kp = std.crypto.sign.Ed25519.KeyPair.generateDeterministic(seed_hash) catch unreachable;
return .{
.public = kp.public_key.toBytes(),
.secret = kp.secret_key.toBytes(),
};
}
fn formatHex(bytes: []const u8, buf: []u8) []u8 {
const charset = "0123456789abcdef";
for (bytes, 0..) |b, i| {
buf[i * 2] = charset[b >> 4];
buf[i * 2 + 1] = charset[b & 0x0f];
}
return buf[0 .. bytes.len * 2];
}
fn parseHex(hex: []const u8, out: []u8) !void {
if (hex.len != out.len * 2) return error.InvalidLength;
for (0..out.len) |i| {
out[i] = std.fmt.parseInt(u8, hex[i * 2 ..][0..2], 16) catch return error.InvalidHex;
}
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Parse arguments
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
var name: []const u8 = "peer";
var port: u16 = 9000;
var bootstrap_addr: ?[]const u8 = null;
var target_pubkey: ?[32]u8 = null;
var bootstrap_dht_id: ?[32]u8 = null; // DHT node ID is 32 bytes
var deterministic_keys: bool = false;
var target_name: ?[]const u8 = null; // For deterministic key lookup
var public_ip: ?[4]u8 = null; // Explicit public IP for NAT environments
_ = args.next(); // Skip program name
while (args.next()) |arg| {
if (std.mem.eql(u8, arg, "--name")) {
name = args.next() orelse return error.MissingArg;
} else if (std.mem.eql(u8, arg, "--port")) {
const port_str = args.next() orelse return error.MissingArg;
port = try std.fmt.parseInt(u16, port_str, 10);
} else if (std.mem.eql(u8, arg, "--bootstrap")) {
bootstrap_addr = args.next() orelse return error.MissingArg;
} else if (std.mem.eql(u8, arg, "--peer")) {
const hex = args.next() orelse return error.MissingArg;
target_pubkey = [_]u8{0} ** 32;
try parseHex(hex, &target_pubkey.?);
} else if (std.mem.eql(u8, arg, "--dht-id")) {
const hex = args.next() orelse return error.MissingArg;
bootstrap_dht_id = [_]u8{0} ** 32;
try parseHex(hex, &bootstrap_dht_id.?);
} else if (std.mem.eql(u8, arg, "--deterministic")) {
deterministic_keys = true;
} else if (std.mem.eql(u8, arg, "--connect-to")) {
target_name = args.next() orelse return error.MissingArg;
} else if (std.mem.eql(u8, arg, "--public-ip")) {
// Parse IP address (e.g., "10.201.0.20")
const ip_str = args.next() orelse return error.MissingArg;
var ip_parts = std.mem.splitScalar(u8, ip_str, '.');
var ip: [4]u8 = undefined;
for (0..4) |i| {
const octet = ip_parts.next() orelse return error.InvalidIP;
ip[i] = try std.fmt.parseInt(u8, octet, 10);
}
public_ip = ip;
} else if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
std.debug.print(
\\MWP Demo - Mutual Witness Protocol for NAT Traversal
\\
\\Usage:
\\ mwp-demo [options]
\\
\\Options:
\\ --name <name> Peer name (default: peer)
\\ --port <port> P2P listen port (default: 9000)
\\ --bootstrap <addr> Bootstrap node address (e.g., 127.0.0.1:9000)
\\ --dht-id <id> Bootstrap node's DHT node ID (64 hex chars)
\\ --peer <pubkey> Target peer's MWP public key (64 hex chars)
\\ --deterministic Use deterministic keys based on --name (for testing)
\\ --connect-to <name> With --deterministic, auto-compute target's pubkey
\\ --public-ip <ip> Public IP address (for NAT/Docker, e.g., 10.201.0.20)
\\ --help, -h Show this help
\\
\\Examples:
\\ # Deterministic keys (easiest for testing):
\\ Terminal 1: mwp-demo --name alice --port 18100 --deterministic --connect-to bob
\\ Terminal 2: mwp-demo --name bob --port 18200 --deterministic --connect-to alice \
\\ --bootstrap 127.0.0.1:18100 --dht-id <alice_dht_id>
\\
\\ # Manual keys:
\\ Terminal 1: mwp-demo --name alice --port 9000
\\ Terminal 2: mwp-demo --name bob --port 9010 --bootstrap 127.0.0.1:9000 \
\\ --dht-id <alice_dht_id> --peer <alice_mwp_key>
\\
, .{});
return;
}
}
std.debug.print("\n", .{});
std.debug.print("╔════════════════════════════════════════════════════╗\n", .{});
std.debug.print("║ MWP - Mutual Witness Protocol Demo ║\n", .{});
std.debug.print("║ Zero-Infrastructure NAT Traversal ║\n", .{});
std.debug.print("╚════════════════════════════════════════════════════╝\n", .{});
std.debug.print("\n", .{});
// =========================================
// Step 1: Initialize P2P Network
// =========================================
std.debug.print("[1/4] Initializing P2P network...\n", .{});
var config = p2p.P2PConfig{};
config.network.listen_port = port;
config.network.enable_noise_encryption = true; // Enable for DHT ID exchange
var p2p_node = try P2P.init(allocator, config);
defer p2p_node.deinit();
try p2p_node.start();
// Start listening for incoming connections (0.0.0.0 to accept from all interfaces)
const listen_addr = p2p.Address.ipv4(.{ 0, 0, 0, 0 }, port);
try p2p_node.startListening(listen_addr);
std.debug.print(" P2P node listening on port {d}\n", .{port});
// Get our local DHT ID
const local_dht_id = p2p_node.getDhtLocalId() orelse {
std.debug.print(" ERROR: No DHT ID available\n", .{});
return error.DhtNotInitialized;
};
var dht_id_hex: [64]u8 = undefined;
_ = formatHex(&local_dht_id, &dht_id_hex);
std.debug.print(" DHT Node ID: {s}\n", .{dht_id_hex});
// Bootstrap if address provided
if (bootstrap_addr) |addr| {
std.debug.print(" Connecting to bootstrap node: {s}\n", .{addr});
// Parse bootstrap address
var parts = std.mem.splitScalar(u8, addr, ':');
const host = parts.next() orelse return error.InvalidBootstrap;
const port_str = parts.next() orelse return error.InvalidBootstrap;
const boot_port = try std.fmt.parseInt(u16, port_str, 10);
// Parse IP
var ip_parts = std.mem.splitScalar(u8, host, '.');
var ip: [4]u8 = undefined;
for (0..4) |i| {
const octet = ip_parts.next() orelse return error.InvalidIP;
ip[i] = try std.fmt.parseInt(u8, octet, 10);
}
const boot_addr = p2p.Address.ipv4(ip, boot_port);
if (p2p_node.connectToPeer(boot_addr)) |connection_peer_id| {
std.debug.print(" Connected! Peer ID: {x}\n", .{connection_peer_id.bytes[0..4].*});
// Register DHT node ID mapping if provided
if (bootstrap_dht_id) |remote_dht_id| {
std.debug.print(" Registering DHT peer mapping...\n", .{});
try p2p_node.registerDhtNodeId(remote_dht_id, connection_peer_id);
p2p_node.dhtAddPeer(remote_dht_id, boot_addr) catch |err| {
std.debug.print(" Warning: Failed to add DHT peer: {}\n", .{err});
};
std.debug.print(" DHT peer registered!\n", .{});
} else {
std.debug.print(" Note: No --dht-id provided, DHT peer not registered\n", .{});
}
// Trigger a DHT lookup to test IP Reflection
std.debug.print(" Sending DHT FIND_VALUE to trigger IP Reflection...\n", .{});
const test_key: [32]u8 = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ++ [_]u8{0} ** 28;
_ = p2p_node.dhtFindValue(test_key) catch |err| {
std.debug.print(" DHT lookup result: {} (expected if key not found)\n", .{err});
};
// Process messages to receive the response
std.debug.print(" Processing DHT response...\n", .{});
for (0..30) |_| {
try p2p_node.update();
std.Thread.sleep(50 * std.time.ns_per_ms);
}
// Check for IP Reflection results (Bundled STUN)
if (p2p_node.getObservedPublicAddress()) |observed| {
std.debug.print("\n ┌─────────────────────────────────────────┐\n", .{});
std.debug.print(" │ IP REFLECTION (Bundled STUN) SUCCESS! │\n", .{});
std.debug.print(" └─────────────────────────────────────────┘\n", .{});
switch (observed.ip) {
.v4 => |obs_ip| std.debug.print(" Discovered public address: {d}.{d}.{d}.{d}:{d}\n", .{ obs_ip[0], obs_ip[1], obs_ip[2], obs_ip[3], observed.port }),
.v6 => std.debug.print(" Discovered public IPv6 address (port {d})\n", .{observed.port}),
}
std.debug.print(" (Learned from DHT peer without any STUN server!)\n\n", .{});
} else {
std.debug.print(" No observed address yet (IP Reflection pending)\n", .{});
}
} else |err| {
std.debug.print(" Warning: Bootstrap connection failed: {} (will accept incoming connections)\n", .{err});
}
}
const dht_peers = p2p_node.getDhtPeerCount();
std.debug.print(" DHT peer count: {d}\n", .{dht_peers});
// =========================================
// Step 2: Initialize MWP
// =========================================
std.debug.print("\n[2/4] Initializing MWP...\n", .{});
// In listener mode (target but no bootstrap), wait for incoming peer connection
// to learn our address via IP Reflection
// Check both target_pubkey (from --peer) and target_name (from --connect-to)
if ((target_pubkey != null or target_name != null) and bootstrap_addr == null) {
std.debug.print(" Listener mode: waiting for incoming peer connection...\n", .{});
const wait_start = std.time.milliTimestamp();
while (std.time.milliTimestamp() - wait_start < 30000) {
try p2p_node.update();
// Check if we got any observed addresses (from processing incoming DHT messages)
const all_obs = p2p_node.getAllObservedAddresses(allocator) catch &[_]p2p.ObservedAddress{};
defer if (all_obs.len > 0) allocator.free(all_obs);
if (all_obs.len > 0) {
std.debug.print(" Got observed address from peer!\n", .{});
break;
}
std.Thread.sleep(100 * std.time.ns_per_ms);
}
}
// Compute our keypair (deterministic or random)
const our_keypair = if (deterministic_keys)
deterministicKeypair(name)
else
null;
// If using deterministic keys with --connect-to, compute target's pubkey
if (deterministic_keys and target_name != null) {
const target_kp = deterministicKeypair(target_name.?);
target_pubkey = target_kp.public;
std.debug.print(" Computed target pubkey for '{s}'\n", .{target_name.?});
}
// Get our addresses for MWP - prefer explicit --public-ip, then observed address
var mwp_addrs: [1]mwp.Address = undefined;
var found_addr = false;
// First priority: explicit --public-ip option (for NAT/Docker)
if (public_ip) |ip| {
mwp_addrs[0] = mwp.Address.initV4(ip, port + 1);
std.debug.print(" Using explicit public IP: {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], port + 1 });
found_addr = true;
}
// Second priority: NAT-PMP (automatic port mapping)
if (!found_addr) {
if (p2p_node.tryNatPmpDiscovery(@intCast(port + 1), 3600)) |external_ip| {
mwp_addrs[0] = mwp.Address.initV4(external_ip, port + 1);
std.debug.print(" Using NAT-PMP: {d}.{d}.{d}.{d}:{d}\n", .{ external_ip[0], external_ip[1], external_ip[2], external_ip[3], port + 1 });
found_addr = true;
}
}
// Third priority: UPnP IGD (automatic port mapping for most consumer routers)
if (!found_addr) {
if (p2p_node.tryUpnpDiscovery(@intCast(port + 1), 3600)) |external_ip| {
mwp_addrs[0] = mwp.Address.initV4(external_ip, port + 1);
std.debug.print(" Using UPnP IGD: {d}.{d}.{d}.{d}:{d}\n", .{ external_ip[0], external_ip[1], external_ip[2], external_ip[3], port + 1 });
found_addr = true;
}
}
// Fourth priority: consensus address from IP Reflection (multi-source)
if (!found_addr) {
const consensus = p2p_node.getConsensusAddress();
if (consensus.address) |observed| {
switch (observed.ip) {
.v4 => |ip| {
// Skip loopback
if (ip[0] != 127) {
mwp_addrs[0] = mwp.Address.initV4(ip, port + 1);
const confidence_str = switch (consensus.confidence) {
.none => "none",
.single_source => "single source (unverified)",
.consensus => "VERIFIED (multi-source consensus)",
.conflict => "CONFLICT (using majority)",
};
std.debug.print(" Using IP from IP Reflection: {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], port + 1 });
std.debug.print(" Confidence: {s} ({d}/{d} observers)\n", .{ confidence_str, consensus.observer_count, consensus.total_observers });
found_addr = true;
}
},
.v6 => {},
}
}
}
// Final fallback to localhost
if (!found_addr) {
std.debug.print(" No observed IP, using localhost (127.0.0.1:{d})\n", .{port + 1});
mwp_addrs[0] = mwp.Address.initV4(.{ 127, 0, 0, 1 }, port + 1);
}
var mwp_node = try mwp.MWP.init(allocator, &p2p_node, .{
.keypair = our_keypair,
.addresses = &mwp_addrs,
.default_ttl = 300,
});
defer mwp_node.deinit();
const our_pubkey = mwp_node.getPublicKey();
var pubkey_hex: [64]u8 = undefined;
_ = formatHex(&our_pubkey, &pubkey_hex);
std.debug.print(" Name: {s}\n", .{name});
std.debug.print(" MWP Public Key:\n", .{});
std.debug.print(" {s}\n", .{pubkey_hex});
// =========================================
// Step 3: Publish or Connect
// =========================================
// If we have both target AND bootstrap: initiate connection
// If we have target but no bootstrap: wait and publish for target
// If we have no target: just wait
if (target_pubkey != null and bootstrap_addr != null) {
// Initiator mode: connect to target
const target = target_pubkey.?;
std.debug.print("\n[3/4] Connecting to peer...\n", .{});
var target_hex: [64]u8 = undefined;
_ = formatHex(&target, &target_hex);
std.debug.print(" Target: {s}\n", .{target_hex});
// Compute meeting key for debugging
const meeting_key = mwp.MWP.computeMeetingKey(our_pubkey, target);
var meeting_hex: [64]u8 = undefined;
_ = formatHex(&meeting_key, &meeting_hex);
std.debug.print(" Meeting key: {s}\n", .{meeting_hex});
// Publish our availability
std.debug.print("\n Publishing availability to DHT...\n", .{});
_ = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
return;
};
std.debug.print(" Published!\n", .{});
// Try to connect
std.debug.print("\n Attempting connection (30s timeout)...\n", .{});
const result = mwp_node.connect(target, .{
.timeout_ms = 30_000,
});
std.debug.print("\n[4/4] Result:\n", .{});
switch (result) {
.success => |info| {
std.debug.print(" ✓ CONNECTION ESTABLISHED!\n", .{});
std.debug.print(" Remote: {d}.{d}.{d}.{d}:{d}\n", .{
info.remote_address.ip.v4[0],
info.remote_address.ip.v4[1],
info.remote_address.ip.v4[2],
info.remote_address.ip.v4[3],
info.remote_address.port,
});
std.debug.print(" Time: {d}ms\n", .{info.establishment_time_ms});
},
.peer_not_found => {
std.debug.print(" ✗ Peer not found in DHT\n", .{});
std.debug.print(" Make sure the peer is online and has published.\n", .{});
},
.timeout => {
std.debug.print(" ✗ Timeout waiting for peer\n", .{});
std.debug.print(" The peer may not be online or reachable.\n", .{});
},
.hole_punch_failed => |err| {
std.debug.print(" ✗ Hole punch failed: {s}\n", .{@tagName(err)});
},
.other_error => |err| {
std.debug.print(" ✗ Error: {s}\n", .{@errorName(err)});
},
}
} else if (target_pubkey) |target| {
// Listener mode with known target: publish and wait for connection
std.debug.print("\n[3/4] Publishing and waiting for peer...\n", .{});
var target_hex: [64]u8 = undefined;
_ = formatHex(&target, &target_hex);
std.debug.print(" Expected peer: {s}\n", .{target_hex});
const meeting_key = mwp.MWP.computeMeetingKey(our_pubkey, target);
var meeting_hex: [64]u8 = undefined;
_ = formatHex(&meeting_key, &meeting_hex);
std.debug.print(" Meeting key: {s}\n", .{meeting_hex});
std.debug.print("\n Other peer should use:\n", .{});
std.debug.print(" --bootstrap 127.0.0.1:{d} --dht-id {s} --connect-to {s}\n", .{ port, dht_id_hex, name });
std.debug.print("\n[4/4] Publishing and listening...\n", .{});
std.debug.print(" (Press Ctrl+C to exit)\n\n", .{});
// Publish immediately on startup - SAVE the publication for later use
std.debug.print(" Initial publish...\n", .{});
const our_publication = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
return;
};
std.debug.print(" Published!\n", .{});
var last_publish: i64 = std.time.milliTimestamp();
var last_heartbeat: i64 = std.time.milliTimestamp();
while (true) {
try p2p_node.update();
const now = std.time.milliTimestamp();
// Check for peer every 2 seconds (don't re-publish to keep same nonce)
if (now - last_publish >= 2000) {
last_publish = now;
// Try to find peer's publication and connect
if (mwp_node.findPeer(target) catch null) |pub_data| {
defer {
var pd = pub_data;
pd.deinit(allocator);
}
std.debug.print("\n ✓ FOUND PEER PUBLICATION!\n", .{});
std.debug.print(" Peer is at {d}.{d}.{d}.{d}:{d}\n", .{
pub_data.addresses[0].ip.v4[0],
pub_data.addresses[0].ip.v4[1],
pub_data.addresses[0].ip.v4[2],
pub_data.addresses[0].ip.v4[3],
pub_data.addresses[0].port,
});
std.debug.print(" Initiating hole punch...\n", .{});
// Use connectWithPublication to use our EXISTING publication
const result = mwp_node.connectWithPublication(our_publication, pub_data, .{
.timeout_ms = 10_000,
});
switch (result) {
.success => |info| {
std.debug.print(" ✓ CONNECTION ESTABLISHED!\n", .{});
std.debug.print(" Remote: {d}.{d}.{d}.{d}:{d}\n", .{
info.remote_address.ip.v4[0],
info.remote_address.ip.v4[1],
info.remote_address.ip.v4[2],
info.remote_address.ip.v4[3],
info.remote_address.port,
});
},
.hole_punch_failed => |err| {
std.debug.print(" ✗ Hole punch failed: {s}\n", .{@tagName(err)});
},
.timeout => {
std.debug.print(" ✗ Connection timeout\n", .{});
},
else => {
std.debug.print(" ✗ Connection failed\n", .{});
},
}
break;
}
}
// Heartbeat every 5 seconds
if (now - last_heartbeat >= 5000) {
last_heartbeat = now;
const dht_count = p2p_node.getDhtPeerCount();
std.debug.print(" [heartbeat] DHT peers: {d}\n", .{dht_count});
}
std.Thread.sleep(10 * std.time.ns_per_ms);
}
} else {
std.debug.print("\n[3/4] Waiting for connections...\n", .{});
std.debug.print("\n Share your MWP public key with peers:\n", .{});
std.debug.print(" {s}\n", .{pubkey_hex});
std.debug.print("\n Other peers can connect with:\n", .{});
std.debug.print(" --bootstrap 127.0.0.1:{d} --dht-id {s} --peer {s}\n", .{ port, dht_id_hex, pubkey_hex });
std.debug.print("\n[4/4] Listening...\n", .{});
std.debug.print(" (Press Ctrl+C to exit)\n\n", .{});
// Main loop: process P2P events and print heartbeat
var last_heartbeat: i64 = std.time.milliTimestamp();
while (true) {
// Process incoming connections and messages
try p2p_node.update();
// Heartbeat every 5 seconds
const now = std.time.milliTimestamp();
if (now - last_heartbeat >= 5000) {
last_heartbeat = now;
const dht_count = p2p_node.getDhtPeerCount();
// Show IP Reflection status (Bundled STUN)
if (p2p_node.getObservedPublicAddress()) |observed| {
switch (observed.ip) {
.v4 => |obs_ip| std.debug.print(" [heartbeat] DHT peers: {d}, Public IP: {d}.{d}.{d}.{d}:{d}\n", .{ dht_count, obs_ip[0], obs_ip[1], obs_ip[2], obs_ip[3], observed.port }),
.v6 => std.debug.print(" [heartbeat] DHT peers: {d}, Public IPv6 (port {d})\n", .{ dht_count, observed.port }),
}
} else {
std.debug.print(" [heartbeat] DHT peers: {d}\n", .{dht_count});
}
}
// Sleep briefly to avoid busy loop
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
}

View File

@@ -136,6 +136,7 @@ pub fn main() !void {
resume_file,
total_size,
piece_size,
null,
.rarest_first,
);
@@ -175,6 +176,7 @@ pub fn main() !void {
resume_file,
total_size + 1024, // Wrong size
piece_size,
null,
.rarest_first,
);
@@ -190,6 +192,7 @@ pub fn main() !void {
"nonexistent_resume_file.resume",
total_size,
piece_size,
null,
.rarest_first,
);

View File

@@ -220,6 +220,7 @@ const PeerManager = struct {
fn createPeer(self: *PeerManager, name: []const u8, role: PeerRole, port: u16) !*PeerState {
var config = P2PConfig.default();
config.network.listen_port = port;
config.network.enable_noise_encryption = false;
config.protocol.enable_encryption = false;
config.events.enable_logging = false;
// CASCADE FIX: Disable rate limiting for test to allow mesh topology establishment
@@ -652,6 +653,7 @@ const SwarmChaosTest = struct {
// Reinitialize A
var config = P2PConfig.default();
config.network.listen_port = recovery_port;
config.network.enable_noise_encryption = false;
config.protocol.enable_encryption = false;
config.events.enable_logging = false;
config.file_sharing.piece_size = Config.PIECE_SIZE;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -63,7 +63,7 @@ FILES_TESTS=(
"test-routing-src"
"test-serializer-src"
"test-dht-src"
# "test-manager-src" # 300 tests - kcov takes 2+ hours, impractical
"test-manager-src"
)
# Integration tests
@@ -81,7 +81,7 @@ INTEGRATION_TESTS=(
"test-p2p-comprehensive"
"test-p2p-high-impact"
"test-secure-connection"
# "test-connected-coverage" # hangs under kcov ptrace
"test-connected-coverage"
"test-tier1-coverage"
"test-tier2-coverage"
"test-transfer-coverage"

View File

@@ -13,6 +13,7 @@ pub const rate_limiter = @import("core/rate_limiter.zig");
pub const limits = @import("core/limits.zig");
pub const tracking_allocator = @import("core/tracking_allocator.zig");
pub const log = @import("core/log.zig");
pub const transport = @import("core/transport.zig");
// Re-export commonly used types
pub const Error = errors.Error;
@@ -31,6 +32,12 @@ pub const MockSocket = socket.MockSocket;
pub const MockSocketConfig = socket.MockSocketConfig;
pub const ReceiveFromResult = socket.ReceiveFromResult;
// Transport abstraction
pub const Transport = transport.Transport;
pub const TransportFactory = transport.TransportFactory;
pub const TransportState = transport.TransportState;
pub const TransportMode = transport.TransportMode;
pub const Connection = connection.Connection;
pub const ConnectionState = connection.ConnectionState;
pub const ConnectionConfig = connection.ConnectionConfig;
@@ -74,4 +81,5 @@ test {
_ = limits;
_ = tracking_allocator;
_ = log;
_ = transport;
}

View File

@@ -12,8 +12,11 @@ const posix = std.posix;
const mem = std.mem;
const fmt = std.fmt;
const builtin = @import("builtin");
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error;
const platform_time = @import("platform").time;
/// Address family types
pub const AddressFamily = enum(u8) {
@@ -145,36 +148,42 @@ pub const Ipv6Address = struct {
}
pub fn fromString(str: []const u8) Error!Ipv6Address {
var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 };
var group_idx: usize = 0;
// Two-pass parsing for :: compression
// Pass 1: parse groups into front/back arrays around ::
var front: [8]u16 = [_]u16{0} ** 8;
var back: [8]u16 = [_]u16{0} ** 8;
var front_count: usize = 0;
var back_count: usize = 0;
var found_double_colon = false;
var current_val: u16 = 0;
var digit_count: usize = 0;
var i: usize = 0;
// Handle leading ::
if (str.len >= 2 and str[0] == ':' and str[1] == ':') {
found_double_colon = true;
i = 2;
}
while (i < str.len) : (i += 1) {
const c = str[i];
if (c == ':') {
if (i + 1 < str.len and str[i + 1] == ':') {
// Handle :: (compressed zeros)
if (group_idx > 0 and digit_count > 0) {
addr.bytes[group_idx * 2] = @intCast(current_val >> 8);
addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF);
group_idx += 1;
}
// Skip remaining groups for compressed zeros
i += 1;
current_val = 0;
digit_count = 0;
continue;
}
if (group_idx >= 8) return Error.AddressParseError;
addr.bytes[group_idx * 2] = @intCast(current_val >> 8);
addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF);
group_idx += 1;
// Write current group
const target = if (found_double_colon) &back else &front;
const count = if (found_double_colon) &back_count else &front_count;
if (count.* >= 8) return Error.AddressParseError;
target[count.*] = current_val;
count.* += 1;
current_val = 0;
digit_count = 0;
if (i + 1 < str.len and str[i + 1] == ':') {
if (found_double_colon) return Error.AddressParseError; // only one :: allowed
found_double_colon = true;
i += 1; // skip second colon
}
} else {
const digit = switch (c) {
const digit: u16 = switch (c) {
'0'...'9' => c - '0',
'a'...'f' => c - 'a' + 10,
'A'...'F' => c - 'A' + 10,
@@ -186,10 +195,33 @@ pub const Ipv6Address = struct {
}
}
// Handle last group
if (digit_count > 0 and group_idx < 8) {
addr.bytes[group_idx * 2] = @intCast(current_val >> 8);
addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF);
// Write final group
if (digit_count > 0) {
const target = if (found_double_colon) &back else &front;
const count = if (found_double_colon) &back_count else &front_count;
if (count.* >= 8) return Error.AddressParseError;
target[count.*] = current_val;
count.* += 1;
}
// Assemble: front groups + zero padding + back groups
const total = front_count + back_count;
if (found_double_colon) {
if (total > 8) return Error.AddressParseError;
} else {
if (total != 8) return Error.AddressParseError;
}
var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 };
for (front[0..front_count], 0..) |val, g| {
addr.bytes[g * 2] = @intCast(val >> 8);
addr.bytes[g * 2 + 1] = @intCast(val & 0xFF);
}
const back_start = 8 - back_count;
for (back[0..back_count], 0..) |val, g| {
const idx = back_start + g;
addr.bytes[idx * 2] = @intCast(val >> 8);
addr.bytes[idx * 2 + 1] = @intCast(val & 0xFF);
}
return addr;
@@ -627,9 +659,9 @@ pub const Address = struct {
/// Get address family constant for socket operations
pub fn getSocketFamily(self: Address) u16 {
return switch (self.family) {
.ipv4 => 2, // AF_INET
.ipv6 => 10, // AF_INET6
.unix => 1, // AF_UNIX
.ipv4 => posix.AF.INET,
.ipv6 => posix.AF.INET6,
.unix => posix.AF.UNIX,
.custom => 0,
};
}
@@ -796,7 +828,7 @@ pub const MAX_DNS_CACHE_MEMORY: usize = 10 * 1024 * 1024;
/// DNS rate limiting per host
pub const DnsRateLimit = struct {
last_lookup: std.AutoHashMap(u64, i64),
mutex: std.Thread.Mutex,
mutex: Mutex,
allocator: mem.Allocator,
min_interval_ms: i64,
@@ -823,7 +855,7 @@ pub const DnsRateLimit = struct {
self.mutex.lock();
defer self.mutex.unlock();
const now = std.time.milliTimestamp();
const now = platform_time.milliTimestamp();
if (self.last_lookup.get(hash)) |last_time| {
// Check if enough time has passed since last lookup
@@ -848,13 +880,13 @@ pub const AddressResolver = struct {
/// SECURITY: Rate limiter to prevent DNS amplification attacks
rate_limiter: DnsRateLimit,
/// SECURITY: Track total cache memory usage
cache_memory_used: std.atomic.Value(usize),
cache_memory_used: AtomicValue(usize),
pub fn init(allocator: mem.Allocator) AddressResolver {
return .{
.allocator = allocator,
.rate_limiter = DnsRateLimit.init(allocator, 1000), // 1 second minimum between lookups
.cache_memory_used = std.atomic.Value(usize).init(0),
.cache_memory_used = AtomicValue(usize).init(0),
};
}

View File

@@ -7,11 +7,14 @@
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const atomic = std.atomic;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error;
const limits = @import("limits.zig");
const log = @import("log.zig");
const platform_time = @import("platform").time;
/// Buffer type indicating intended usage
pub const BufferType = enum(u8) {
@@ -58,11 +61,11 @@ pub const PoolConfig = struct {
/// Uses a sliding window algorithm for smooth rate limiting
pub const RateLimiter = struct {
/// Number of allocations in current window
allocation_count: std.atomic.Value(u64),
allocation_count: AtomicValue(u64),
/// Bytes allocated in current window
bytes_allocated: std.atomic.Value(u64),
bytes_allocated: AtomicValue(u64),
/// Window start timestamp (ms since epoch)
window_start_ms: std.atomic.Value(i64),
window_start_ms: AtomicValue(i64),
/// Configuration limits
max_allocations_per_second: u32,
max_bytes_per_second: u64,
@@ -70,9 +73,9 @@ pub const RateLimiter = struct {
pub fn init(config: PoolConfig) RateLimiter {
return .{
.allocation_count = std.atomic.Value(u64).init(0),
.bytes_allocated = std.atomic.Value(u64).init(0),
.window_start_ms = std.atomic.Value(i64).init(std.time.milliTimestamp()),
.allocation_count = AtomicValue(u64).init(0),
.bytes_allocated = AtomicValue(u64).init(0),
.window_start_ms = AtomicValue(i64).init(platform_time.milliTimestamp()),
.max_allocations_per_second = config.max_allocations_per_second,
.max_bytes_per_second = config.max_bytes_per_second,
.window_size_ms = config.rate_limit_window_ms,
@@ -82,7 +85,7 @@ pub const RateLimiter = struct {
/// Check if allocation is allowed and record it if so
/// Returns true if allowed, false if rate limited
pub fn checkAndRecord(self: *RateLimiter, bytes: usize) bool {
const now_ms = std.time.milliTimestamp();
const now_ms = platform_time.milliTimestamp();
const window_start = self.window_start_ms.load(.acquire);
// THR-M1 FIX: Properly synchronized window reset
@@ -184,7 +187,7 @@ pub const BufferPool = struct {
chunks: std.ArrayList(PoolChunk),
free_list_head: ?usize, // Index of first free chunk
allocator: mem.Allocator,
mutex: std.Thread.Mutex,
mutex: Mutex,
/// SECURITY: Rate limiter for DoS prevention
rate_limiter: RateLimiter,
@@ -437,7 +440,7 @@ const BufferBase = struct {
flags: BufferFlags,
pool: ?*BufferPool,
allocator: ?mem.Allocator,
ref_count: atomic.Value(u32),
ref_count: AtomicValue(u32),
pub fn init(data: []u8, flags: BufferFlags, pool: ?*BufferPool) BufferBase {
return .{
@@ -448,7 +451,7 @@ const BufferBase = struct {
.flags = flags,
.pool = pool,
.allocator = null,
.ref_count = atomic.Value(u32).init(1),
.ref_count = AtomicValue(u32).init(1),
};
}
@@ -461,7 +464,7 @@ const BufferBase = struct {
.flags = flags,
.pool = null,
.allocator = allocator,
.ref_count = atomic.Value(u32).init(1),
.ref_count = AtomicValue(u32).init(1),
};
}
@@ -891,7 +894,7 @@ pub const MessageBuffer = struct {
) void {
self.message_type = msg_type;
self.message_id = msg_id;
self.timestamp = std.time.timestamp();
self.timestamp = platform_time.timestamp();
}
pub fn getMessageHeader(self: *const MessageBuffer) MessageHeader {

View File

@@ -5,11 +5,15 @@
//! protocols with connection pooling, health checking, and graceful shutdown.
const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const testing = std.testing;
const mem = std.mem;
const atomic = std.atomic;
const os = std.os;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error;
const Address = @import("address.zig").Address;
const socket_mod = @import("socket.zig");
@@ -17,6 +21,8 @@ const Socket = socket_mod.Socket;
const SocketConfig = socket_mod.SocketConfig;
const Buffer = @import("buffer.zig");
const log = @import("log.zig");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
/// Connection types
pub const ConnectionType = enum(u8) {
@@ -51,33 +57,33 @@ pub const ConnectionConfig = struct {
/// Connection statistics
pub const ConnectionStats = struct {
bytes_sent: atomic.Value(u64),
bytes_received: atomic.Value(u64),
messages_sent: atomic.Value(u64),
messages_received: atomic.Value(u64),
connection_attempts: atomic.Value(u64),
successful_connections: atomic.Value(u64),
failed_connections: atomic.Value(u64),
uptime: atomic.Value(i64),
last_activity: atomic.Value(i64),
errors: atomic.Value(u64),
health_checks: atomic.Value(u64),
ref_count_errors: atomic.Value(u64),
bytes_sent: AtomicValue(u64),
bytes_received: AtomicValue(u64),
messages_sent: AtomicValue(u64),
messages_received: AtomicValue(u64),
connection_attempts: AtomicValue(u64),
successful_connections: AtomicValue(u64),
failed_connections: AtomicValue(u64),
uptime: AtomicValue(i64),
last_activity: AtomicValue(i64),
errors: AtomicValue(u64),
health_checks: AtomicValue(u64),
ref_count_errors: AtomicValue(u64),
pub fn init() ConnectionStats {
return .{
.bytes_sent = atomic.Value(u64).init(0),
.bytes_received = atomic.Value(u64).init(0),
.messages_sent = atomic.Value(u64).init(0),
.messages_received = atomic.Value(u64).init(0),
.connection_attempts = atomic.Value(u64).init(0),
.successful_connections = atomic.Value(u64).init(0),
.failed_connections = atomic.Value(u64).init(0),
.uptime = atomic.Value(i64).init(0),
.last_activity = atomic.Value(i64).init(0),
.errors = atomic.Value(u64).init(0),
.health_checks = atomic.Value(u64).init(0),
.ref_count_errors = atomic.Value(u64).init(0),
.bytes_sent = AtomicValue(u64).init(0),
.bytes_received = AtomicValue(u64).init(0),
.messages_sent = AtomicValue(u64).init(0),
.messages_received = AtomicValue(u64).init(0),
.connection_attempts = AtomicValue(u64).init(0),
.successful_connections = AtomicValue(u64).init(0),
.failed_connections = AtomicValue(u64).init(0),
.uptime = AtomicValue(i64).init(0),
.last_activity = AtomicValue(i64).init(0),
.errors = AtomicValue(u64).init(0),
.health_checks = AtomicValue(u64).init(0),
.ref_count_errors = AtomicValue(u64).init(0),
};
}
@@ -116,7 +122,7 @@ pub const ConnectionStats = struct {
}
}
self.last_activity.store(std.time.timestamp(), .monotonic);
self.last_activity.store(platform_time.timestamp(), .monotonic);
}
/// CRIT-4 FIX: Record receive with atomic increment
@@ -153,7 +159,7 @@ pub const ConnectionStats = struct {
}
}
self.last_activity.store(std.time.timestamp(), .monotonic);
self.last_activity.store(platform_time.timestamp(), .monotonic);
}
/// SECURITY FIX Issue 4: Increment counters with overflow detection
@@ -173,7 +179,7 @@ pub const ConnectionStats = struct {
} else {
std.log.warn("successful_connections counter saturated at maximum value", .{});
}
self.uptime.store(std.time.timestamp(), .monotonic);
self.uptime.store(platform_time.timestamp(), .monotonic);
}
pub fn recordFailedConnection(self: *ConnectionStats) void {
@@ -318,7 +324,7 @@ pub const HealthCheckResult = struct {
.status = .healthy,
.latency_ms = latency_ms,
.err = null,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -327,7 +333,7 @@ pub const HealthCheckResult = struct {
.status = .degraded,
.latency_ms = latency_ms,
.err = e,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -336,7 +342,7 @@ pub const HealthCheckResult = struct {
.status = .unhealthy,
.latency_ms = -1,
.err = e,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
};
@@ -347,7 +353,7 @@ pub const Connection = struct {
connection_type: ConnectionType,
config: ConnectionConfig,
/// Connection state - atomic for thread safety
state: atomic.Value(ConnectionState),
state: AtomicValue(ConnectionState),
socket: ?Socket,
local_address: ?Address,
remote_address: ?Address,
@@ -360,11 +366,11 @@ pub const Connection = struct {
/// Reference count for thread-safe shared ownership
/// Starts at 1 when created, incremented by retain(), decremented by release()
ref_count: atomic.Value(u32),
ref_count: AtomicValue(u32),
/// Mutex to protect socket operations from concurrent access
/// Must be held during any socket read/write/connect/close operation
socket_mutex: std.Thread.Mutex,
socket_mutex: Mutex,
pub fn init(
connection_type: ConnectionType,
@@ -373,7 +379,7 @@ pub const Connection = struct {
) Error!Connection {
// Generate cryptographically random connection ID
var id_bytes: [8]u8 = undefined;
std.crypto.random.bytes(&id_bytes);
platform_random.bytes(&id_bytes);
const id = std.mem.readInt(u64, &id_bytes, .little);
const buffer_config = Buffer.PoolConfig{
@@ -387,7 +393,7 @@ pub const Connection = struct {
.id = id,
.connection_type = connection_type,
.config = config,
.state = atomic.Value(ConnectionState).init(.disconnected),
.state = AtomicValue(ConnectionState).init(.disconnected),
.socket = null,
.local_address = null,
.remote_address = null,
@@ -396,8 +402,8 @@ pub const Connection = struct {
.last_health_check = 0,
.health_status = .unknown,
.allocator = allocator,
.created_at = std.time.timestamp(),
.ref_count = atomic.Value(u32).init(1),
.created_at = platform_time.timestamp(),
.ref_count = AtomicValue(u32).init(1),
.socket_mutex = .{},
};
}
@@ -432,9 +438,13 @@ pub const Connection = struct {
// This was the last reference
return true;
}
// Safety check: underflow would indicate a bug
// Defensive check: detect double-free bugs without crashing.
// Dumps a stack trace pointing to the exact call site, then returns
// an error so the application can continue running.
if (old_count == 0) {
log.err("Connection reference count underflow! Double-free detected.", .{});
_ = self.ref_count.fetchAdd(1, .acq_rel); // undo the wrapping fetchSub
std.log.err("BUG: Connection ref count underflow (double-free). Stack trace:", .{});
if (!is_wasm) std.debug.dumpCurrentStackTrace(@returnAddress());
return Error.InternalError;
}
return false;
@@ -732,7 +742,7 @@ pub const Connection = struct {
/// Thread-safe: uses socket_mutex to protect socket access
pub fn checkHealth(self: *Connection) HealthCheckResult {
self.stats.recordHealthCheck();
self.last_health_check = std.time.timestamp();
self.last_health_check = platform_time.milliTimestamp();
// Acquire socket mutex to prevent race with connect/disconnect
self.socket_mutex.lock();
@@ -843,7 +853,7 @@ pub const Connection = struct {
/// Check if connection needs health check
pub fn needsHealthCheck(self: *const Connection) bool {
const now = std.time.timestamp();
const now = platform_time.milliTimestamp();
return (now - self.last_health_check) >= self.config.health_check_interval;
}
@@ -852,7 +862,7 @@ pub const Connection = struct {
if (self.stats.getUptime() == 0) {
return 0;
}
return std.time.timestamp() - self.stats.getUptime();
return platform_time.timestamp() - self.stats.getUptime();
}
/// Graceful shutdown with timeout
@@ -879,16 +889,18 @@ pub const Connection = struct {
if (self.connection_type == .tcp or self.connection_type == .unix_stream) {
// Shutdown write side (send FIN)
if (socket.fd >= 0) {
std.posix.shutdown(socket.fd, .send) catch |err| {
std.log.warn("Failed to shutdown write side (connection ID: {}): {}", .{ self.id, err });
};
if (!is_wasm) {
std.posix.shutdown(socket.fd, .send) catch |err| {
std.log.warn("Failed to shutdown write side (connection ID: {}): {}", .{ self.id, err });
};
}
// Wait for remaining data with timeout
const start_time = std.time.milliTimestamp();
const start_time = platform_time.milliTimestamp();
var buffer: [1024]u8 = undefined;
while (true) {
const elapsed = std.time.milliTimestamp() - start_time;
const elapsed = platform_time.milliTimestamp() - start_time;
if (elapsed > timeout_ms) {
std.log.warn("Graceful shutdown timeout after {}ms (connection ID: {})", .{ timeout_ms, self.id });
break;
@@ -928,7 +940,7 @@ pub const ConnectionPool = struct {
connections: std.ArrayList(*Connection),
config: ConnectionConfig,
allocator: mem.Allocator,
mutex: std.Thread.Mutex,
mutex: Mutex,
/// SECURITY FIX Issue 3: Maximum number of connections allowed in pool
max_pool_size: usize,
/// SECURITY: Maximum connections allowed per IP address

View File

@@ -6,7 +6,10 @@
const std = @import("std");
const testing = std.testing;
const builtin = @import("builtin");
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const log = @import("log.zig");
const platform_time = @import("platform").time;
/// Comprehensive error types for P2P networking operations
pub const Error = error{
@@ -162,7 +165,7 @@ pub const ErrorInfo = struct {
.err = err,
.message = message,
.context = context,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
.location = .{
.file = file,
.line = line,
@@ -352,19 +355,19 @@ pub fn toInt(e: Error) i32 {
/// Error statistics and tracking
pub const ErrorStats = struct {
total_errors: std.atomic.Value(u64),
total_errors: AtomicValue(u64),
/// Per-error counts using a simple array indexed by error code
/// We use a fixed-size array for lock-free atomic access
error_counts: [256]std.atomic.Value(u64),
error_counts: [256]AtomicValue(u64),
pub fn init() ErrorStats {
var stats = ErrorStats{
.total_errors = std.atomic.Value(u64).init(0),
.total_errors = AtomicValue(u64).init(0),
.error_counts = undefined,
};
// Initialize all error counts to 0
for (&stats.error_counts) |*count| {
count.* = std.atomic.Value(u64).init(0);
count.* = AtomicValue(u64).init(0);
}
return stats;
}
@@ -388,14 +391,14 @@ pub const ErrorStats = struct {
/// Enhanced error metrics with detailed tracking
pub const ErrorMetrics = struct {
total_errors: std.atomic.Value(u64),
total_errors: AtomicValue(u64),
errors_by_type: std.AutoHashMap(Error, u64),
mutex: std.Thread.Mutex,
mutex: Mutex,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) ErrorMetrics {
return .{
.total_errors = std.atomic.Value(u64).init(0),
.total_errors = AtomicValue(u64).init(0),
.errors_by_type = std.AutoHashMap(Error, u64).init(allocator),
.mutex = .{},
.allocator = allocator,
@@ -448,7 +451,7 @@ pub const ErrorSnapshot = struct {
};
/// Global error statistics instance
var global_error_stats: std.atomic.Value(?*ErrorStats) = std.atomic.Value(?*ErrorStats).init(null);
var global_error_stats: AtomicValue(?*ErrorStats) = AtomicValue(?*ErrorStats).init(null);
pub fn getGlobalErrorStats() ?*ErrorStats {
return global_error_stats.load(.monotonic);

View File

@@ -5,28 +5,29 @@
const std = @import("std");
const mem = std.mem;
const time = std.time;
const platform_time = @import("time");
const AtomicValue = @import("sync").AtomicValue;
const log = @import("log.zig");
/// Token bucket rate limiter
pub const RateLimiter = struct {
/// Current number of tokens
tokens: std.atomic.Value(u64),
tokens: AtomicValue(u64),
/// Maximum tokens (burst capacity)
max_tokens: u64,
/// Token refill rate (tokens per second)
refill_rate: u64,
/// Last refill timestamp (nanoseconds)
last_refill: std.atomic.Value(i64),
last_refill: AtomicValue(i64),
/// Mutex for non-atomic operations
mutex: std.Thread.Mutex = .{},
pub fn init(config: Config) RateLimiter {
return .{
.tokens = std.atomic.Value(u64).init(config.burst_size),
.tokens = AtomicValue(u64).init(config.burst_size),
.max_tokens = config.burst_size,
.refill_rate = config.tokens_per_second,
.last_refill = std.atomic.Value(i64).init(@intCast(time.nanoTimestamp())),
.last_refill = AtomicValue(i64).init(@intCast(platform_time.nanoTimestamp())),
};
}
@@ -79,7 +80,7 @@ pub const RateLimiter = struct {
/// Refill tokens based on elapsed time
fn refill(self: *RateLimiter) void {
const now: i64 = @intCast(time.nanoTimestamp());
const now: i64 = @intCast(platform_time.nanoTimestamp());
const last = self.last_refill.load(.acquire);
const elapsed_ns = now - last;
@@ -87,7 +88,7 @@ pub const RateLimiter = struct {
// Calculate tokens to add (using nanoseconds for precision)
const elapsed_ns_u64: u64 = @intCast(elapsed_ns);
const elapsed_seconds = elapsed_ns_u64 / time.ns_per_s;
const elapsed_seconds = elapsed_ns_u64 / 1_000_000_000;
if (elapsed_seconds == 0) return;
const new_tokens = elapsed_seconds * self.refill_rate;
@@ -238,7 +239,7 @@ pub const ConnectionRateLimiter = struct {
return false;
}
const now = std.time.timestamp();
const now = platform_time.timestamp();
// Check per-IP rate limit
self.mutex.lock();

View File

@@ -5,16 +5,23 @@
//! with both synchronous and asynchronous operation modes.
const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const testing = std.testing;
const os = std.os;
const posix = std.posix;
const net = std.net;
const posix = if (!is_wasm) std.posix else undefined;
const net = if (!is_wasm) std.net else undefined;
const fd_t = if (!is_wasm) std.posix.fd_t else i32;
const mem = std.mem;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error;
const Address = @import("address.zig").Address;
const log = @import("log.zig");
const Buffer = @import("buffer.zig");
const platform_time = @import("platform").time;
/// Socket protocol types
pub const SocketProtocol = enum(u8) {
@@ -64,28 +71,28 @@ pub const SocketState = enum(u8) {
/// Socket statistics
/// THR-M2 FIX: Use atomics for thread-safe access from multiple threads
pub const SocketStats = struct {
bytes_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
bytes_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
packets_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
packets_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
errors: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
last_activity: std.atomic.Value(i64) = std.atomic.Value(i64).init(0),
bytes_sent: AtomicValue(u64) = AtomicValue(u64).init(0),
bytes_received: AtomicValue(u64) = AtomicValue(u64).init(0),
packets_sent: AtomicValue(u64) = AtomicValue(u64).init(0),
packets_received: AtomicValue(u64) = AtomicValue(u64).init(0),
errors: AtomicValue(u64) = AtomicValue(u64).init(0),
last_activity: AtomicValue(i64) = AtomicValue(i64).init(0),
pub fn recordSend(self: *SocketStats, bytes: usize) void {
_ = self.bytes_sent.fetchAdd(bytes, .monotonic);
_ = self.packets_sent.fetchAdd(1, .monotonic);
self.last_activity.store(std.time.milliTimestamp(), .monotonic);
self.last_activity.store(platform_time.milliTimestamp(), .monotonic);
}
pub fn recordReceive(self: *SocketStats, bytes: usize) void {
_ = self.bytes_received.fetchAdd(bytes, .monotonic);
_ = self.packets_received.fetchAdd(1, .monotonic);
self.last_activity.store(std.time.milliTimestamp(), .monotonic);
self.last_activity.store(platform_time.milliTimestamp(), .monotonic);
}
pub fn recordError(self: *SocketStats) void {
_ = self.errors.fetchAdd(1, .monotonic);
self.last_activity.store(std.time.milliTimestamp(), .monotonic);
self.last_activity.store(platform_time.milliTimestamp(), .monotonic);
}
/// Get snapshot of current stats (THR-M2 FIX: thread-safe getters)
@@ -116,7 +123,7 @@ pub const SocketStats = struct {
/// Main socket abstraction
pub const Socket = struct {
fd: posix.fd_t,
fd: fd_t,
config: SocketConfig,
state: SocketState,
stats: SocketStats,
@@ -151,18 +158,19 @@ pub const Socket = struct {
/// Create system socket
pub fn open(self: *Socket) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .created) {
return Error.InvalidState;
}
const domain: u32 = switch (self.config.protocol) {
.tcp, .udp => 2, // AF_INET
.unix_stream, .unix_dgram => 1, // AF_UNIX
.tcp, .udp => posix.AF.INET,
.unix_stream, .unix_dgram => posix.AF.UNIX,
};
const sock_type: u32 = switch (self.config.protocol) {
.tcp, .unix_stream => 1, // SOCK_STREAM
.udp, .unix_dgram => 2, // SOCK_DGRAM
.tcp, .unix_stream => posix.SOCK.STREAM,
.udp, .unix_dgram => posix.SOCK.DGRAM,
};
self.fd = posix.socket(domain, sock_type, 0) catch |err| {
@@ -181,6 +189,7 @@ pub const Socket = struct {
}
fn applyOptions(self: *Socket) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// ERR-H2 FIX: Track compound failures to detect systemic socket option issues
var option_failures: u32 = 0;
const MAX_TOLERATED_FAILURES: u32 = 3;
@@ -192,9 +201,10 @@ pub const Socket = struct {
log.err("CRITICAL: Failed to set non-blocking mode: {}", .{err});
self.stats.recordError();
// Close the socket since it's in an invalid state
// Set state BEFORE closing FD to prevent another thread from using a closed FD
self.state = .closed;
posix.close(self.fd);
self.fd = -1;
self.state = .closed;
return err;
};
}
@@ -310,6 +320,7 @@ pub const Socket = struct {
/// Set socket to non-blocking mode
pub fn setNonBlocking(self: *Socket, non_blocking: bool) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.state == .created or self.state == .closed) {
return Error.InvalidState;
}
@@ -340,6 +351,7 @@ pub const Socket = struct {
/// Set socket send timeout (useful for making sends non-blocking after connection)
/// A timeout of 0 means the send will return immediately if it would block
pub fn setSendTimeout(self: *Socket, timeout_ms: u32) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.state == .created or self.state == .closed) {
return Error.InvalidState;
}
@@ -360,6 +372,7 @@ pub const Socket = struct {
/// Bind socket to address
pub fn bind(self: *Socket, address: Address) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// Can bind from created (will auto-open) or opened state
if (self.state != .created and self.state != .opened) {
return Error.InvalidState;
@@ -403,6 +416,7 @@ pub const Socket = struct {
/// Listen for connections (TCP only)
pub fn listen(self: *Socket, backlog: u32) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.config.protocol != .tcp and self.config.protocol != .unix_stream) {
return Error.OperationNotSupported;
}
@@ -428,6 +442,7 @@ pub const Socket = struct {
/// Accept incoming connection
pub fn accept(self: *Socket) Error!Socket {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .listening) {
return Error.InvalidState;
}
@@ -458,7 +473,7 @@ pub const Socket = struct {
client_socket.fd = client_fd;
client_socket.state = .connected;
client_socket.local_address = self.local_address;
client_socket.stats.last_activity.store(std.time.milliTimestamp(), .monotonic);
client_socket.stats.last_activity.store(platform_time.milliTimestamp(), .monotonic);
// Extract and store peer address
// Convert IPv4 address bytes and create proper Address
@@ -481,6 +496,7 @@ pub const Socket = struct {
/// Connect to remote address
pub fn connect(self: *Socket, address: Address) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// Auto-open socket if needed
if (self.state == .created) {
try self.open();
@@ -512,11 +528,12 @@ pub const Socket = struct {
self.remote_address = address;
self.state = .connected;
self.stats.last_activity.store(std.time.milliTimestamp(), .monotonic);
self.stats.last_activity.store(platform_time.milliTimestamp(), .monotonic);
}
/// Send data over socket
pub fn send(self: *Socket, data: []const u8) Error!usize {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .connected and self.state != .bound) {
return Error.InvalidState;
}
@@ -534,6 +551,7 @@ pub const Socket = struct {
/// Send data to specific address (UDP only)
pub fn sendTo(self: *Socket, data: []const u8, address: Address) Error!usize {
if (is_wasm) return Error.OperationNotSupported;
if (self.config.protocol != .udp and self.config.protocol != .unix_dgram) {
return Error.OperationNotSupported;
}
@@ -561,6 +579,7 @@ pub const Socket = struct {
/// Receive data from socket
pub fn receive(self: *Socket, buffer: []u8) Error!usize {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .connected and self.state != .bound) {
return Error.InvalidState;
}
@@ -584,6 +603,7 @@ pub const Socket = struct {
/// Receive data and get sender address (UDP only)
pub fn receiveFrom(self: *Socket, buffer: []u8) Error!struct { size: usize, address: Address } {
if (is_wasm) return Error.OperationNotSupported;
if (self.config.protocol != .udp and self.config.protocol != .unix_dgram) {
return Error.OperationNotSupported;
}
@@ -628,6 +648,11 @@ pub const Socket = struct {
// Skip if already closed or never opened (fd would be -1)
if (self.state == .closed or self.state == .created) return;
if (is_wasm) {
self.state = .closed;
return;
}
// Check if fd is valid before closing
if (self.fd < 0) {
self.state = .closed;
@@ -642,6 +667,7 @@ pub const Socket = struct {
/// Get socket option
pub fn getOption(self: *Socket, option: SocketOption) Error!i32 {
if (is_wasm) return Error.OperationNotSupported;
// Ensure socket is opened before getting options
if (self.state == .created) {
try self.open();
@@ -687,6 +713,7 @@ pub const Socket = struct {
/// Set socket option
pub fn setOption(self: *Socket, option: SocketOption, value: i32) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// Ensure socket is opened before setting options
if (self.state == .created) {
try self.open();
@@ -723,6 +750,7 @@ pub const Socket = struct {
/// Check if socket is ready for reading
pub fn canRead(self: *const Socket) Error!bool {
if (is_wasm) return Error.OperationNotSupported;
var fds = [_]posix.pollfd{.{
.fd = self.fd,
.events = posix.POLL.IN,
@@ -735,6 +763,7 @@ pub const Socket = struct {
/// Check if socket is ready for writing
pub fn canWrite(self: *const Socket) Error!bool {
if (is_wasm) return Error.OperationNotSupported;
var fds = [_]posix.pollfd{.{
.fd = self.fd,
.events = posix.POLL.OUT,
@@ -811,7 +840,7 @@ pub const SocketManager = struct {
allocator: mem.Allocator,
sockets: std.ArrayList(Socket),
factory: SocketFactory,
mutex: std.Thread.Mutex,
mutex: Mutex,
pub fn init(allocator: mem.Allocator) SocketManager {
return .{
@@ -856,7 +885,7 @@ pub const SocketManager = struct {
}
/// Remove socket by file descriptor - safe even if ArrayList has reallocated
pub fn removeSocketByFd(self: *SocketManager, fd: std.posix.fd_t) void {
pub fn removeSocketByFd(self: *SocketManager, fd: fd_t) void {
self.mutex.lock();
defer self.mutex.unlock();

View File

@@ -12,6 +12,8 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const limits = @import("limits.zig");
/// Thread-safe global memory tracking allocator
@@ -23,32 +25,43 @@ pub const TrackingAllocator = struct {
max_bytes: u64,
/// Current allocated bytes (atomic for thread safety)
allocated_bytes: std.atomic.Value(u64),
allocated_bytes: AtomicValue(u64),
/// Peak allocation (for diagnostics)
peak_bytes: std.atomic.Value(u64),
peak_bytes: AtomicValue(u64),
/// Number of rejected allocations (for diagnostics)
rejected_count: std.atomic.Value(u64),
rejected_count: AtomicValue(u64),
/// Number of successful allocations (for diagnostics)
allocation_count: std.atomic.Value(u64),
allocation_count: AtomicValue(u64),
/// Number of frees (for diagnostics)
free_count: std.atomic.Value(u64),
free_count: AtomicValue(u64),
const Self = @This();
/// Atomically subtract from allocated_bytes, saturating at 0 to prevent underflow.
/// Uses fetchSub (single atomic op) in the common path for maximum throughput.
/// Only corrects on underflow, which is rare (forced shutdown freeing untracked memory).
fn saturatingSub(self: *Self, amount: u64) void {
const prev = self.allocated_bytes.fetchSub(amount, .release);
if (prev < amount) {
// Underflowed — correct back to 0
_ = self.allocated_bytes.fetchAdd(amount - prev, .release);
}
}
/// Initialize a tracking allocator with a backing allocator and memory limit
pub fn init(backing_allocator: Allocator, max_bytes: u64) Self {
return .{
.backing_allocator = backing_allocator,
.max_bytes = max_bytes,
.allocated_bytes = std.atomic.Value(u64).init(0),
.peak_bytes = std.atomic.Value(u64).init(0),
.rejected_count = std.atomic.Value(u64).init(0),
.allocation_count = std.atomic.Value(u64).init(0),
.free_count = std.atomic.Value(u64).init(0),
.allocated_bytes = AtomicValue(u64).init(0),
.peak_bytes = AtomicValue(u64).init(0),
.rejected_count = AtomicValue(u64).init(0),
.allocation_count = AtomicValue(u64).init(0),
.free_count = AtomicValue(u64).init(0),
};
}
@@ -99,7 +112,7 @@ pub const TrackingAllocator = struct {
const result = self.backing_allocator.rawRemap(buf, buf_align, new_len, ret_addr);
if (result == null) {
// Failed - release reserved memory
_ = self.allocated_bytes.fetchSub(delta, .release);
self.saturatingSub(delta);
return null;
}
@@ -121,7 +134,7 @@ pub const TrackingAllocator = struct {
const result = self.backing_allocator.rawRemap(buf, buf_align, new_len, ret_addr);
if (result != null) {
const delta = old_size - new_len;
_ = self.allocated_bytes.fetchSub(delta, .release);
self.saturatingSub(delta);
}
return result;
} else {
@@ -217,7 +230,7 @@ pub const TrackingAllocator = struct {
if (result == null) {
// Allocation failed - release the reserved memory
_ = self.allocated_bytes.fetchSub(size, .release);
self.saturatingSub(size);
std.log.debug("CRIT-8: Backing allocator failed for {d} bytes", .{size});
return null;
}
@@ -258,7 +271,7 @@ pub const TrackingAllocator = struct {
// Try the actual resize
if (!self.backing_allocator.rawResize(buf, buf_align, new_len, ret_addr)) {
// Failed - release reserved memory
_ = self.allocated_bytes.fetchSub(delta, .release);
self.saturatingSub(delta);
return false;
}
@@ -280,7 +293,7 @@ pub const TrackingAllocator = struct {
const delta = old_size - new_len;
if (self.backing_allocator.rawResize(buf, buf_align, new_len, ret_addr)) {
_ = self.allocated_bytes.fetchSub(delta, .release);
self.saturatingSub(delta);
return true;
}
return false;
@@ -298,14 +311,14 @@ pub const TrackingAllocator = struct {
self.backing_allocator.rawFree(buf, buf_align, ret_addr);
// Release tracked memory
_ = self.allocated_bytes.fetchSub(size, .release);
self.saturatingSub(size);
_ = self.free_count.fetchAdd(1, .monotonic);
}
};
/// Global tracking allocator instance (optional singleton pattern)
var global_tracker: ?TrackingAllocator = null;
var global_tracker_mutex: std.Thread.Mutex = .{};
var global_tracker_mutex: Mutex = .{};
/// Initialize the global tracking allocator
/// Thread-safe, can be called multiple times (only first call takes effect)

462
src/core/transport.zig Normal file
View File

@@ -0,0 +1,462 @@
//! Transport abstraction layer for platform-agnostic network I/O.
//!
//! Provides a vtable-based `Transport` interface that decouples higher layers
//! (NetworkManager, SecureConnection, DHT, file transfer) from the concrete
//! I/O mechanism. Implementations:
//! - PosixStreamTransport / PosixDatagramTransport (native TCP/UDP via Socket)
//! - WebRTCTransport (browser DataChannel via JS imports, or native via libdatachannel)
//! - MockTransport (in-memory, for tests)
const std = @import("std");
const Address = @import("address.zig").Address;
const CoreError = @import("error.zig").Error;
// ---------------------------------------------------------------------------
// Transport state
// ---------------------------------------------------------------------------
pub const TransportState = enum(u8) {
/// Initial state, not yet connected or bound
created = 0,
/// Underlying resource opened (e.g. socket fd allocated)
opened = 1,
/// Bound to a local address (UDP / listener)
bound = 2,
/// Listening for incoming connections (TCP listener)
listening = 3,
/// Connected to a remote peer (TCP, or WebRTC DataChannel open)
connected = 4,
/// Closed / shutdown
closed = 5,
/// Connecting in progress (non-blocking connect)
connecting = 6,
};
// ---------------------------------------------------------------------------
// Transport mode
// ---------------------------------------------------------------------------
pub const TransportMode = enum(u8) {
/// Reliable, ordered byte stream (TCP, WebRTC reliable DataChannel)
stream = 0,
/// Unreliable datagrams with addressing (UDP)
datagram = 1,
};
// ---------------------------------------------------------------------------
// Receive-from result (used by datagram transports)
// ---------------------------------------------------------------------------
/// Result of a datagram receiveFrom operation.
pub const ReceiveFromResult = struct {
size: usize,
address: Address,
};
// ---------------------------------------------------------------------------
// Transport — the core interface
// ---------------------------------------------------------------------------
/// A polymorphic transport handle. Thin wrapper around an erased pointer + vtable.
/// Copy-by-value (16 bytes on 64-bit).
pub const Transport = struct {
/// Erased pointer to the concrete implementation.
ptr: *anyopaque,
/// Pointer to the static vtable.
vtable: *const VTable,
pub const VTable = struct {
/// Send data (stream mode). Returns bytes sent.
/// Returns `CoreError.ConnectionTimeout` on WouldBlock.
send: *const fn (ptr: *anyopaque, data: []const u8) CoreError!usize,
/// Receive data (stream mode). Returns bytes received.
/// Returns `CoreError.ConnectionTimeout` on WouldBlock.
/// Returns `CoreError.ConnectionClosed` on EOF.
receive: *const fn (ptr: *anyopaque, buffer: []u8) CoreError!usize,
/// Send datagram to a specific address. Returns bytes sent.
/// Returns `CoreError.OperationNotSupported` for stream transports.
sendTo: *const fn (ptr: *anyopaque, data: []const u8, address: Address) CoreError!usize,
/// Receive datagram and source address.
/// Returns `CoreError.OperationNotSupported` for stream transports.
receiveFrom: *const fn (ptr: *anyopaque, buffer: []u8) CoreError!ReceiveFromResult,
/// Non-blocking readiness check: can we send without blocking?
canSend: *const fn (ptr: *anyopaque) bool,
/// Non-blocking readiness check: is there data available to read?
canReceive: *const fn (ptr: *anyopaque) bool,
/// Close the transport. Idempotent.
close: *const fn (ptr: *anyopaque) void,
/// Current state.
getState: *const fn (ptr: *anyopaque) TransportState,
/// Remote peer address (null for unconnected / datagram transports).
getRemoteAddress: *const fn (ptr: *anyopaque) ?Address,
/// Transport mode (stream vs datagram).
getMode: *const fn (ptr: *anyopaque) TransportMode,
};
// -- Convenience proxy methods (inline) ----------------------------------
pub inline fn send(self: Transport, data: []const u8) CoreError!usize {
return self.vtable.send(self.ptr, data);
}
pub inline fn receive(self: Transport, buffer: []u8) CoreError!usize {
return self.vtable.receive(self.ptr, buffer);
}
pub inline fn sendTo(self: Transport, data: []const u8, address: Address) CoreError!usize {
return self.vtable.sendTo(self.ptr, data, address);
}
pub inline fn receiveFrom(self: Transport, buffer: []u8) CoreError!ReceiveFromResult {
return self.vtable.receiveFrom(self.ptr, buffer);
}
pub inline fn canSend(self: Transport) bool {
return self.vtable.canSend(self.ptr);
}
pub inline fn canReceive(self: Transport) bool {
return self.vtable.canReceive(self.ptr);
}
pub inline fn close(self: Transport) void {
self.vtable.close(self.ptr);
}
pub inline fn getState(self: Transport) TransportState {
return self.vtable.getState(self.ptr);
}
pub inline fn getRemoteAddress(self: Transport) ?Address {
return self.vtable.getRemoteAddress(self.ptr);
}
pub inline fn getMode(self: Transport) TransportMode {
return self.vtable.getMode(self.ptr);
}
/// Helper: wrap any concrete implementation that has the right method signatures.
/// Usage: `const transport = Transport.init(&my_impl);`
pub fn init(impl_ptr: anytype) Transport {
const Impl = @TypeOf(impl_ptr);
const impl_info = @typeInfo(Impl);
if (impl_info != .pointer) @compileError("Expected pointer to implementation, got " ++ @typeName(Impl));
const Child = impl_info.pointer.child;
const gen = struct {
fn sendFn(ptr: *anyopaque, data: []const u8) CoreError!usize {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.send(data);
}
fn receiveFn(ptr: *anyopaque, buffer: []u8) CoreError!usize {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.receive(buffer);
}
fn sendToFn(ptr: *anyopaque, data: []const u8, address: Address) CoreError!usize {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.sendTo(data, address);
}
fn receiveFromFn(ptr: *anyopaque, buffer: []u8) CoreError!ReceiveFromResult {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.receiveFrom(buffer);
}
fn canSendFn(ptr: *anyopaque) bool {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.canSend();
}
fn canReceiveFn(ptr: *anyopaque) bool {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.canReceive();
}
fn closeFn(ptr: *anyopaque) void {
const self: *Child = @ptrCast(@alignCast(ptr));
self.close();
}
fn getStateFn(ptr: *anyopaque) TransportState {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.getState();
}
fn getRemoteAddressFn(ptr: *anyopaque) ?Address {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.getRemoteAddress();
}
fn getModeFn(ptr: *anyopaque) TransportMode {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.getMode();
}
const vtable = VTable{
.send = sendFn,
.receive = receiveFn,
.sendTo = sendToFn,
.receiveFrom = receiveFromFn,
.canSend = canSendFn,
.canReceive = canReceiveFn,
.close = closeFn,
.getState = getStateFn,
.getRemoteAddress = getRemoteAddressFn,
.getMode = getModeFn,
};
};
return .{
.ptr = @ptrCast(@alignCast(impl_ptr)),
.vtable = &gen.vtable,
};
}
};
// ---------------------------------------------------------------------------
// TransportFactory — creates Transport instances
// ---------------------------------------------------------------------------
/// Callback invoked when a new inbound Transport is ready (e.g. TCP accept).
pub const AcceptCallback = *const fn (transport: Transport, context: ?*anyopaque) void;
/// Factory for creating and accepting transports.
pub const TransportFactory = struct {
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
/// Initiate an outbound connection. Returns a Transport in `.connecting` state.
connect: *const fn (ptr: *anyopaque, address: Address) CoreError!Transport,
/// Start listening on the given address for inbound connections.
listen: *const fn (ptr: *anyopaque, address: Address, callback: AcceptCallback, ctx: ?*anyopaque) CoreError!void,
/// Stop listening.
stopListening: *const fn (ptr: *anyopaque) void,
/// Poll for events (accept, connect completion). Returns number of events processed.
poll: *const fn (ptr: *anyopaque, timeout_ms: u32) CoreError!usize,
};
pub inline fn connect(self: TransportFactory, address: Address) CoreError!Transport {
return self.vtable.connect(self.ptr, address);
}
pub inline fn listen(self: TransportFactory, address: Address, callback: AcceptCallback, ctx: ?*anyopaque) CoreError!void {
return self.vtable.listen(self.ptr, address, callback, ctx);
}
pub inline fn stopListening(self: TransportFactory) void {
self.vtable.stopListening(self.ptr);
}
pub inline fn poll(self: TransportFactory, timeout_ms: u32) CoreError!usize {
return self.vtable.poll(self.ptr, timeout_ms);
}
/// Helper: wrap any concrete factory implementation.
pub fn init(impl_ptr: anytype) TransportFactory {
const Impl = @TypeOf(impl_ptr);
const impl_info = @typeInfo(Impl);
if (impl_info != .pointer) @compileError("Expected pointer to factory implementation, got " ++ @typeName(Impl));
const Child = impl_info.pointer.child;
const gen = struct {
fn connectFn(ptr: *anyopaque, address: Address) CoreError!Transport {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.connect(address);
}
fn listenFn(ptr: *anyopaque, address: Address, callback: AcceptCallback, ctx: ?*anyopaque) CoreError!void {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.listen(address, callback, ctx);
}
fn stopListeningFn(ptr: *anyopaque) void {
const self: *Child = @ptrCast(@alignCast(ptr));
self.stopListening();
}
fn pollFn(ptr: *anyopaque, timeout_ms: u32) CoreError!usize {
const self: *Child = @ptrCast(@alignCast(ptr));
return self.poll(timeout_ms);
}
const vtable = VTable{
.connect = connectFn,
.listen = listenFn,
.stopListening = stopListeningFn,
.poll = pollFn,
};
};
return .{
.ptr = @ptrCast(@alignCast(impl_ptr)),
.vtable = &gen.vtable,
};
}
};
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
test "Transport vtable dispatch with mock" {
const testing = std.testing;
// A minimal mock that satisfies the Transport interface
const Mock = struct {
send_count: usize = 0,
recv_count: usize = 0,
closed: bool = false,
mode: TransportMode = .stream,
fn send(self: *@This(), data: []const u8) CoreError!usize {
self.send_count += 1;
return data.len;
}
fn receive(self: *@This(), buffer: []u8) CoreError!usize {
self.recv_count += 1;
if (buffer.len >= 5) {
@memcpy(buffer[0..5], "hello");
return 5;
}
return 0;
}
fn sendTo(_: *@This(), _: []const u8, _: Address) CoreError!usize {
return CoreError.OperationNotSupported;
}
fn receiveFrom(_: *@This(), _: []u8) CoreError!ReceiveFromResult {
return CoreError.OperationNotSupported;
}
fn canSend(_: *@This()) bool {
return true;
}
fn canReceive(_: *@This()) bool {
return true;
}
fn close(self: *@This()) void {
self.closed = true;
}
fn getState(_: *@This()) TransportState {
return .connected;
}
fn getRemoteAddress(_: *@This()) ?Address {
return null;
}
fn getMode(self: *@This()) TransportMode {
return self.mode;
}
};
var mock = Mock{};
const t = Transport.init(&mock);
// send
const sent = try t.send("test data");
try testing.expectEqual(@as(usize, 9), sent);
try testing.expectEqual(@as(usize, 1), mock.send_count);
// receive
var buf: [64]u8 = undefined;
const received = try t.receive(&buf);
try testing.expectEqual(@as(usize, 5), received);
try testing.expectEqualSlices(u8, "hello", buf[0..5]);
try testing.expectEqual(@as(usize, 1), mock.recv_count);
// state & mode
try testing.expectEqual(TransportState.connected, t.getState());
try testing.expectEqual(TransportMode.stream, t.getMode());
// canSend / canReceive
try testing.expect(t.canSend());
try testing.expect(t.canReceive());
// close
try testing.expect(!mock.closed);
t.close();
try testing.expect(mock.closed);
// datagram ops return OperationNotSupported for stream mock
try testing.expectError(CoreError.OperationNotSupported, t.sendTo("x", Address.ipv4(.{ 127, 0, 0, 1 }, 1234)));
try testing.expectError(CoreError.OperationNotSupported, t.receiveFrom(&buf));
}
test "Transport vtable dispatch with datagram mock" {
const testing = std.testing;
const DgramMock = struct {
last_send_addr: ?Address = null,
last_send_size: usize = 0,
fn send(_: *@This(), _: []const u8) CoreError!usize {
return CoreError.OperationNotSupported;
}
fn receive(_: *@This(), _: []u8) CoreError!usize {
return CoreError.OperationNotSupported;
}
fn sendTo(self: *@This(), data: []const u8, address: Address) CoreError!usize {
self.last_send_addr = address;
self.last_send_size = data.len;
return data.len;
}
fn receiveFrom(_: *@This(), buffer: []u8) CoreError!ReceiveFromResult {
if (buffer.len >= 4) {
@memcpy(buffer[0..4], "ping");
return .{
.size = 4,
.address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
};
}
return CoreError.ConnectionTimeout;
}
fn canSend(_: *@This()) bool {
return true;
}
fn canReceive(_: *@This()) bool {
return true;
}
fn close(_: *@This()) void {}
fn getState(_: *@This()) TransportState {
return .bound;
}
fn getRemoteAddress(_: *@This()) ?Address {
return null;
}
fn getMode(_: *@This()) TransportMode {
return .datagram;
}
};
var mock = DgramMock{};
const t = Transport.init(&mock);
try testing.expectEqual(TransportMode.datagram, t.getMode());
try testing.expectEqual(TransportState.bound, t.getState());
// sendTo
const dest = Address.ipv4(.{ 192, 168, 1, 1 }, 8080);
const sent = try t.sendTo("hello", dest);
try testing.expectEqual(@as(usize, 5), sent);
try testing.expectEqual(dest.port, mock.last_send_addr.?.port);
// receiveFrom
var buf: [64]u8 = undefined;
const result = try t.receiveFrom(&buf);
try testing.expectEqual(@as(usize, 4), result.size);
try testing.expectEqualSlices(u8, "ping", buf[0..4]);
try testing.expectEqual(@as(u16, 5000), result.address.port);
// stream ops return OperationNotSupported for datagram mock
try testing.expectError(CoreError.OperationNotSupported, t.send("x"));
try testing.expectError(CoreError.OperationNotSupported, t.receive(&buf));
}
test "TransportState values" {
const testing = std.testing;
try testing.expectEqual(@as(u8, 0), @intFromEnum(TransportState.created));
try testing.expectEqual(@as(u8, 4), @intFromEnum(TransportState.connected));
try testing.expectEqual(@as(u8, 5), @intFromEnum(TransportState.closed));
try testing.expectEqual(@as(u8, 6), @intFromEnum(TransportState.connecting));
}

View File

@@ -10,6 +10,7 @@
//! based on success/timeout rates, similar to TCP congestion control.
const std = @import("std");
const platform_time = @import("platform").time;
pub const AdaptiveConcurrencyController = struct {
// Configuration (set at init, immutable)
@@ -86,7 +87,7 @@ pub const AdaptiveConcurrencyController = struct {
self: *AdaptiveConcurrencyController,
current_in_flight: usize,
) void {
const now = std.time.nanoTimestamp();
const now = platform_time.nanoTimestamp();
const total = self.cycle_successes + self.cycle_timeouts;
if (total > 0) {

View File

@@ -4,9 +4,15 @@
//! peer coordination, and download progress tracking.
const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const testing = std.testing;
const mem = std.mem;
const atomic = std.atomic;
const fmt = std.fmt;
const core = @import("core");
@@ -14,6 +20,7 @@ const Error = core.errors.Error;
const hash = @import("hash.zig");
const PieceHash = hash.PieceHash;
const HashUtils = hash.HashUtils;
const filesystem = @import("filesystem.zig");
const file = @import("file.zig");
const FileChunker = file.FileChunker;
const FileWriter = file.FileWriter;
@@ -75,7 +82,7 @@ pub const DownloadRequest = struct {
.offset = offset,
.length = length,
.priority = priority,
.requested_at = std.time.timestamp(),
.requested_at = platform_time.timestamp(),
.peer_id = owned_peer_id,
};
}
@@ -87,7 +94,7 @@ pub const DownloadRequest = struct {
/// Check if request has expired
pub fn isExpired(self: DownloadRequest, timeout_seconds: i64) bool {
return std.time.timestamp() - self.requested_at > timeout_seconds;
return platform_time.timestamp() - self.requested_at > timeout_seconds;
}
};
@@ -103,22 +110,22 @@ pub const DownloadRequest = struct {
/// sufficient. If strict transactional semantics are needed, use a mutex.
pub const DownloadState = struct {
total_size: u64,
downloaded_bytes: atomic.Value(u64),
verified_bytes: atomic.Value(u64),
downloaded_bytes: AtomicValue(u64),
verified_bytes: AtomicValue(u64),
piece_count: u32,
completed_pieces: atomic.Value(u32),
failed_pieces: atomic.Value(u32),
completed_pieces: AtomicValue(u32),
failed_pieces: AtomicValue(u32),
start_time: i64,
pub fn init(total_size: u64, piece_count: u32) DownloadState {
return DownloadState{
.total_size = total_size,
.downloaded_bytes = atomic.Value(u64).init(0),
.verified_bytes = atomic.Value(u64).init(0),
.downloaded_bytes = AtomicValue(u64).init(0),
.verified_bytes = AtomicValue(u64).init(0),
.piece_count = piece_count,
.completed_pieces = atomic.Value(u32).init(0),
.failed_pieces = atomic.Value(u32).init(0),
.start_time = std.time.timestamp(),
.completed_pieces = AtomicValue(u32).init(0),
.failed_pieces = AtomicValue(u32).init(0),
.start_time = platform_time.timestamp(),
};
}
@@ -170,7 +177,7 @@ pub const DownloadState = struct {
/// Get download speed (bytes per second)
/// HIGH-4 FIX: Uses acquire ordering to see latest writes.
pub fn getDownloadSpeed(self: *DownloadState) f32 {
const elapsed = std.time.timestamp() - self.start_time;
const elapsed = platform_time.timestamp() - self.start_time;
if (elapsed <= 0) return 0.0;
const downloaded = self.downloaded_bytes.load(.acquire);
@@ -515,11 +522,11 @@ pub const DownloadManager = struct {
file_path: ?[]const u8,
request_timeout: i64,
/// Mutex protecting all hashmaps and lists
manager_mutex: std.Thread.Mutex = .{},
manager_mutex: Mutex = .{},
/// ADAPTIVE: Count of stuck downloads cleaned up since last query
/// Used by adaptive concurrency controller to detect network issues
stuck_downloads_cleaned: atomic.Value(u32) = atomic.Value(u32).init(0),
stuck_downloads_cleaned: AtomicValue(u32) = AtomicValue(u32).init(0),
// PERF: Endgame mode - request remaining pieces from ALL peers
/// Whether endgame mode is active (last few pieces)
@@ -532,6 +539,8 @@ pub const DownloadManager = struct {
endgame_initialized: bool = false,
/// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates)
endgame_broadcast_pending: bool = false,
/// Content hash of the file being downloaded (for resume state validation)
content_hash: [32]u8 = [_]u8{0} ** 32,
pub fn init(
total_size: u64,
@@ -540,7 +549,7 @@ pub const DownloadManager = struct {
piece_size: u64,
allocator: mem.Allocator,
) Error!DownloadManager {
const seed = std.crypto.random.int(u64);
const seed = platform_random.int(u64);
const selector = PieceSelector.init(strategy, seed, allocator);
return DownloadManager{
@@ -756,71 +765,77 @@ pub const DownloadManager = struct {
/// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation
fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void {
// Collect pieces to cancel (can't modify while iterating)
// Use 1024 to handle large downloads (1GB = 1024 pieces at 1MB each)
var to_cancel: [1024]u32 = undefined;
var cancel_count: usize = 0;
// Process in batches of 1024 to avoid heap allocation while handling any download size
var total_cancelled: usize = 0;
while (true) {
var to_cancel: [1024]u32 = undefined;
var cancel_count: usize = 0;
var iter = self.active_downloads.iterator();
while (iter.next()) |entry| {
if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) {
if (cancel_count < to_cancel.len) {
to_cancel[cancel_count] = entry.key_ptr.*;
cancel_count += 1;
}
}
}
// Move cancelled downloads back to pending queue
for (to_cancel[0..cancel_count]) |piece_index| {
_ = self.active_downloads.remove(piece_index);
// SOCKET FIX: Release request tracker slot so new requests can be sent
self.request_tracker.recordCompletion(peer_id, piece_index);
// DISCONNECT FIX: Clear retry tracker for this peer so piece can be
// immediately retried from another peer without counting against retry limit.
// Per BitTorrent best practices, peer disconnect should not penalize the piece.
if (self.retry_trackers.getPtr(piece_index)) |tracker| {
// Only reset if the last failure was from this peer
if (tracker.last_peer) |last| {
if (std.mem.eql(u8, &last, &peer_id)) {
tracker.reset();
var iter = self.active_downloads.iterator();
while (iter.next()) |entry| {
if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) {
if (cancel_count < to_cancel.len) {
to_cancel[cancel_count] = entry.key_ptr.*;
cancel_count += 1;
}
}
}
// Check if already in pending queue
var already_pending = false;
for (self.pending_requests.items) |pending| {
if (pending.piece_index == piece_index) {
already_pending = true;
break;
if (cancel_count == 0) break;
total_cancelled += cancel_count;
// Move cancelled downloads back to pending queue
for (to_cancel[0..cancel_count]) |piece_index| {
_ = self.active_downloads.remove(piece_index);
// SOCKET FIX: Release request tracker slot so new requests can be sent
self.request_tracker.recordCompletion(peer_id, piece_index);
// DISCONNECT FIX: Clear retry tracker for this peer so piece can be
// immediately retried from another peer without counting against retry limit.
// Per BitTorrent best practices, peer disconnect should not penalize the piece.
if (self.retry_trackers.getPtr(piece_index)) |tracker| {
// Only reset if the last failure was from this peer
if (tracker.last_peer) |last| {
if (std.mem.eql(u8, &last, &peer_id)) {
tracker.reset();
}
}
}
}
// Check if piece is already verified (might have completed from another peer)
var already_verified = false;
if (self.selector.availability_map.get(piece_index)) |info| {
already_verified = info.is_verified;
}
// Check if already in pending queue
var already_pending = false;
for (self.pending_requests.items) |pending| {
if (pending.piece_index == piece_index) {
already_pending = true;
break;
}
}
if (!already_pending and !already_verified) {
// Re-add to pending with priority (front of queue)
self.pending_requests.insert(self.allocator, 0, DownloadRequest{
.piece_index = piece_index,
.peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests
.offset = 0,
.length = @intCast(self.piece_size),
.priority = .high, // Boost priority for retried pieces
.requested_at = std.time.timestamp(),
}) catch {
std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index});
};
// Check if piece is already verified (might have completed from another peer)
var already_verified = false;
if (self.selector.availability_map.get(piece_index)) |info| {
already_verified = info.is_verified;
}
if (!already_pending and !already_verified) {
// Re-add to pending with priority (front of queue)
self.pending_requests.insert(self.allocator, 0, DownloadRequest{
.piece_index = piece_index,
.peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests
.offset = 0,
.length = @intCast(self.piece_size),
.priority = .high, // Boost priority for retried pieces
.requested_at = platform_time.timestamp(),
}) catch {
std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index});
};
}
}
}
if (cancel_count > 0) {
std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{cancel_count});
if (total_cancelled > 0) {
std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{total_cancelled});
}
}
@@ -1250,7 +1265,7 @@ pub const DownloadManager = struct {
.offset = request.offset,
.length = request.length,
.downloaded_bytes = 0,
.started_at = std.time.timestamp(),
.started_at = platform_time.timestamp(),
.status = .downloading,
};
@@ -1556,7 +1571,7 @@ pub const DownloadManager = struct {
/// This function detects and removes such stuck downloads so they can be retried.
/// CONCURRENCY FIX: Batch size now matches max_concurrent to handle all stuck downloads in one pass.
fn cleanupStuckActiveDownloadsLocked(self: *DownloadManager, max_concurrent: usize) void {
const now = std.time.timestamp();
const now = platform_time.timestamp();
// THROUGHPUT FIX: 10 seconds provides a balance between fast retry and avoiding
// premature retries. 5 seconds was too aggressive and caused excessive retries.
// 15 seconds was too slow for localhost. For WAN, consider 15 seconds.
@@ -1646,7 +1661,7 @@ pub const DownloadManager = struct {
.offset = piece_offset,
.length = piece_size_u32,
.priority = .normal,
.requested_at = std.time.timestamp(),
.requested_at = platform_time.timestamp(),
// SOCKET FIX: Zero out peer_id so request can be assigned to a different peer.
// Using the same failed peer_id would cause the retry to fail again.
// This matches the behavior in cancelActiveDownloadsFromPeerLocked.
@@ -1974,7 +1989,7 @@ pub const DownloadManager = struct {
/// PERF: Get info needed for mutex-free pwrite operations
/// Returns file handle and calculated absolute offset for direct pwrite
/// Call this while holding mutex, then release mutex and do pwrite directly
pub fn getWriteInfo(self: *DownloadManager, piece_index: u32, offset: u64) Error!struct { file: std.fs.File, absolute_offset: u64, file_path: []const u8 } {
pub fn getWriteInfo(self: *DownloadManager, piece_index: u32, offset: u64) Error!struct { file: filesystem.File, absolute_offset: u64, file_path: []const u8 } {
const writer = self.file_writer orelse return Error.InvalidState;
const path = self.file_path orelse return Error.FileError;
@@ -1996,6 +2011,8 @@ pub const DownloadManager = struct {
/// Verify a piece against expected hash by reading from disk
pub fn verifyPiece(self: *DownloadManager, piece_index: u32, expected_hash: *const PieceHash) Error!bool {
if (is_wasm) return Error.OperationNotSupported;
// Get file path
const file_path = self.file_path orelse return Error.FileError;
@@ -2010,7 +2027,7 @@ pub const DownloadManager = struct {
const actual_piece_size = @min(self.piece_size, self.total_size - offset);
// Open file for reading
var piece_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError;
var piece_file = filesystem.FileSystem.openFile(file_path, .{}) catch return Error.FileError;
defer piece_file.close();
// Seek to piece position
@@ -2092,6 +2109,8 @@ pub const DownloadManager = struct {
/// Save current download state to a resume file
/// The resume file stores which pieces are completed, allowing downloads to continue after restart
pub fn saveResumeState(self: *DownloadManager, resume_path: []const u8) Error!void {
if (is_wasm) return Error.OperationNotSupported;
self.manager_mutex.lock();
defer self.manager_mutex.unlock();
@@ -2101,7 +2120,7 @@ pub const DownloadManager = struct {
}
// Create resume file
var resume_file = std.fs.cwd().createFile(resume_path, .{}) catch return Error.FileError;
var resume_file = filesystem.FileSystem.createFile(resume_path, .{}) catch return Error.FileError;
defer resume_file.close();
// Build header
@@ -2110,7 +2129,7 @@ pub const DownloadManager = struct {
.piece_size = self.piece_size,
.piece_count = self.state.piece_count,
.completed_count = self.state.completed_pieces.load(.acquire),
.file_hash = [_]u8{0} ** 32, // TODO: Store actual file hash if available
.file_hash = self.content_hash,
};
// Write header
@@ -2152,15 +2171,18 @@ pub const DownloadManager = struct {
resume_path: []const u8,
expected_total_size: u64,
expected_piece_size: u64,
expected_content_hash: ?[32]u8,
strategy: SelectionStrategy,
) Error!?DownloadManager {
if (is_wasm) return null;
// Validate path
if (!path_security.PathValidator.isPathSafe(resume_path)) {
return Error.InvalidData;
}
// Open resume file
var resume_file = std.fs.cwd().openFile(resume_path, .{}) catch return null;
var resume_file = filesystem.FileSystem.openFile(resume_path, .{}) catch return null;
defer resume_file.close();
// Read header
@@ -2197,6 +2219,17 @@ pub const DownloadManager = struct {
return null;
}
// Validate content hash if provided (non-zero hash in file must match)
if (expected_content_hash) |expected_hash| {
const zero_hash = [_]u8{0} ** 32;
if (!std.mem.eql(u8, &header.file_hash, &zero_hash)) {
if (!std.crypto.timing_safe.eql([32]u8, header.file_hash, expected_hash)) {
std.log.warn("Resume file content hash mismatch", .{});
return null;
}
}
}
// Create download manager
var manager = try DownloadManager.init(
header.total_size,
@@ -2206,6 +2239,7 @@ pub const DownloadManager = struct {
allocator,
);
errdefer manager.deinit();
manager.content_hash = header.file_hash;
// Read bitfield
const bitfield_size = (header.piece_count + 7) / 8;
@@ -2257,13 +2291,15 @@ pub const DownloadManager = struct {
self: *DownloadManager,
piece_hashes: []const PieceHash,
) Error!u32 {
if (is_wasm) return Error.OperationNotSupported;
self.manager_mutex.lock();
defer self.manager_mutex.unlock();
const file_path = self.file_path orelse return Error.FileError;
// Open file for reading
var data_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError;
var data_file = filesystem.FileSystem.openFile(file_path, .{}) catch return Error.FileError;
defer data_file.close();
var failed_count: u32 = 0;
@@ -2348,7 +2384,9 @@ pub const DownloadManager = struct {
/// Delete the resume state file (call after successful download completion)
pub fn deleteResumeState(resume_path: []const u8) void {
std.fs.cwd().deleteFile(resume_path) catch |err| {
if (is_wasm) return;
filesystem.FileSystem.deleteFile(resume_path) catch |err| {
std.log.debug("Failed to delete resume file: {}", .{err});
};
}
@@ -2404,7 +2442,7 @@ pub const PieceRetryTracker = struct {
/// MEM-2 FIX: Copies peer ID instead of storing reference
pub fn recordFailure(self: *PieceRetryTracker, peer: []const u8) void {
self.retry_count += 1;
self.last_attempt = std.time.milliTimestamp();
self.last_attempt = platform_time.milliTimestamp();
// Copy peer ID to owned array - prevents dangling pointer
if (peer.len >= 32) {
var peer_copy: [32]u8 = undefined;
@@ -2430,7 +2468,7 @@ pub const PieceRetryTracker = struct {
if (!self.shouldRetry()) return false;
if (self.retry_count == 0) return true;
const now = std.time.milliTimestamp();
const now = platform_time.milliTimestamp();
const delay = self.getRetryDelay();
return (now - self.last_attempt) >= delay;
}

View File

@@ -9,6 +9,7 @@ const mem = std.mem;
const fs = std.fs;
const fmt = std.fmt;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core");
const Error = core.errors.Error;
@@ -185,7 +186,7 @@ pub const FileChunker = struct {
const current_piece_size = @min(self.piece_size, remaining);
// Read piece data
const piece_data = self.allocator.alloc(u8, current_piece_size) catch return Error.OutOfMemory;
const piece_data = self.allocator.alloc(u8, @intCast(current_piece_size)) catch return Error.OutOfMemory;
defer self.allocator.free(piece_data);
const bytes_read = file.read(piece_data) catch return Error.FileError;
@@ -227,28 +228,28 @@ pub const FileChunker = struct {
return Error.InvalidData;
}
// Open the file
const file = fs.cwd().openFile(file_path, .{}) catch |err| {
// Open the file via FileSystem abstraction
var file = FileSystem.openFile(file_path, .{}) catch |err| {
std.log.warn("readPiece: openFile failed for '{s}': {}", .{ file_path, err });
return Error.FileError;
};
defer file.close();
return self.readPieceInternal(file, piece_index, piece_size);
return self.readPieceInternal(&file, piece_index, piece_size);
}
/// PERF FIX: Public method to read piece from an already-open file handle.
/// This avoids the overhead of opening/closing the file for every piece.
pub fn readPieceFromHandle(self: FileChunker, file: fs.File, piece_index: u32, piece_size: u64) Error![]u8 {
pub fn readPieceFromHandle(self: FileChunker, file: *FSFile, piece_index: u32, piece_size: u64) Error![]u8 {
return self.readPieceInternal(file, piece_index, piece_size);
}
fn readPieceInternal(self: FileChunker, file: fs.File, piece_index: u32, piece_size: u64) Error![]u8 {
fn readPieceInternal(self: FileChunker, file: *FSFile, piece_index: u32, piece_size: u64) Error![]u8 {
// OVERFLOW FIX: Use checked multiplication to prevent overflow
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
// THREAD SAFETY FIX: Use preadAll instead of seek+read to allow concurrent reads
// from the same file handle without race conditions on file position.
const piece_data = self.allocator.alloc(u8, piece_size) catch return Error.OutOfMemory;
const piece_data = self.allocator.alloc(u8, @intCast(piece_size)) catch return Error.OutOfMemory;
const bytes_read = file.preadAll(piece_data, offset) catch |err| {
std.log.warn("readPiece: preadAll failed: {}", .{err});
self.allocator.free(piece_data);
@@ -274,14 +275,14 @@ pub const FileChunker = struct {
piece_index: u32,
piece_data: []const u8,
) Error!void {
const file = fs.cwd().openFile(file_path, .{
var file = FileSystem.openFile(file_path, .{
.mode = .write_only,
}) catch return Error.FileError;
defer file.close();
// OVERFLOW FIX: Use checked multiplication to prevent overflow
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
// Seek to piece position
file.seekTo(offset) catch return Error.FileError;
@@ -776,6 +777,9 @@ pub const FileUtils = struct {
/// Check if sufficient disk space is available
pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
// No disk space concept in browser/WASM environment
if (is_wasm) return;
const dir_path = std.fs.path.dirname(path) orelse ".";
if (builtin.os.tag == .linux or builtin.os.tag == .macos) {
@@ -838,13 +842,22 @@ pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
var stat: Statfs = undefined;
// Use extern fstatfs for both Linux and macOS
const fstatfs_impl = struct {
pub extern "c" fn fstatfs(fd: c_int, buf: *anyopaque) c_int;
// Use fstatfs - requires libc on Linux, always available on macOS
const result = if (builtin.os.tag == .macos or builtin.link_libc) blk: {
const fstatfs_impl = struct {
pub extern "c" fn fstatfs(fd: c_int, buf: *anyopaque) c_int;
};
break :blk fstatfs_impl.fstatfs(fd, &stat);
} else if (builtin.os.tag == .linux) blk: {
// Use Linux syscall directly when libc is not linked
const linux = std.os.linux;
const raw_result = linux.syscall2(.fstatfs, @as(usize, @bitCast(@as(isize, fd))), @intFromPtr(&stat));
break :blk if (raw_result == 0) @as(c_int, 0) else @as(c_int, -1);
} else blk: {
// Skip check on unsupported platforms
break :blk @as(c_int, -1);
};
const result = fstatfs_impl.fstatfs(fd, &stat);
if (result != 0) {
std.log.warn("Failed to get filesystem stats for {s}", .{dir_path});
return; // Allow operation to proceed
@@ -986,17 +999,17 @@ pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
pub const FileReader = struct {
allocator: mem.Allocator,
file_path: []const u8,
file: fs.File,
file: FSFile,
buffer_size: usize,
pub fn init(file_path: []const u8, allocator: mem.Allocator, buffer_size: usize) Error!FileReader {
// Validate path before opening
if (!path_security.PathValidator.isPathSafe(file_path)) {
return Error.InvalidData;
}
const file = fs.cwd().openFile(file_path, .{}) catch return Error.FileError;
const file = FileSystem.openFile(file_path, .{}) catch return Error.FileError;
return FileReader{
.allocator = allocator,
.file_path = file_path,
@@ -1049,8 +1062,8 @@ pub const FileReader = struct {
pub const FileWriter = struct {
allocator: mem.Allocator,
file_path: []const u8,
file: fs.File,
file: FSFile,
pub fn init(file_path: []const u8, allocator: mem.Allocator, file_size: ?u64) Error!FileWriter {
return initInternal(file_path, allocator, file_size, true);
}
@@ -1081,14 +1094,14 @@ pub const FileWriter = struct {
}
// DISK VERIFY FIX: Open with read=true to allow pread for disk verification
const file = fs.cwd().createFile(file_path, .{
var file = FileSystem.createFile(file_path, .{
.truncate = truncate,
.read = true,
}) catch return Error.FileError;
// PERF: Pre-allocate file if size is known (reduces fragmentation, faster writes)
if (file_size) |size| {
preallocateFile(file, size);
preallocateFile(&file, size);
}
return FileWriter{
@@ -1099,21 +1112,27 @@ pub const FileWriter = struct {
}
/// PERF: Pre-allocate file space to avoid fragmentation and allocation during writes
fn preallocateFile(file: fs.File, size: u64) void {
fn preallocateFile(file: *FSFile, size: u64) void {
// No pre-allocation on WASM
if (is_wasm) return;
// Try fallocate first (Linux) - actually allocates blocks
if (builtin.os.tag == .linux) {
// FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size
const FALLOC_FL_KEEP_SIZE = 0x01;
const fd = file.handle;
const result = std.os.linux.syscall4(.fallocate,
@as(usize, @intCast(fd)),
@as(usize, FALLOC_FL_KEEP_SIZE),
@as(usize, 0), // offset
@as(usize, @intCast(size)),
);
if (result == 0) {
std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)});
return;
if (!is_wasm) {
// FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size
const FALLOC_FL_KEEP_SIZE = 0x01;
const real_file = file.impl.real;
const fd = real_file.handle;
const result = std.os.linux.syscall4(.fallocate,
@as(usize, @intCast(fd)),
@as(usize, FALLOC_FL_KEEP_SIZE),
@as(usize, 0), // offset
@as(usize, @intCast(size)),
);
if (result == 0) {
std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)});
return;
}
}
// fallocate failed, fall through to ftruncate
}
@@ -1165,7 +1184,9 @@ pub const FileWriter = struct {
}
/// Get the underlying file handle for direct pwrite operations outside mutex
pub fn getFileHandle(self: *const FileWriter) std.fs.File {
/// Returns a copy of the FSFile — safe because pwriteAll/sync use the fd/file_id,
/// not the position field.
pub fn getFileHandle(self: *const FileWriter) FSFile {
return self.file;
}
@@ -1177,8 +1198,9 @@ pub const FileWriter = struct {
// On macOS, fsync only syncs to the drive's buffer, not the physical disk.
// F_FULLFSYNC forces the drive to flush its internal cache to the platters.
if (builtin.os.tag == .macos) {
const handle = self.file.handle;
if (!is_wasm and builtin.os.tag == .macos) {
const real_file = self.file.impl.real;
const handle = real_file.handle;
const F_FULLFSYNC = 51; // From <fcntl.h>
_ = std.c.fcntl(handle, F_FULLFSYNC, @as(c_int, 0));
// Ignore error - not all drives support F_FULLFSYNC
@@ -1189,7 +1211,7 @@ pub const FileWriter = struct {
pub fn close(self: *FileWriter) void {
self.file.close();
}
pub fn deinit(self: *FileWriter) void {
// CRITICAL FIX: Sync data to disk before closing to ensure all writes are persisted.
// Without this, data may remain in OS buffer cache and verification after stop() fails.
@@ -1228,11 +1250,11 @@ pub const MMAP_MAX_SIZE: u64 = 2 * 1024 * 1024 * 1024;
/// ```
pub const MappedFile = struct {
/// Pointer to mapped memory region
data: []align(std.heap.page_size_min) u8,
data: if (is_wasm) []u8 else []align(std.heap.page_size_min) u8,
/// Original file size
file_size: u64,
/// File handle (kept open while mapped)
file: fs.File,
/// File handle (kept open while mapped) — void on WASM (mmap not supported)
file: if (is_wasm) void else fs.File,
/// Initialize memory-mapped file for reading
/// Returns error if file is too small for mmap benefit or too large
@@ -1242,6 +1264,8 @@ pub const MappedFile = struct {
/// Initialize with custom size limits
pub fn initWithLimits(file_path: []const u8, min_size: u64, max_size: u64) Error!MappedFile {
if (is_wasm) return Error.OperationNotSupported;
// Validate path
if (!PathValidator.isPathSafe(file_path)) {
return Error.InvalidData;
@@ -1280,7 +1304,9 @@ pub const MappedFile = struct {
}
/// Initialize from an already-open file handle
pub fn initFromHandle(file: fs.File, file_size: u64) Error!MappedFile {
pub fn initFromHandle(file: if (is_wasm) void else fs.File, file_size: u64) Error!MappedFile {
if (is_wasm) return Error.OperationNotSupported;
if (file_size < MMAP_MIN_SIZE) {
return Error.InvalidData;
}
@@ -1338,27 +1364,28 @@ pub const MappedFile = struct {
/// Advise the kernel about access patterns (optimization hint)
pub fn adviseSequential(self: *MappedFile) void {
if (builtin.os.tag == .linux) {
if (!is_wasm and builtin.os.tag == .linux) {
_ = std.posix.madvise(self.data, std.posix.MADV.SEQUENTIAL);
}
}
/// Advise random access pattern
pub fn adviseRandom(self: *MappedFile) void {
if (builtin.os.tag == .linux) {
if (!is_wasm and builtin.os.tag == .linux) {
_ = std.posix.madvise(self.data, std.posix.MADV.RANDOM);
}
}
/// Pre-fault pages into memory (reduce page faults during reads)
pub fn prefault(self: *MappedFile) void {
if (builtin.os.tag == .linux) {
if (!is_wasm and builtin.os.tag == .linux) {
_ = std.posix.madvise(self.data, std.posix.MADV.WILLNEED);
}
}
/// Release resources
pub fn deinit(self: *MappedFile) void {
if (is_wasm) return;
// Unmap memory
std.posix.munmap(self.data);
// Close file
@@ -1366,7 +1393,9 @@ pub const MappedFile = struct {
}
/// Platform-specific mmap implementation
fn mapFile(file: fs.File, size: u64) ![]align(std.heap.page_size_min) u8 {
fn mapFile(file: if (is_wasm) void else fs.File, size: u64) !if (is_wasm) []u8 else []align(std.heap.page_size_min) u8 {
if (is_wasm) return error.OperationNotSupported;
const len: usize = @intCast(size);
// Use mmap on POSIX systems

View File

@@ -1,13 +1,14 @@
//! Filesystem Abstraction Layer
//!
//! Provides a unified interface for filesystem operations that can be backed by
//! either the real filesystem (std.fs) or an in-memory mock filesystem for testing.
//! either the real filesystem (std.fs), an in-memory mock filesystem for testing,
//! or a WASM/JS-backed filesystem for browser environments.
//!
//! Usage:
//! ```zig
//! const FS = @import("filesystem.zig").FileSystem;
//!
//! // Opens file using current backend (real or mock)
//! // Opens file using current backend (real, mock, or wasm)
//! var file = try FS.openFile("/path/to/file", .{});
//! defer file.close();
//!
@@ -18,10 +19,13 @@
//! To use MockFS in tests, set `use_mock_fs = true` before importing.
const std = @import("std");
const platform_time = @import("platform").time;
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const mock_fs = @import("mock_fs.zig");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
/// Compile-time flag to enable mock filesystem
/// Set this in test files before importing filesystem.zig
pub var use_mock_fs: bool = false;
@@ -30,22 +34,57 @@ pub var use_mock_fs: bool = false;
/// Must be initialized before use when use_mock_fs is true
pub var mock_instance: ?*mock_fs.MockFS = null;
// ============================================================================
// WASM extern "env" file functions (only compiled for WASM targets)
// These are implemented by the JS host (browser/host/file-host.js)
// ============================================================================
const wasm_externs = if (is_wasm) struct {
extern "env" fn js_file_open(path_ptr: [*]const u8, path_len: u32, read_only: u32) i32;
extern "env" fn js_file_create(path_ptr: [*]const u8, path_len: u32) i32;
extern "env" fn js_file_read(file_id: u32, buf_ptr: [*]u8, buf_len: u32, offset: u64) i32;
extern "env" fn js_file_write(file_id: u32, data_ptr: [*]const u8, data_len: u32, offset: u64) i32;
extern "env" fn js_file_get_size(file_id: u32) i64;
extern "env" fn js_file_close(file_id: u32) void;
extern "env" fn js_file_exists(path_ptr: [*]const u8, path_len: u32) u32;
extern "env" fn js_file_delete(path_ptr: [*]const u8, path_len: u32) u32;
extern "env" fn js_file_rename(old_ptr: [*]const u8, old_len: u32, new_ptr: [*]const u8, new_len: u32) u32;
extern "env" fn js_file_mkdir(path_ptr: [*]const u8, path_len: u32) u32;
} else struct {};
/// File kind (matches std.fs.File.Kind subset)
pub const FileKind = enum {
file,
directory,
unknown,
};
/// File statistics
pub const Stat = struct {
size: u64,
ctime: i128,
mtime: i128,
atime: i128,
kind: FileKind = .file,
};
/// Abstract file handle that wraps either std.fs.File or MockFileHandle
/// WASM file state — JS-managed handle ID with position tracking
pub const WasmFileState = struct {
file_id: u32,
position: u64,
read_only: bool,
};
/// Abstract file handle that wraps std.fs.File, MockFileHandle, or WasmFileState
pub const File = struct {
impl: FileImpl,
const FileImpl = union(enum) {
real: std.fs.File,
mock: MockFileState,
};
/// On WASM: mock + wasm variants only (no real filesystem).
/// On native: real + mock variants only (no wasm extern calls).
const FileImpl = if (is_wasm)
union(enum) { mock: MockFileState, wasm: WasmFileState }
else
union(enum) { real: std.fs.File, mock: MockFileState };
const MockFileState = struct {
fs: *mock_fs.MockFS,
@@ -54,150 +93,279 @@ pub const File = struct {
read_only: bool,
};
// ---- Mock helpers (shared by both WASM and native) ----
fn mockRead(state: *MockFileState, buffer: []u8) !usize {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data;
if (state.position >= content.len) return 0;
const available = content.len - @as(usize, @intCast(state.position));
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]);
state.position += to_read;
return to_read;
}
fn mockPreadAll(state: MockFileState, buffer: []u8, offset: u64) !usize {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data;
const off: usize = @intCast(@min(offset, content.len));
if (off >= content.len) return 0;
const available = content.len - off;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[off..][0..to_read]);
return to_read;
}
fn mockWrite(state: *MockFileState, data: []const u8) !usize {
if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
const end_pos = state.position + data.len;
if (end_pos > file.data.len) {
file.resize(@intCast(end_pos)) catch return error.OutOfMemory;
}
const pos: usize = @intCast(state.position);
@memcpy(file.data[pos..][0..data.len], data);
state.position += data.len;
file.modified_at = platform_time.timestamp();
return data.len;
}
fn mockPwriteAll(state: MockFileState, data: []const u8, offset: u64) !void {
if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
const off: usize = @intCast(offset);
if (off + data.len > file.data.len) {
file.resize(off + data.len) catch return error.OutOfMemory;
}
@memcpy(file.data[off..][0..data.len], data);
file.modified_at = platform_time.timestamp();
}
fn mockStat(state: MockFileState) !Stat {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
return Stat{
.size = file.data.len,
.ctime = file.created_at,
.mtime = file.modified_at,
.atime = file.modified_at,
};
}
fn mockSetEndPos(state: MockFileState, pos: u64) !void {
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
file.resize(pos) catch return error.OutOfMemory;
}
// ---- Public API ----
/// Read data from file at current position
pub fn read(self: *File, buffer: []u8) !usize {
switch (self.impl) {
.real => |f| return f.read(buffer),
.mock => |*state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data;
if (state.position >= content.len) {
return 0; // EOF
}
const available = content.len - @as(usize, @intCast(state.position));
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]);
state.position += to_read;
return to_read;
},
if (is_wasm) {
return switch (self.impl) {
.mock => |*state| mockRead(state, buffer),
.wasm => |*state| {
const n = wasm_externs.js_file_read(state.file_id, buffer.ptr, @intCast(buffer.len), state.position);
if (n < 0) return error.InputOutput;
const bytes: usize = @intCast(n);
state.position += bytes;
return bytes;
},
};
} else {
return switch (self.impl) {
.real => |f| f.read(buffer),
.mock => |*state| mockRead(state, buffer),
};
}
}
/// Read exactly buffer.len bytes (or until EOF)
pub fn readAll(self: *File, buffer: []u8) !usize {
var total: usize = 0;
while (total < buffer.len) {
const n = try self.read(buffer[total..]);
if (n == 0) break;
total += n;
}
return total;
}
/// Read data from file at specific offset (pread)
pub fn preadAll(self: *File, buffer: []u8, offset: u64) !usize {
switch (self.impl) {
.real => |f| return f.preadAll(buffer, offset),
.mock => |state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data;
const off: usize = @intCast(@min(offset, content.len));
if (off >= content.len) {
return 0;
}
const available = content.len - off;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[off..][0..to_read]);
return to_read;
},
if (is_wasm) {
return switch (self.impl) {
.mock => |state| mockPreadAll(state, buffer, offset),
.wasm => |state| {
const n = wasm_externs.js_file_read(state.file_id, buffer.ptr, @intCast(buffer.len), offset);
if (n < 0) return error.InputOutput;
return @intCast(n);
},
};
} else {
return switch (self.impl) {
.real => |f| f.preadAll(buffer, offset),
.mock => |state| mockPreadAll(state, buffer, offset),
};
}
}
/// Write data to file at current position
pub fn write(self: *File, data: []const u8) !usize {
switch (self.impl) {
.real => |f| return f.write(data),
.mock => |*state| {
if (state.read_only) return error.AccessDenied;
if (is_wasm) {
return switch (self.impl) {
.mock => |*state| mockWrite(state, data),
.wasm => |*state| {
if (state.read_only) return error.AccessDenied;
const n = wasm_externs.js_file_write(state.file_id, data.ptr, @intCast(data.len), state.position);
if (n < 0) return error.InputOutput;
const bytes: usize = @intCast(n);
state.position += bytes;
return bytes;
},
};
} else {
return switch (self.impl) {
.real => |f| f.write(data),
.mock => |*state| mockWrite(state, data),
};
}
}
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
// Extend file if necessary
const end_pos = state.position + data.len;
if (end_pos > file.data.len) {
file.resize(end_pos) catch return error.OutOfMemory;
}
// Copy data
const pos: usize = @intCast(state.position);
@memcpy(file.data[pos..][0..data.len], data);
state.position += data.len;
file.modified_at = std.time.timestamp();
return data.len;
},
/// Write all data to file at current position
pub fn writeAll(self: *File, data: []const u8) !void {
var written: usize = 0;
while (written < data.len) {
const n = try self.write(data[written..]);
if (n == 0) return error.InputOutput;
written += n;
}
}
/// Write data at specific offset (pwrite)
pub fn pwriteAll(self: *File, data: []const u8, offset: u64) !void {
switch (self.impl) {
.real => |f| try f.pwriteAll(data, offset),
.mock => |state| {
if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
const off: usize = @intCast(offset);
// Extend file if necessary
if (off + data.len > file.data.len) {
file.resize(off + data.len) catch return error.OutOfMemory;
}
// Copy data
@memcpy(file.data[off..][0..data.len], data);
file.modified_at = std.time.timestamp();
},
if (is_wasm) {
return switch (self.impl) {
.mock => |state| mockPwriteAll(state, data, offset),
.wasm => |state| {
if (state.read_only) return error.AccessDenied;
const n = wasm_externs.js_file_write(state.file_id, data.ptr, @intCast(data.len), offset);
if (n < 0) return error.InputOutput;
},
};
} else {
return switch (self.impl) {
.real => |f| try f.pwriteAll(data, offset),
.mock => |state| mockPwriteAll(state, data, offset),
};
}
}
/// Seek to position
pub fn seekTo(self: *File, position: u64) !void {
switch (self.impl) {
.real => |f| try f.seekTo(position),
.mock => |*state| {
state.position = position;
},
if (is_wasm) {
switch (self.impl) {
.mock => |*state| state.position = position,
.wasm => |*state| state.position = position,
}
} else {
switch (self.impl) {
.real => |f| try f.seekTo(position),
.mock => |*state| state.position = position,
}
}
}
/// Get current position
pub fn getPos(self: *File) !u64 {
switch (self.impl) {
.real => |f| return f.getPos(),
.mock => |state| return state.position,
if (is_wasm) {
return switch (self.impl) {
.mock => |state| state.position,
.wasm => |state| state.position,
};
} else {
return switch (self.impl) {
.real => |f| f.getPos(),
.mock => |state| state.position,
};
}
}
/// Get file end position (size)
pub fn getEndPos(self: *File) !u64 {
const s = try self.stat();
return s.size;
}
/// Set file end position (truncate/extend)
pub fn setEndPos(self: *File, pos: u64) !void {
if (is_wasm) {
switch (self.impl) {
.mock => |state| try mockSetEndPos(state, pos),
.wasm => {}, // No-op — JS manages sizing automatically
}
} else {
switch (self.impl) {
.real => |f| try f.setEndPos(pos),
.mock => |state| try mockSetEndPos(state, pos),
}
}
}
/// Get file statistics
pub fn stat(self: *File) !Stat {
switch (self.impl) {
.real => |f| {
const s = try f.stat();
return Stat{
.size = s.size,
.ctime = s.ctime,
.mtime = s.mtime,
.atime = s.atime,
};
},
.mock => |state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
return Stat{
.size = file.data.len,
.ctime = file.created_at,
.mtime = file.modified_at,
.atime = file.modified_at,
};
},
if (is_wasm) {
return switch (self.impl) {
.mock => |state| mockStat(state),
.wasm => |state| {
const size = wasm_externs.js_file_get_size(state.file_id);
if (size < 0) return error.InputOutput;
const now = platform_time.timestamp();
return Stat{ .size = @intCast(size), .ctime = now, .mtime = now, .atime = now };
},
};
} else {
return switch (self.impl) {
.real => |f| {
const s = try f.stat();
const kind: FileKind = switch (s.kind) {
.directory => .directory,
.file => .file,
else => .unknown,
};
return Stat{ .size = s.size, .ctime = s.ctime, .mtime = s.mtime, .atime = s.atime, .kind = kind };
},
.mock => |state| mockStat(state),
};
}
}
/// Sync file to disk (no-op for mock)
/// Sync file to disk (no-op for mock and wasm)
pub fn sync(self: *File) !void {
switch (self.impl) {
.real => |f| try f.sync(),
.mock => {},
if (is_wasm) {
switch (self.impl) {
.mock, .wasm => {},
}
} else {
switch (self.impl) {
.real => |f| try f.sync(),
.mock => {},
}
}
}
/// Close file handle
pub fn close(self: *File) void {
switch (self.impl) {
.real => |f| f.close(),
.mock => {}, // MockFS doesn't track open handles
if (is_wasm) {
switch (self.impl) {
.mock => {},
.wasm => |state| wasm_externs.js_file_close(state.file_id),
}
} else {
switch (self.impl) {
.real => |f| f.close(),
.mock => {},
}
}
}
};
@@ -206,6 +374,26 @@ pub const File = struct {
pub const FileSystem = struct {
/// Open an existing file
pub fn openFile(path: []const u8, flags: std.fs.File.OpenFlags) !File {
if (is_wasm) {
if (mock_instance) |mfs| {
if (!mfs.fileExists(path)) return error.FileNotFound;
return File{ .impl = .{ .mock = .{
.fs = mfs,
.path = path,
.position = 0,
.read_only = flags.mode == .read_only,
} } };
}
const read_only: u32 = if (flags.mode == .read_only) 1 else 0;
const fid = wasm_externs.js_file_open(path.ptr, @intCast(path.len), read_only);
if (fid < 0) return error.FileNotFound;
return File{ .impl = .{ .wasm = .{
.file_id = @intCast(fid),
.position = 0,
.read_only = read_only == 1,
} } };
}
if (mock_instance) |mfs| {
// Check if file exists in mock
if (!mfs.fileExists(path)) {
@@ -230,6 +418,28 @@ pub const FileSystem = struct {
/// Create a new file or truncate existing
pub fn createFile(path: []const u8, flags: std.fs.File.CreateFlags) !File {
if (is_wasm) {
if (mock_instance) |mfs| {
mfs.writeFile(path, "") catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
return File{ .impl = .{ .mock = .{
.fs = mfs,
.path = path,
.position = 0,
.read_only = false,
} } };
}
const fid = wasm_externs.js_file_create(path.ptr, @intCast(path.len));
if (fid < 0) return error.AccessDenied;
return File{ .impl = .{ .wasm = .{
.file_id = @intCast(fid),
.position = 0,
.read_only = false,
} } };
}
if (mock_instance) |mfs| {
// Create file in mock (or truncate if exists)
mfs.writeFile(path, "") catch |err| switch (err) {
@@ -255,6 +465,11 @@ pub const FileSystem = struct {
/// Check if file exists
pub fn fileExists(path: []const u8) bool {
if (is_wasm) {
if (mock_instance) |mfs| return mfs.fileExists(path);
return wasm_externs.js_file_exists(path.ptr, @intCast(path.len)) != 0;
}
if (mock_instance) |mfs| {
return mfs.fileExists(path);
} else {
@@ -265,6 +480,20 @@ pub const FileSystem = struct {
/// Delete a file
pub fn deleteFile(path: []const u8) !void {
if (is_wasm) {
if (mock_instance) |mfs| {
mfs.deleteFile(path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
else => return error.AccessDenied,
};
return;
}
if (wasm_externs.js_file_delete(path.ptr, @intCast(path.len)) == 0) {
return error.FileNotFound;
}
return;
}
if (mock_instance) |mfs| {
mfs.deleteFile(path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
@@ -277,6 +506,20 @@ pub const FileSystem = struct {
/// Create directory (and parents)
pub fn makePath(path: []const u8) !void {
if (is_wasm) {
if (mock_instance) |mfs| {
mfs.makeDir(path) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
return;
}
if (wasm_externs.js_file_mkdir(path.ptr, @intCast(path.len)) == 0) {
return error.AccessDenied;
}
return;
}
if (mock_instance) |mfs| {
mfs.makeDir(path) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
@@ -289,6 +532,21 @@ pub const FileSystem = struct {
/// Rename/move a file
pub fn rename(old_path: []const u8, new_path: []const u8) !void {
if (is_wasm) {
if (mock_instance) |mfs| {
mfs.rename(old_path, new_path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
return;
}
if (wasm_externs.js_file_rename(old_path.ptr, @intCast(old_path.len), new_path.ptr, @intCast(new_path.len)) == 0) {
return error.FileNotFound;
}
return;
}
if (mock_instance) |mfs| {
mfs.rename(old_path, new_path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
@@ -299,6 +557,39 @@ pub const FileSystem = struct {
try std.fs.cwd().rename(old_path, new_path);
}
}
/// Check if path is a directory (for manager.zig's resolveOutputPath)
pub fn statFile(path: []const u8) !Stat {
if (is_wasm) {
// On WASM, open the file to get its size (no directory concept)
var f = openFile(path, .{}) catch return error.FileNotFound;
defer f.close();
return f.stat();
}
if (mock_instance) |mfs| {
if (mfs.dirExists(path)) {
return Stat{ .size = 0, .ctime = 0, .mtime = 0, .atime = 0, .kind = .directory };
}
var f = try openFile(path, .{});
defer f.close();
return f.stat();
}
const s = try std.fs.cwd().statFile(path);
const kind: FileKind = switch (s.kind) {
.directory => .directory,
.file => .file,
else => .unknown,
};
return Stat{
.size = s.size,
.ctime = s.ctime,
.mtime = s.mtime,
.atime = s.atime,
.kind = kind,
};
}
};
// ============================================================================
@@ -434,3 +725,48 @@ test "FileSystem: mock delete and rename" {
try FileSystem.deleteFile("/new.txt");
try std.testing.expect(!FileSystem.fileExists("/new.txt"));
}
test "FileSystem: mock readAll and writeAll" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
var file = try FileSystem.createFile("/rw.txt", .{});
try file.writeAll("Hello, readAll!");
file.close();
var file2 = try FileSystem.openFile("/rw.txt", .{});
defer file2.close();
var buf: [100]u8 = undefined;
const n = try file2.readAll(&buf);
try std.testing.expectEqualStrings("Hello, readAll!", buf[0..n]);
}
test "FileSystem: mock getEndPos and setEndPos" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
try mfs.writeFile("/size.txt", "12345");
var file = try FileSystem.openFile("/size.txt", .{ .mode = .read_write });
defer file.close();
const end = try file.getEndPos();
try std.testing.expectEqual(@as(u64, 5), end);
try file.setEndPos(10);
const end2 = try file.getEndPos();
try std.testing.expectEqual(@as(u64, 10), end2);
}

View File

@@ -7,6 +7,7 @@
//! acceleration (SHA-NI on x86_64, SHA2 extensions on ARM64) when available.
const std = @import("std");
const platform_time = @import("platform").time;
const testing = std.testing;
const crypto = std.crypto;
const mem = std.mem;
@@ -157,8 +158,8 @@ pub const FileMetadata = struct {
.size = size,
.piece_count = @as(u32, @intCast(piece_hashes.len)),
.piece_hashes = piece_hashes,
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.modified_at = platform_time.timestamp(),
};
}
@@ -274,7 +275,7 @@ pub const HashPool = struct {
) Error!VerificationBatch {
var results: std.ArrayList(VerificationResult) = .{};
errdefer results.deinit(self.allocator);
const start_time = std.time.milliTimestamp();
const start_time = platform_time.milliTimestamp();
var valid_count: u32 = 0;
for (piece_datas, 0..) |piece_data, i| {
@@ -298,7 +299,7 @@ pub const HashPool = struct {
}
}
const end_time = std.time.milliTimestamp();
const end_time = platform_time.milliTimestamp();
const verification_time = @as(u64, @intCast(end_time - start_time));
return VerificationBatch{

View File

@@ -18,11 +18,16 @@
//! IMPORTANT: Never acquire lower-level locks (0-4) while holding Level 5 locks.
const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const testing = std.testing;
const mem = std.mem;
const fmt = std.fmt;
const atomic = std.atomic;
const core = @import("core");
const Error = core.errors.Error;
@@ -31,6 +36,7 @@ const HashUtils = hash_mod.HashUtils;
const FileMetadata = hash_mod.FileMetadata;
const PieceHash = hash_mod.PieceHash;
const ContentHash = hash_mod.ContentHash;
const filesystem = @import("filesystem.zig");
const file_mod = @import("file.zig");
const FileChunker = file_mod.FileChunker;
const FileWriter = file_mod.FileWriter;
@@ -161,7 +167,7 @@ pub const PeerReputation = struct {
}
// MED-4 FIX: Global configurable blacklist duration (thread-safe)
var configured_base_duration: std.atomic.Value(i64) = std.atomic.Value(i64).init(DEFAULT_BLACKLIST_DURATION_SECONDS);
var configured_base_duration: AtomicValue(i64) = AtomicValue(i64).init(DEFAULT_BLACKLIST_DURATION_SECONDS);
/// MED-4 FIX: Configure the base blacklist duration
/// MED-6 FIX: Uses .release ordering for security config to ensure visibility
@@ -224,7 +230,7 @@ pub const PeerReputation = struct {
/// MED-4 FIX: Uses exponential backoff for repeat offenders
pub fn recordBadPiece(self: *PeerReputation) void {
self.bad_pieces += 1;
self.last_bad_piece_time = std.time.timestamp();
self.last_bad_piece_time = platform_time.timestamp();
// Blacklist peer if they've sent too many bad pieces
if (self.bad_pieces >= MAX_BAD_PIECES) {
@@ -234,7 +240,7 @@ pub const PeerReputation = struct {
const base = getBaseBlacklistDuration();
const multiplier: i64 = @as(i64, 1) << @min(self.blacklist_count - 1, 10); // Cap at 2^10 = 1024x
const duration = @min(base * multiplier, MAX_BLACKLIST_DURATION_SECONDS);
self.blacklisted_until = std.time.timestamp() + duration;
self.blacklisted_until = platform_time.timestamp() + duration;
std.log.info("MED-4: Peer blacklisted for {}s (offense #{}, base={}s)", .{
duration,
self.blacklist_count,
@@ -250,7 +256,7 @@ pub const PeerReputation = struct {
/// Check if peer is currently blacklisted
pub fn isBlacklisted(self: *const PeerReputation) bool {
return std.time.timestamp() < self.blacklisted_until;
return platform_time.timestamp() < self.blacklisted_until;
}
/// Get reputation score (0.0 to 1.0, higher is better)
@@ -304,7 +310,7 @@ pub const PeerResponseTracker = struct {
pub fn init() PeerSlotInfo {
return .{
.queued_count = 0,
.last_activity = std.time.timestamp(),
.last_activity = platform_time.timestamp(),
.queued_bytes = 0,
};
}
@@ -417,7 +423,7 @@ pub const PeerResponseTracker = struct {
}
gop.value_ptr.queued_count += 1;
gop.value_ptr.queued_bytes += piece_size;
gop.value_ptr.last_activity = std.time.timestamp();
gop.value_ptr.last_activity = platform_time.timestamp();
return true;
},
.rejected_peer_limit, .rejected_total_limit => return false,
@@ -435,7 +441,7 @@ pub const PeerResponseTracker = struct {
} else {
info.queued_bytes = 0;
}
info.last_activity = std.time.timestamp();
info.last_activity = platform_time.timestamp();
// Clean up entry if peer has no more queued responses
if (info.queued_count == 0) {
@@ -454,7 +460,7 @@ pub const PeerResponseTracker = struct {
/// Clean up stale peer entries (peers with no activity for a while)
pub fn cleanupStalePeers(self: *PeerResponseTracker) usize {
const now = std.time.timestamp();
const now = platform_time.timestamp();
var to_remove = std.ArrayList([32]u8).init(self.allocator);
defer to_remove.deinit();
@@ -676,7 +682,7 @@ pub const PreSerializedPieceResponse = struct {
off += 1;
// Message ID (4 bytes, big endian)
const msg_id = std.crypto.random.int(u32);
const msg_id = platform_random.int(u32);
std.mem.writeInt(u32, result.header[off..][0..4], msg_id, .big);
off += 4;
@@ -685,13 +691,19 @@ pub const PreSerializedPieceResponse = struct {
off += 2;
// Timestamp (8 bytes, big endian)
const timestamp = std.time.timestamp();
const timestamp = platform_time.timestamp();
std.mem.writeInt(i64, result.header[off..][0..8], timestamp, .big);
off += 8;
// Data length (4 bytes, big endian)
// Data = [content_hash:32][piece_index:4][offset:4][piece_data:N]
const data_len: u32 = @intCast(32 + 4 + 4 + data.len);
const total_data_len = 32 + 4 + 4 + data.len;
if (total_data_len > std.math.maxInt(u32)) {
// Piece data too large for u32 length field — return empty response
result.header_len = 0;
return result;
}
const data_len: u32 = @intCast(total_data_len);
std.mem.writeInt(u32, result.header[off..][0..4], data_len, .big);
off += 4;
@@ -862,7 +874,7 @@ pub const FileSharingSession = struct {
const content_hash = try HashUtils.metadataHash(file_metadata);
return FileSharingSession{
.session_id = std.crypto.random.int(u64),
.session_id = platform_random.int(u64),
.file_metadata = file_metadata,
.content_hash = content_hash,
.download_manager = null,
@@ -870,8 +882,8 @@ pub const FileSharingSession = struct {
.transfer_protocol = TransferProtocol.init(allocator),
.piece_pool = PiecePool.init(allocator),
.status = .initializing,
.created_at = std.time.timestamp(),
.updated_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.updated_at = platform_time.timestamp(),
.allocator = allocator,
.response_tracker = null, // Initialized when upload starts
.pending_piece_responses = .{},
@@ -933,6 +945,7 @@ pub const FileSharingSession = struct {
allocator,
);
manager.content_hash = self.content_hash;
try manager.setOutputFile(output_path);
self.download_manager = manager;
self.status = .ready;
@@ -1009,7 +1022,7 @@ pub const FileSharingSession = struct {
/// Update session timestamp
pub fn update(self: *FileSharingSession) void {
self.updated_at = std.time.timestamp();
self.updated_at = platform_time.timestamp();
}
/// Check if session is active
@@ -1106,7 +1119,6 @@ pub const FileSharingManager = struct {
/// Dynamically adjusts max_concurrent_downloads based on network health
adaptive_controller: ?AdaptiveConcurrencyController,
/// TIMING: Counter for periodic timing logs
timing_log_counter: u32 = 0,
// ========================================================================
// HIGH-5 FIX: LOCK ORDERING DOCUMENTATION
@@ -1130,19 +1142,19 @@ pub const FileSharingManager = struct {
// DownloadManager.manager_mutex is only acquired while holding sessions_mutex,
// so it's implicitly ordered after sessions_mutex.
// ========================================================================
sessions_mutex: std.Thread.Mutex = .{},
file_registry_mutex: std.Thread.Mutex = .{},
stats_mutex: std.Thread.Mutex = .{}, // Protects messages_sent/failed
sessions_mutex: Mutex = .{},
file_registry_mutex: Mutex = .{},
stats_mutex: Mutex = .{}, // Protects messages_sent/failed
/// THR-CRIT-2: Protects peer_reputation HashMap and all PeerReputation entry mutations.
/// All HashMap access (.get, .getOrPut, .put) must be done while holding this mutex.
/// Mutations to PeerReputation entries (recordBadPiece, recordGoodPiece) must be done
/// while holding this mutex. Read operations via .get() return a copy which is safe
/// to use outside the mutex.
reputation_mutex: std.Thread.Mutex = .{},
reputation_mutex: Mutex = .{},
/// THR-H2 FIX: Protects runtime config modifications (bandwidth limits, strategies, features)
/// Config is read during session operations and modified via updateBandwidthLimits,
/// setSelectionStrategy, setFeatures. Mutex ensures atomic reads/writes.
config_mutex: std.Thread.Mutex = .{},
config_mutex: Mutex = .{},
// HIGH-5 FIX: Debug tracking for lock ordering verification
lock_order_debug: if (@import("builtin").mode == .Debug) LockOrderDebug else void = if (@import("builtin").mode == .Debug) .{} else {},
@@ -1155,7 +1167,7 @@ pub const FileSharingManager = struct {
threadlocal var tls_config_held: bool = false;
// Statistics for lock order violations (for monitoring) - global counter is fine
violations_detected: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
violations_detected: AtomicValue(u64) = AtomicValue(u64).init(0),
fn checkCanAcquireSessions(self: *LockOrderDebug) Error!void {
// sessions_mutex can only be acquired if we either:
@@ -1232,7 +1244,7 @@ pub const FileSharingManager = struct {
.use_results_queue = true,
// PERF: Pre-allocate buffers for piece verification
.num_piece_buffers = config.buffer_pool_size,
.piece_buffer_size = config.piece_size,
.piece_buffer_size = @intCast(config.piece_size),
}) catch {
// errdefer will handle destroy
return Error.OutOfMemory;
@@ -1487,7 +1499,7 @@ pub const FileSharingManager = struct {
};
}
session.status = .completed;
session.updated_at = std.time.timestamp();
session.updated_at = platform_time.timestamp();
std.log.info("Download completed! Session {d}: All {d} pieces verified (async), file_path={s}", .{
session_id,
dm.state.piece_count,
@@ -1684,7 +1696,7 @@ pub const FileSharingManager = struct {
std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries});
return Error.SystemError;
}
final_session_id = std.crypto.random.int(u64);
final_session_id = platform_random.int(u64);
std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries});
}
session.session_id = final_session_id;
@@ -1849,7 +1861,7 @@ pub const FileSharingManager = struct {
std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries});
return Error.SystemError;
}
final_session_id = std.crypto.random.int(u64);
final_session_id = platform_random.int(u64);
std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries});
}
session.session_id = final_session_id;
@@ -1879,6 +1891,8 @@ pub const FileSharingManager = struct {
file_metadata: FileMetadata,
output_path: []const u8,
) Error!u64 {
if (is_wasm) return Error.OperationNotSupported;
// SECURITY: Sanitize the filename from metadata to prevent path traversal
// This is used for validation, not for determining the output path
const sanitized_name = sanitizeFilename(file_metadata.name, self.allocator) catch return Error.OutOfMemory;
@@ -1889,7 +1903,7 @@ pub const FileSharingManager = struct {
// If it's a file path, use it directly (user specified the exact destination)
const is_directory = blk: {
// Check if output_path exists and is a directory
const stat = std.fs.cwd().statFile(output_path) catch {
const stat = filesystem.FileSystem.statFile(output_path) catch {
// Path doesn't exist - check if it ends with a path separator or has no extension
const base = std.fs.path.basename(output_path);
// If basename has no extension and doesn't look like a filename, treat as directory
@@ -2022,7 +2036,7 @@ pub const FileSharingManager = struct {
std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries});
return Error.SystemError;
}
final_session_id = std.crypto.random.int(u64);
final_session_id = platform_random.int(u64);
std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries});
}
session.session_id = final_session_id;
@@ -2114,7 +2128,7 @@ pub const FileSharingManager = struct {
/// Process all active sessions
pub fn processSessions(self: *FileSharingManager) Error!void {
// TIMING: Track overall function time and phases
const timer_start = std.time.nanoTimestamp();
const timer_start = platform_time.nanoTimestamp();
var phase1_time: i128 = 0;
var phase2_time: i128 = 0;
var phase3_time: i128 = 0;
@@ -2174,7 +2188,7 @@ pub const FileSharingManager = struct {
// CRIT-NEW-21 FIX: Track dropped messages due to OOM
var dropped_messages: usize = 0;
var total_messages: usize = 0;
const phase1_start = std.time.nanoTimestamp();
const phase1_start = platform_time.nanoTimestamp();
self.sessions_mutex.lock();
var it = self.sessions.valueIterator();
@@ -2308,8 +2322,8 @@ pub const FileSharingManager = struct {
}
// TIMING: Phase 1 complete
phase1_time = std.time.nanoTimestamp() - phase1_start;
const phase2_start = std.time.nanoTimestamp();
phase1_time = platform_time.nanoTimestamp() - phase1_start;
const phase2_start = platform_time.nanoTimestamp();
// PHASE 2: Send messages (NO lock held - prevents deadlock)
for (messages_to_send.items) |msg| {
@@ -2320,7 +2334,7 @@ pub const FileSharingManager = struct {
.message_id = 0,
.peer_id = msg.peer_id_copy,
.data = msg.data_copy,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
std.log.debug("PHASE2: Sending message type={}", .{msg.message_type});
// CRIT-NEW-19 FIX: Record swallowed error for tracking
@@ -2365,8 +2379,8 @@ pub const FileSharingManager = struct {
}
// TIMING: Phase 2 complete
phase2_time = std.time.nanoTimestamp() - phase2_start;
const phase3_start = std.time.nanoTimestamp();
phase2_time = platform_time.nanoTimestamp() - phase2_start;
const phase3_start = platform_time.nanoTimestamp();
// ARCH-1 FIX: Process session download managers directly instead of the disconnected queue
// The queue held separate DownloadManagers that weren't linked to sessions
@@ -2533,8 +2547,8 @@ pub const FileSharingManager = struct {
}
// TIMING: Phase 3 complete
phase3_time = std.time.nanoTimestamp() - phase3_start;
const phase4_start = std.time.nanoTimestamp();
phase3_time = platform_time.nanoTimestamp() - phase3_start;
const phase4_start = platform_time.nanoTimestamp();
// ADAPTIVE: Record cycle statistics after processing all sessions
// Record stuck downloads as partial timeouts - provides congestion signal
@@ -2565,7 +2579,7 @@ pub const FileSharingManager = struct {
// Debug logging for adaptive controller state
if (total_stuck > 0 or total_in_flight > 50) {
const stats = ctrl.getStats();
std.log.info("ADAPTIVE: in_flight={}, stuck={}, timeouts_recorded={}, success={d:.1}%, timeout={d:.1}%, concurrency={}", .{
std.log.debug("ADAPTIVE: in_flight={}, stuck={}, timeouts_recorded={}, success={d:.1}%, timeout={d:.1}%, concurrency={}", .{
total_in_flight,
total_stuck,
weighted_timeouts,
@@ -2580,7 +2594,7 @@ pub const FileSharingManager = struct {
}
// TIMING: Phase 4 complete
phase4_time = std.time.nanoTimestamp() - phase4_start;
phase4_time = platform_time.nanoTimestamp() - phase4_start;
// PHASE 5: Check for endgame broadcast trigger (outside lock to avoid deadlock)
{
@@ -2606,12 +2620,10 @@ pub const FileSharingManager = struct {
// Clean up completed/failed sessions
self.cleanupCompletedSessions();
// TIMING: Log timing breakdown (only when significant time spent)
const total_time = std.time.nanoTimestamp() - timer_start;
// TIMING: Log timing breakdown only when significant (>10ms)
const total_time = platform_time.nanoTimestamp() - timer_start;
const total_ms = @as(f64, @floatFromInt(total_time)) / 1_000_000.0;
// Log every 100th call or when > 1ms to reduce spam while getting data
self.timing_log_counter +%= 1;
if (total_ms > 1.0 or self.timing_log_counter % 100 == 0) {
if (total_ms > 10.0) {
const p1_ms = @as(f64, @floatFromInt(phase1_time)) / 1_000_000.0;
const p2_ms = @as(f64, @floatFromInt(phase2_time)) / 1_000_000.0;
const p3_ms = @as(f64, @floatFromInt(phase3_time)) / 1_000_000.0;
@@ -2705,7 +2717,7 @@ pub const FileSharingManager = struct {
// CASCADE FIX: Keep completed sessions longer for cascade distribution
// Previously 60 seconds was too short - peers couldn't serve pieces to slower downloaders
const grace_period_seconds: i64 = 3600; // Keep for 1 hour after completion
const age = std.time.timestamp() - session.updated_at;
const age = platform_time.timestamp() - session.updated_at;
if (session.status == .completed) {
// Only remove completed sessions after grace period
if (age >= grace_period_seconds) {
@@ -3227,16 +3239,16 @@ pub const FileSharingManager = struct {
/// THROUGHPUT FIX: Increased from 2GB to 4GB for high-throughput localhost testing.
/// With 1MB pieces: 4GB / 1MB = 4096 messages
/// This allows deep pipelines without triggering fair queue rejection.
const MAX_QUEUED_RESPONSE_BYTES: usize = 4 * 1024 * 1024 * 1024; // 4GB max for high throughput
const MAX_QUEUED_RESPONSE_BYTES: u64 = 4 * 1024 * 1024 * 1024; // 4GB max for high throughput
/// Calculate adaptive queue limit based on piece size
fn calculateMaxQueuedResponses(piece_size: u64) usize {
// Minimum 64 to ensure reasonable throughput, max 4000 for smaller pieces
// THROUGHPUT FIX: Increased limits to prevent silent request rejection
const piece_size_usize: usize = if (piece_size > std.math.maxInt(usize)) std.math.maxInt(usize) else @intCast(piece_size);
if (piece_size_usize == 0) return 4000;
const calculated = MAX_QUEUED_RESPONSE_BYTES / piece_size_usize;
return @min(4000, @max(64, calculated));
if (piece_size == 0) return 4000;
const calculated: u64 = MAX_QUEUED_RESPONSE_BYTES / piece_size;
const clamped = @min(@as(u64, 4000), @max(@as(u64, 64), calculated));
return @intCast(clamped);
}
/// Count only piece_data messages in the queue (the memory-heavy ones).
@@ -3454,7 +3466,7 @@ pub const FileSharingManager = struct {
.message_id = 0,
.peer_id = &peer_id,
.data = &reject_payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
_ = sender.sendMessage(reject_msg) catch {};
}
@@ -3636,7 +3648,7 @@ pub const FileSharingManager = struct {
// ASYNC VERIFICATION: Do disk write FIRST, then queue verification.
// This allows parallel verification while writes complete atomically via pwrite.
// Using pwrite allows concurrent writes without holding mutex during I/O
var write_file: std.fs.File = undefined;
var write_file: filesystem.File = undefined;
var absolute_offset: u64 = undefined;
var write_file_path: []const u8 = undefined;
{
@@ -3890,7 +3902,7 @@ pub const FileSharingManager = struct {
};
}
session.status = .completed;
session.updated_at = std.time.timestamp();
session.updated_at = platform_time.timestamp();
std.log.info("Download completed! All {d} pieces verified", .{dm.state.piece_count});
// CASCADE FIX: Mark for full bitfield broadcast
download_completed = true;
@@ -4239,7 +4251,7 @@ pub const FileSharingManager = struct {
.offset = piece_offset,
.length = piece_size_u32,
.priority = .normal,
.requested_at = std.time.timestamp(),
.requested_at = platform_time.timestamp(),
// Use zero peer_id so a different peer will be selected
.peer_id = [_]u8{0} ** 32,
};
@@ -4525,7 +4537,7 @@ pub const FileSharingManager = struct {
.offset = 0,
.length = @intCast(dm.piece_size),
.priority = .high,
.requested_at = std.time.timestamp(),
.requested_at = platform_time.timestamp(),
}) catch continue;
pieces_requeued += 1;
@@ -4570,7 +4582,7 @@ pub const FileSharingManager = struct {
else
self.config.piece_size;
existing.download_manager = download_mod.DownloadManager.init(
var dm = download_mod.DownloadManager.init(
metadata.size,
metadata.piece_count,
.rarest_first,
@@ -4580,6 +4592,8 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err});
return err;
};
dm.content_hash = existing.content_hash;
existing.download_manager = dm;
}
return;
}
@@ -4593,7 +4607,7 @@ pub const FileSharingManager = struct {
// content_hash already computed above for session lookup - reuse it
var session = FileSharingSession{
.session_id = std.crypto.random.int(u64),
.session_id = platform_random.int(u64),
.file_metadata = metadata,
.content_hash = content_hash,
.download_manager = null,
@@ -4601,8 +4615,8 @@ pub const FileSharingManager = struct {
.status = .ready,
.transfer_protocol = transfer_mod.TransferProtocol.init(self.allocator),
.piece_pool = PiecePool.init(self.allocator),
.created_at = std.time.timestamp(),
.updated_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.updated_at = platform_time.timestamp(),
.allocator = self.allocator,
.response_tracker = null, // Download sessions don't need response tracking
.pending_piece_responses = .{}, // ZERO-COPY: Initialize empty
@@ -4614,7 +4628,7 @@ pub const FileSharingManager = struct {
else
self.config.piece_size;
session.download_manager = download_mod.DownloadManager.init(
var new_dm = download_mod.DownloadManager.init(
metadata.size,
metadata.piece_count,
.rarest_first,
@@ -4624,12 +4638,14 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err});
return err;
};
new_dm.content_hash = session.content_hash;
session.download_manager = new_dm;
// Store session
self.sessions.put(session.session_id, session) catch |err| {
std.log.err("Failed to store session: {}", .{err});
if (session.download_manager) |*dm| {
dm.deinit();
if (session.download_manager) |*cleanup_dm| {
cleanup_dm.deinit();
}
return err;
};
@@ -5013,12 +5029,12 @@ pub const SessionStats = struct {
/// Get session age in seconds
pub fn getAge(self: SessionStats) i64 {
return std.time.timestamp() - self.created_at;
return platform_time.timestamp() - self.created_at;
}
/// Get time since last update
pub fn getTimeSinceUpdate(self: SessionStats) i64 {
return std.time.timestamp() - self.updated_at;
return platform_time.timestamp() - self.updated_at;
}
/// Get formatted status string
@@ -5196,7 +5212,7 @@ pub const FileSharingEvent = struct {
return FileSharingEvent{
.event_type = event_type,
.session_id = session_id,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
.data = data,
};
}
@@ -5250,7 +5266,7 @@ test "file sharing session creation" {
test "file sharing manager basic operations" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var manager = try FileSharingManager.init(config, allocator);
var manager = try FileSharingManager.initForTesting(config, allocator);
defer manager.deinit();
// Test initial stats
@@ -5268,7 +5284,7 @@ test "file sharing manager basic operations" {
test "file sharing manager processing" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var manager = try FileSharingManager.init(config, allocator);
var manager = try FileSharingManager.initForTesting(config, allocator);
defer manager.deinit();
// Process empty manager (should not crash)
@@ -5291,8 +5307,8 @@ test "session statistics formatting" {
.file_size = 1024 * 1024,
.piece_count = 10,
.pieces_completed = 6,
.created_at = std.time.timestamp() - 3600, // 1 hour ago
.updated_at = std.time.timestamp() - 300, // 5 minutes ago
.created_at = platform_time.timestamp() - 3600, // 1 hour ago
.updated_at = platform_time.timestamp() - 300, // 5 minutes ago
};
try testing.expectEqual(@as(i64, 3600), stats.getAge());
@@ -5527,7 +5543,7 @@ test "handlePieceData rejects bad hash and blacklists peer" {
test "blacklisted peer cannot send pieces" {
const allocator = testing.allocator;
const config = FileSharingConfig.default();
var manager = try FileSharingManager.init(config, allocator);
var manager = try FileSharingManager.initForTesting(config, allocator);
defer manager.deinit();
const peer_id: [32]u8 = [_]u8{77} ** 32;
@@ -5536,7 +5552,7 @@ test "blacklisted peer cannot send pieces" {
manager.reputation_mutex.lock();
var rep = PeerReputation.init(peer_id);
rep.bad_pieces = 3;
rep.blacklisted_until = std.time.timestamp() + 1000; // Blacklisted for future
rep.blacklisted_until = platform_time.timestamp() + 1000; // Blacklisted for future
try manager.peer_reputation.put(peer_id, rep);
manager.reputation_mutex.unlock();
@@ -5768,7 +5784,7 @@ test "PeerReputation: reset clears all state" {
rep.bad_pieces = 5;
rep.good_pieces = 10;
rep.blacklisted_until = std.time.timestamp() + 1000;
rep.blacklisted_until = platform_time.timestamp() + 1000;
rep.reset();
@@ -5825,7 +5841,7 @@ test "NetworkSender: sendMessage with mock callback" {
.message_id = 1,
.peer_id = &peer_id,
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = try sender.sendMessage(msg);
@@ -5849,7 +5865,7 @@ test "NetworkSender: sendMessage failure" {
.message_id = 1,
.peer_id = &peer_id,
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = try sender.sendMessage(msg);
@@ -5878,8 +5894,8 @@ test "FileSharingSession: status transitions" {
.size = 1024,
.piece_count = 4,
.piece_hashes = &[_]PieceHash{},
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.modified_at = platform_time.timestamp(),
};
var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator);
@@ -5904,8 +5920,8 @@ test "FileSharingSession: update timestamp" {
.size = 1024,
.piece_count = 4,
.piece_hashes = &[_]PieceHash{},
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.modified_at = platform_time.timestamp(),
};
var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator);
@@ -6170,8 +6186,8 @@ test "SessionStats: utility methods" {
.file_size = 1024,
.piece_count = 4,
.pieces_completed = 2,
.created_at = std.time.timestamp() - 100,
.updated_at = std.time.timestamp() - 50,
.created_at = platform_time.timestamp() - 100,
.updated_at = platform_time.timestamp() - 50,
};
// Test getAge

View File

@@ -18,6 +18,7 @@
//! ```
const std = @import("std");
const platform_time = @import("platform").time;
const Allocator = std.mem.Allocator;
/// Error types for MockFS operations
@@ -47,8 +48,8 @@ pub const MockFile = struct {
return .{
.allocator = allocator,
.data = &[_]u8{},
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.modified_at = platform_time.timestamp(),
};
}
@@ -71,7 +72,7 @@ pub const MockFile = struct {
self.allocator.free(self.data);
}
self.data = new_data;
self.modified_at = std.time.timestamp();
self.modified_at = platform_time.timestamp();
}
pub fn resize(self: *MockFile, new_size: usize) !void {
@@ -91,7 +92,7 @@ pub const MockFile = struct {
self.allocator.free(self.data);
}
self.data = new_data;
self.modified_at = std.time.timestamp();
self.modified_at = platform_time.timestamp();
}
};
@@ -149,7 +150,7 @@ pub const MockFileHandle = struct {
// Copy data
@memcpy(file.data[self.position..][0..data.len], data);
self.position += data.len;
file.modified_at = std.time.timestamp();
file.modified_at = platform_time.timestamp();
return data.len;
}
@@ -168,7 +169,7 @@ pub const MockFileHandle = struct {
// Copy data
@memcpy(file.data[off..][0..data.len], data);
file.modified_at = std.time.timestamp();
file.modified_at = platform_time.timestamp();
return data.len;
}

View File

@@ -5,6 +5,8 @@
//! file access by validating all file paths before operations.
const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const fs = std.fs;
const mem = std.mem;
@@ -61,6 +63,12 @@ pub const PathValidator = struct {
/// Returns the validated absolute path on success.
/// Caller is responsible for freeing the returned path.
fn validatePath(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 {
// On WASM, no real filesystem — path validation is a simple pattern check + dupe
if (is_wasm) {
if (mem.indexOf(u8, path, "..") != null) return PathSecurityError.PathTraversal;
return allocator.dupe(u8, path) catch return error.OutOfMemory;
}
// 1. Check for path traversal patterns
if (mem.indexOf(u8, path, "..") != null) {
return PathSecurityError.PathTraversal;
@@ -379,6 +387,12 @@ pub const PathValidator = struct {
/// the path. For maximum security, use validateAndOpenFile() and keep the
/// file handle open until done using it.
pub fn validateReadable(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 {
// On WASM, no real filesystem — just validate patterns and return dupe
if (is_wasm) {
if (mem.indexOf(u8, path, "..") != null) return PathSecurityError.PathTraversal;
return allocator.dupe(u8, path) catch return error.OutOfMemory;
}
// Use TOCTOU-safe open to validate the file
const file = try self.validateAndOpenFile(path, allocator);
file.close();
@@ -703,6 +717,12 @@ pub const PathValidator = struct {
/// could be modified by an attacker between validation and use.
/// For security-critical operations, use validateAndCreateFile() instead.
pub fn validateWritable(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 {
// On WASM, no real filesystem — just validate patterns and return dupe
if (is_wasm) {
if (!isPathSafe(path)) return PathSecurityError.PathTraversal;
return allocator.dupe(u8, path) catch return error.OutOfMemory;
}
// First, check for traversal patterns in the input
if (!isPathSafe(path)) {
return PathSecurityError.PathTraversal;
@@ -880,6 +900,13 @@ pub const PathValidator = struct {
/// Global default validator for general use
pub fn createDefaultValidator(allocator: mem.Allocator) !PathValidator {
if (is_wasm) {
// On WASM, no CWD — create a validator that accepts all paths
const allowed_dirs = try allocator.alloc([]const u8, 1);
allowed_dirs[0] = try allocator.dupe(u8, "/");
return PathValidator.init(allowed_dirs);
}
// Get current working directory as default allowed directory
const cwd = try fs.cwd().realpathAlloc(allocator, ".");

View File

@@ -4,6 +4,8 @@
//! Bandwidth-Delay Product (BDP) measurements.
const std = @import("std");
const platform_time = @import("platform").time;
const Mutex = @import("sync").Mutex;
const core = @import("core");
const Error = core.errors.Error;
@@ -69,7 +71,7 @@ pub const PeerMetrics = struct {
var metrics = PeerMetrics{
.peer_id = peer_id,
.piece_size = piece_size,
.last_bandwidth_calc_ns = std.time.nanoTimestamp(),
.last_bandwidth_calc_ns = platform_time.nanoTimestamp(),
};
metrics.recalculateBdp();
return metrics;
@@ -77,13 +79,13 @@ pub const PeerMetrics = struct {
/// Record a request being sent (for RTT measurement)
pub fn recordRequestSent(self: *PeerMetrics) void {
self.last_request_time_ns = std.time.nanoTimestamp();
self.last_request_time_ns = platform_time.nanoTimestamp();
self.current_pending += 1;
}
/// Record a response received with timing for RTT calculation
pub fn recordResponseReceived(self: *PeerMetrics, bytes: u64, success: bool) void {
const now = std.time.nanoTimestamp();
const now = platform_time.nanoTimestamp();
if (self.current_pending > 0) {
self.current_pending -= 1;
@@ -270,7 +272,7 @@ pub const PeerMetricsManager = struct {
/// Allocator
allocator: std.mem.Allocator,
/// Mutex for thread safety
mutex: std.Thread.Mutex = .{},
mutex: Mutex = .{},
pub fn init(allocator: std.mem.Allocator, piece_size: u64) PeerMetricsManager {
return .{

View File

@@ -4,6 +4,7 @@
//! rarest-first, random, and sequential algorithms for optimal P2P distribution.
const std = @import("std");
const platform_time = @import("platform").time;
const testing = std.testing;
const mem = std.mem;
const math = std.math;
@@ -219,7 +220,7 @@ pub const PieceSelector = struct {
/// Mark piece as starting download
pub fn startDownload(self: *PieceSelector, piece_index: u32) Error!void {
if (self.canStartDownload(piece_index)) {
try self.active_downloads.put(piece_index, std.time.timestamp());
try self.active_downloads.put(piece_index, platform_time.timestamp());
} else {
return Error.RateLimited;
}

View File

@@ -7,7 +7,9 @@
//! disk I/O operations by reusing buffers instead of allocating new ones.
const std = @import("std");
const atomic = std.atomic;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const mem = std.mem;
const core = @import("core");
@@ -57,14 +59,14 @@ pub const PieceBufferPool = struct {
/// Free list using indices (thread-safe via mutex)
free_stack: std.ArrayList(usize),
mutex: std.Thread.Mutex,
mutex: Mutex,
/// Statistics
acquired_count: atomic.Value(u64),
released_count: atomic.Value(u64),
fallback_count: atomic.Value(u64),
pool_hits: atomic.Value(u64),
pool_misses: atomic.Value(u64),
acquired_count: AtomicValue(u64),
released_count: AtomicValue(u64),
fallback_count: AtomicValue(u64),
pool_hits: AtomicValue(u64),
pool_misses: AtomicValue(u64),
pub fn init(allocator: mem.Allocator, config: PieceBufferPoolConfig) Error!PieceBufferPool {
// Allocate buffer pointer array
@@ -107,11 +109,11 @@ pub const PieceBufferPool = struct {
.buffers = buffers,
.free_stack = free_stack,
.mutex = .{},
.acquired_count = atomic.Value(u64).init(0),
.released_count = atomic.Value(u64).init(0),
.fallback_count = atomic.Value(u64).init(0),
.pool_hits = atomic.Value(u64).init(0),
.pool_misses = atomic.Value(u64).init(0),
.acquired_count = AtomicValue(u64).init(0),
.released_count = AtomicValue(u64).init(0),
.fallback_count = AtomicValue(u64).init(0),
.pool_hits = AtomicValue(u64).init(0),
.pool_misses = AtomicValue(u64).init(0),
};
}

View File

@@ -21,9 +21,14 @@
//! ```
const std = @import("std");
const atomic = std.atomic;
const platform_time = @import("platform").time;
const builtin = @import("builtin");
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const mem = std.mem;
const Thread = std.Thread;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core");
const Error = core.errors.Error;
@@ -96,24 +101,24 @@ pub const PiecePipeline = struct {
/// Task queue
task_queue: std.ArrayList(PieceTask),
queue_mutex: Thread.Mutex,
queue_not_empty: Thread.Condition,
queue_mutex: Mutex,
queue_not_empty: if (is_wasm) void else std.Thread.Condition,
/// Worker threads
workers: std.ArrayList(Thread),
workers: if (is_wasm) void else std.ArrayList(std.Thread),
/// Shutdown flag
shutdown: atomic.Value(bool),
shutdown: AtomicValue(bool),
/// Callbacks for piece processing
callbacks: ?PipelineCallbacks,
/// Statistics
tasks_queued: atomic.Value(u64),
tasks_processed: atomic.Value(u64),
tasks_failed: atomic.Value(u64),
queue_full_count: atomic.Value(u64),
total_queue_wait_ns: atomic.Value(u64),
tasks_queued: AtomicValue(u64),
tasks_processed: AtomicValue(u64),
tasks_failed: AtomicValue(u64),
queue_full_count: AtomicValue(u64),
total_queue_wait_ns: AtomicValue(u64),
pub fn init(allocator: mem.Allocator, config: PiecePipelineConfig) PiecePipeline {
return .{
@@ -121,15 +126,15 @@ pub const PiecePipeline = struct {
.config = config,
.task_queue = .{},
.queue_mutex = .{},
.queue_not_empty = .{},
.workers = .{},
.shutdown = atomic.Value(bool).init(false),
.queue_not_empty = if (is_wasm) {} else .{},
.workers = if (is_wasm) {} else .{},
.shutdown = AtomicValue(bool).init(false),
.callbacks = null,
.tasks_queued = atomic.Value(u64).init(0),
.tasks_processed = atomic.Value(u64).init(0),
.tasks_failed = atomic.Value(u64).init(0),
.queue_full_count = atomic.Value(u64).init(0),
.total_queue_wait_ns = atomic.Value(u64).init(0),
.tasks_queued = AtomicValue(u64).init(0),
.tasks_processed = AtomicValue(u64).init(0),
.tasks_failed = AtomicValue(u64).init(0),
.queue_full_count = AtomicValue(u64).init(0),
.total_queue_wait_ns = AtomicValue(u64).init(0),
};
}
@@ -141,7 +146,7 @@ pub const PiecePipeline = struct {
task.deinit();
}
self.task_queue.deinit(self.allocator);
self.workers.deinit(self.allocator);
if (!is_wasm) self.workers.deinit(self.allocator);
}
/// Set the callbacks for piece processing
@@ -149,20 +154,22 @@ pub const PiecePipeline = struct {
self.callbacks = callbacks;
}
/// Start worker threads
/// Start worker threads (no-op on WASM — use processSynchronously instead)
pub fn start(self: *PiecePipeline) Error!void {
if (self.callbacks == null) {
return Error.InvalidState;
}
if (is_wasm) return;
const num_workers = if (self.config.num_workers == 0)
@as(u32, @intCast(@max(1, Thread.getCpuCount() catch 4)))
@as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4)))
else
self.config.num_workers;
var i: u32 = 0;
while (i < num_workers) : (i += 1) {
const thread = Thread.spawn(.{}, workerLoop, .{self}) catch {
const thread = std.Thread.spawn(.{}, workerLoop, .{self}) catch {
return Error.InvalidState;
};
self.workers.append(self.allocator, thread) catch {
@@ -171,8 +178,10 @@ pub const PiecePipeline = struct {
}
}
/// Stop all worker threads
/// Stop all worker threads (no-op on WASM)
pub fn stop(self: *PiecePipeline) void {
if (is_wasm) return;
self.shutdown.store(true, .release);
// Wake up all workers
@@ -187,6 +196,42 @@ pub const PiecePipeline = struct {
self.workers.clearRetainingCapacity();
}
/// Process up to `max_tasks` pending pieces synchronously.
/// For WASM: call this from the update loop since threads are unavailable.
/// On native: this can also be used for single-threaded operation.
pub fn processSynchronously(self: *PiecePipeline, max_tasks: u32) void {
const cb = self.callbacks orelse return;
var processed: u32 = 0;
while (processed < max_tasks) : (processed += 1) {
// Dequeue a task
var task: PieceTask = undefined;
{
self.queue_mutex.lock();
defer self.queue_mutex.unlock();
if (self.task_queue.items.len == 0) break;
task = self.task_queue.orderedRemove(0);
}
defer task.deinit();
// Track queue wait time
const wait_ns: u64 = @intCast(@max(0, platform_time.nanoTimestamp() - task.queued_at));
_ = self.total_queue_wait_ns.fetchAdd(wait_ns, .monotonic);
cb.processPiece(
task.peer_id,
task.content_hash,
task.piece_index,
task.offset,
task.data,
) catch {
_ = self.tasks_failed.fetchAdd(1, .monotonic);
continue;
};
_ = self.tasks_processed.fetchAdd(1, .monotonic);
}
}
/// Queue a piece for processing (non-blocking for caller)
/// The data is COPIED - caller can free their copy after this returns
pub fn queuePiece(
@@ -222,14 +267,14 @@ pub const PiecePipeline = struct {
.offset = offset,
.data = data_copy,
.allocator = self.allocator,
.queued_at = std.time.nanoTimestamp(),
.queued_at = platform_time.nanoTimestamp(),
}) catch {
self.allocator.free(data_copy);
return Error.OutOfMemory;
};
_ = self.tasks_queued.fetchAdd(1, .monotonic);
self.queue_not_empty.signal();
if (!is_wasm) self.queue_not_empty.signal();
}
/// Get current queue depth
@@ -287,7 +332,7 @@ pub const PiecePipeline = struct {
defer t.deinit();
// Track queue wait time
const wait_ns: u64 = @intCast(@max(0, std.time.nanoTimestamp() - t.queued_at));
const wait_ns: u64 = @intCast(@max(0, platform_time.nanoTimestamp() - t.queued_at));
_ = self.total_queue_wait_ns.fetchAdd(wait_ns, .monotonic);
// Process the piece via callback
@@ -364,7 +409,7 @@ test "piece pipeline basic operations" {
const TestContext = struct {
processed_count: u32 = 0,
mutex: Thread.Mutex = .{},
mutex: Mutex = .{},
};
var ctx = TestContext{};

View File

@@ -4,6 +4,9 @@
//! message exchange, and coordination between download and upload operations.
const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const AtomicValue = @import("sync").AtomicValue;
const testing = std.testing;
const mem = std.mem;
const fmt = std.fmt;
@@ -132,7 +135,7 @@ pub const PreSerializedPieceData = struct {
offset += 1;
// Message ID (4 bytes, big endian)
const msg_id = std.crypto.random.int(u32);
const msg_id = platform_random.int(u32);
@memcpy(result.header[offset..][0..4], &std.mem.toBytes(std.mem.nativeToBig(u32, msg_id)));
offset += 4;
@@ -142,7 +145,7 @@ pub const PreSerializedPieceData = struct {
offset += 2;
// Timestamp (8 bytes, big endian)
const timestamp = std.time.timestamp();
const timestamp = platform_time.timestamp();
@memcpy(result.header[offset..][0..8], &std.mem.toBytes(std.mem.nativeToBig(i64, timestamp)));
offset += 8;
@@ -345,7 +348,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const payload = fmt.allocPrint(allocator, "HANDshake {s} {s}", .{ peer_id, client_id }) catch {
@@ -355,16 +358,16 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
return TransferMessage{
.message_type = .handshake,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -376,7 +379,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const payload = allocator.alloc(u8, 32) catch {
@@ -386,17 +389,17 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@memcpy(payload, &file_hash);
return TransferMessage{
.message_type = .metadata_request,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -409,7 +412,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Serialize metadata: name_len(2) + name + size(8) + piece_count(4) + created_at(8) + modified_at(8) + piece_hashes
@@ -423,7 +426,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -436,7 +439,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -475,10 +478,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .metadata_response,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -564,7 +567,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Payload format: content_hash(32) + piece_index(4) + offset(4) = 40 bytes
@@ -575,7 +578,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -588,10 +591,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .piece_request,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -612,7 +615,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -621,7 +624,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Payload: content_hash(32) + count(2) + indices(4 * count)
@@ -633,7 +636,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -647,10 +650,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .batch_piece_request,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -686,7 +689,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const payload = allocator.alloc(u8, 9) catch {
@@ -696,7 +699,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -706,10 +709,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .piece_response,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -724,7 +727,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Combine piece index, data, and hash
@@ -738,7 +741,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -753,10 +756,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .piece_data,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -769,7 +772,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const payload = allocator.alloc(u8, 8) catch {
@@ -779,7 +782,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -788,10 +791,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .cancel_request,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -805,7 +808,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Calculate bitfield size: ceil(piece_count / 8)
@@ -819,7 +822,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -839,10 +842,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .bitfield,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -855,7 +858,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const bitfield_bytes = (piece_count + 7) / 8;
@@ -868,7 +871,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -886,10 +889,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .bitfield,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -903,7 +906,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Format: content_hash(32) + piece_index(4)
@@ -914,7 +917,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
@@ -923,10 +926,10 @@ pub const TransferMessage = struct {
return TransferMessage{
.message_type = .have,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = payload,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
@@ -982,7 +985,7 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{}, // Empty slice to avoid freeing invalid memory
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const owned_data = allocator.dupe(u8, error_text) catch {
@@ -992,22 +995,22 @@ pub const TransferMessage = struct {
.message_id = 0,
.peer_id = &[_]u8{},
.data = &[_]u8{},
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
};
return TransferMessage{
.message_type = .err,
.message_id = std.crypto.random.int(u32),
.message_id = platform_random.int(u32),
.peer_id = owned_peer_id,
.data = owned_data,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
}
/// Check if message has expired
pub fn isExpired(self: TransferMessage, timeout_seconds: i64) bool {
return std.time.timestamp() - self.timestamp > timeout_seconds;
return platform_time.timestamp() - self.timestamp > timeout_seconds;
}
};
@@ -1060,7 +1063,7 @@ pub const TransferSession = struct {
const content_hash = HashUtils.contentHash(file_metadata.piece_hashes) catch return Error.HashComputationFailed;
return TransferSession{
.session_id = std.crypto.random.int(u64),
.session_id = platform_random.int(u64),
.peer_id = peer_id,
.file_metadata = file_metadata,
.content_hash = content_hash,
@@ -1069,8 +1072,8 @@ pub const TransferSession = struct {
.peer_capabilities = PeerCapabilities.init(allocator),
.progress_tracker = ProgressTracker.init(file_metadata.size),
.rate_limiter = RateLimiter.init(),
.created_at = std.time.timestamp(),
.last_activity = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.last_activity = platform_time.timestamp(),
// IMP-M2 FIX: Initialize received piece hashes map
.received_piece_hashes = std.AutoHashMap(u32, PieceHash).init(allocator),
.allocator = allocator,
@@ -1085,12 +1088,12 @@ pub const TransferSession = struct {
/// Update last activity timestamp
pub fn updateActivity(self: *TransferSession) void {
self.last_activity = std.time.timestamp();
self.last_activity = platform_time.timestamp();
}
/// Check if session is active
pub fn isActive(self: *TransferSession, timeout_seconds: i64) bool {
return std.time.timestamp() - self.last_activity < timeout_seconds;
return platform_time.timestamp() - self.last_activity < timeout_seconds;
}
/// Get transfer progress
@@ -1294,8 +1297,8 @@ pub const TransferProtocol = struct {
.size = 0,
.piece_count = 0,
.piece_hashes = empty_hashes,
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
.created_at = platform_time.timestamp(),
.modified_at = platform_time.timestamp(),
};
const session = TransferSession.create(peer_id, metadata, self.allocator) catch return Error.OutOfMemory;
@@ -2135,16 +2138,16 @@ pub const TransferStats = struct {
pub const RateLimiter = struct {
max_bandwidth_bps: u64,
max_concurrent_transfers: usize,
current_bandwidth: std.atomic.Value(u64),
active_transfers: std.atomic.Value(usize),
current_bandwidth: AtomicValue(u64),
active_transfers: AtomicValue(usize),
/// Initialize with custom bandwidth limits
pub fn initWithLimits(max_bandwidth_bps: u64, max_concurrent_transfers: usize) RateLimiter {
return RateLimiter{
.max_bandwidth_bps = max_bandwidth_bps,
.max_concurrent_transfers = max_concurrent_transfers,
.current_bandwidth = std.atomic.Value(u64).init(0),
.active_transfers = std.atomic.Value(usize).init(0),
.current_bandwidth = AtomicValue(u64).init(0),
.active_transfers = AtomicValue(usize).init(0),
};
}
@@ -2229,18 +2232,18 @@ pub const RateLimiter = struct {
/// Progress tracker for transfers
pub const ProgressTracker = struct {
total_bytes: u64,
downloaded_bytes: std.atomic.Value(u64),
uploaded_bytes: std.atomic.Value(u64),
downloaded_bytes: AtomicValue(u64),
uploaded_bytes: AtomicValue(u64),
start_time: i64,
last_update: std.atomic.Value(i64),
last_update: AtomicValue(i64),
pub fn init(total_bytes: u64) ProgressTracker {
return ProgressTracker{
.total_bytes = total_bytes,
.downloaded_bytes = std.atomic.Value(u64).init(0),
.uploaded_bytes = std.atomic.Value(u64).init(0),
.start_time = std.time.timestamp(),
.last_update = std.atomic.Value(i64).init(std.time.timestamp()),
.downloaded_bytes = AtomicValue(u64).init(0),
.uploaded_bytes = AtomicValue(u64).init(0),
.start_time = platform_time.timestamp(),
.last_update = AtomicValue(i64).init(platform_time.timestamp()),
};
}
@@ -2248,14 +2251,14 @@ pub const ProgressTracker = struct {
/// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern
pub fn updateDownload(self: *ProgressTracker, bytes: u64) void {
_ = self.downloaded_bytes.fetchAdd(bytes, .monotonic);
self.last_update.store(std.time.timestamp(), .monotonic);
self.last_update.store(platform_time.timestamp(), .monotonic);
}
/// Update uploaded bytes
/// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern
pub fn updateUpload(self: *ProgressTracker, bytes: u64) void {
_ = self.uploaded_bytes.fetchAdd(bytes, .monotonic);
self.last_update.store(std.time.timestamp(), .monotonic);
self.last_update.store(platform_time.timestamp(), .monotonic);
}
/// Add uploaded bytes (alias for updateUpload)
@@ -2279,7 +2282,7 @@ pub const ProgressTracker = struct {
/// Get download speed in bytes per second
pub fn getDownloadSpeed(self: *ProgressTracker) f32 {
const now = std.time.timestamp();
const now = platform_time.timestamp();
const elapsed = now - self.start_time;
if (elapsed <= 0) return 0.0;
@@ -2289,7 +2292,7 @@ pub const ProgressTracker = struct {
/// Get upload speed in bytes per second
pub fn getUploadSpeed(self: *ProgressTracker) f32 {
const now = std.time.timestamp();
const now = platform_time.timestamp();
const elapsed = now - self.start_time;
if (elapsed <= 0) return 0.0;
@@ -2313,7 +2316,7 @@ pub const ProgressTracker = struct {
/// Check if transfer is stalled
pub fn isStalled(self: *ProgressTracker, timeout_seconds: i64) bool {
const now = std.time.timestamp();
const now = platform_time.timestamp();
const last_update = self.last_update.load(.monotonic);
return now - last_update > timeout_seconds;
}
@@ -2417,14 +2420,14 @@ test "transfer message expiration" {
.message_id = 12345,
.peer_id = "test_peer",
.data = "test data",
.timestamp = std.time.timestamp() - 120, // 2 minutes ago
.timestamp = platform_time.timestamp() - 120, // 2 minutes ago
};
// Message should be expired (60 second timeout)
try testing.expect(message.isExpired(60));
// Fresh message should not be expired
message.timestamp = std.time.timestamp();
message.timestamp = platform_time.timestamp();
try testing.expect(!message.isExpired(60));
}
@@ -2771,7 +2774,7 @@ test "ProgressTracker isStalled" {
try testing.expect(!tracker.isStalled(60));
// Manually set old last_update
tracker.last_update.store(std.time.timestamp() - 120, .monotonic);
tracker.last_update.store(platform_time.timestamp() - 120, .monotonic);
// Should be stalled now (120s > 60s timeout)
try testing.expect(tracker.isStalled(60));
@@ -2781,7 +2784,7 @@ test "ProgressTracker getEstimatedDownloadTimeRemaining" {
var tracker = ProgressTracker.init(1000);
// No progress yet - returns 0 (progress is 0.0, so boundary case)
tracker.start_time = std.time.timestamp() - 10;
tracker.start_time = platform_time.timestamp() - 10;
try testing.expectEqual(@as(i64, 0), tracker.getEstimatedDownloadTimeRemaining());
// With some progress
@@ -2907,7 +2910,7 @@ test "TransferProtocol handleError" {
.message_id = 1,
.peer_id = "peer1",
.data = "test error",
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
try protocol.handleMessage(error_msg);
@@ -2930,7 +2933,7 @@ test "TransferProtocol handleBandwidthUpdate" {
.message_id = 1,
.peer_id = "peer1",
.data = "",
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
// Should succeed since session exists (even without upload manager)
@@ -2957,7 +2960,7 @@ test "TransferProtocol handleTransferComplete" {
.message_id = 1,
.peer_id = "peer1",
.data = "",
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
try protocol.handleMessage(complete_msg);
@@ -3059,7 +3062,7 @@ test "TransferProtocol popMessagesFair prioritizes requests" {
.message_id = 1,
.peer_id = response_peer_id,
.data = response_data,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
try protocol.pending_responses.append(allocator, response_msg);
@@ -3071,7 +3074,7 @@ test "TransferProtocol popMessagesFair prioritizes requests" {
.message_id = 2,
.peer_id = request_peer_id,
.data = request_data,
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
try protocol.pending_requests.append(allocator, request_msg);
@@ -3123,7 +3126,7 @@ test "TransferProtocol handleHandshake invalid format" {
.message_id = 1,
.peer_id = "peer",
.data = "short",
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(short_msg);
@@ -3140,7 +3143,7 @@ test "TransferProtocol handleHandshake invalid prefix" {
.message_id = 1,
.peer_id = "peer",
.data = "INVALID peer1 client1",
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(bad_msg);
@@ -3158,7 +3161,7 @@ test "TransferProtocol handleHandshake invalid characters" {
.message_id = 1,
.peer_id = "peer",
.data = "HANDshake peer@invalid client1",
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(bad_msg);
@@ -3175,7 +3178,7 @@ test "TransferProtocol handleCancelRequest invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(cancel_msg);
@@ -3192,7 +3195,7 @@ test "TransferProtocol handlePieceRequest invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short (needs 16 bytes)
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(piece_req);
@@ -3209,7 +3212,7 @@ test "TransferProtocol handlePieceResponse invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short (needs 9 bytes)
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(piece_resp);
@@ -3226,7 +3229,7 @@ test "TransferProtocol handlePieceData invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short (needs 36 bytes minimum)
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(piece_data_msg);
@@ -3243,7 +3246,7 @@ test "TransferProtocol handlePieceHash invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short (needs 36 bytes)
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(piece_hash_msg);
@@ -3260,7 +3263,7 @@ test "TransferProtocol handleUploadRequest invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short (needs 48 bytes)
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(upload_req);
@@ -3277,7 +3280,7 @@ test "TransferProtocol handleBitfield invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "ab", // Too short
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(bitfield_msg);
@@ -3294,7 +3297,7 @@ test "TransferProtocol handleHave invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "ab", // Too short (needs 4 bytes)
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(have_msg);
@@ -3311,7 +3314,7 @@ test "TransferProtocol handleBatchPieceRequest invalid data" {
.message_id = 1,
.peer_id = "peer",
.data = "short", // Too short
.timestamp = std.time.timestamp(),
.timestamp = platform_time.timestamp(),
};
const result = protocol.handleMessage(batch_req);

View File

@@ -4,9 +4,14 @@
//! bandwidth allocation, and upload rate limiting.
const std = @import("std");
const platform_time = @import("platform").time;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const testing = std.testing;
const mem = std.mem;
const atomic = std.atomic;
const fmt = std.fmt;
const core = @import("core");
@@ -14,6 +19,8 @@ const Error = core.errors.Error;
const hash_mod = @import("hash.zig");
const PieceHash = hash_mod.PieceHash;
const HashUtils = hash_mod.HashUtils;
const filesystem = @import("filesystem.zig");
const FileSystem = filesystem.FileSystem;
const file_mod = @import("file.zig");
const FileChunker = file_mod.FileChunker;
const MappedFile = file_mod.MappedFile;
@@ -97,7 +104,7 @@ pub const UploadRequest = struct {
.offset = offset,
.length = length,
.peer_id = peer_id_owned,
.requested_at = std.time.timestamp(),
.requested_at = platform_time.timestamp(),
.priority = priority,
.request_id = 0,
.file_hash = [_]u8{0} ** 32,
@@ -123,7 +130,7 @@ pub const UploadRequest = struct {
.offset = offset,
.length = length,
.peer_id = peer_id_owned,
.requested_at = std.time.timestamp(),
.requested_at = platform_time.timestamp(),
.priority = priority,
.request_id = request_id,
.file_hash = file_hash,
@@ -132,7 +139,7 @@ pub const UploadRequest = struct {
/// Check if request has expired
pub fn isExpired(self: UploadRequest, timeout_seconds: i64) bool {
return std.time.timestamp() - self.requested_at > timeout_seconds;
return platform_time.timestamp() - self.requested_at > timeout_seconds;
}
/// Get request score for prioritization
@@ -143,7 +150,7 @@ pub const UploadRequest = struct {
score += @as(i32, @intFromEnum(self.priority)) * 100;
// Time waited boost (older requests get higher score)
const time_waited = std.time.timestamp() - self.requested_at;
const time_waited = platform_time.timestamp() - self.requested_at;
score += @as(i32, @intCast(@min(time_waited, 300))); // Max 5 minutes boost
return score;
@@ -161,26 +168,26 @@ pub const UploadRequest = struct {
/// This is acceptable for statistics tracking where eventual consistency is
/// sufficient. If strict transactional semantics are needed, use a mutex.
pub const UploadState = struct {
total_uploaded: atomic.Value(u64),
active_uploads: atomic.Value(u32),
completed_uploads: atomic.Value(u32),
failed_uploads: atomic.Value(u32),
total_uploaded: AtomicValue(u64),
active_uploads: AtomicValue(u32),
completed_uploads: AtomicValue(u32),
failed_uploads: AtomicValue(u32),
/// IMP-M4 FIX: Track cancelled uploads separately
cancelled_count: atomic.Value(u32),
cancelled_count: AtomicValue(u32),
start_time: i64,
upload_bandwidth: atomic.Value(u64), // Current bandwidth usage
upload_bandwidth: AtomicValue(u64), // Current bandwidth usage
max_bandwidth: u64, // Maximum allowed bandwidth
pub fn init(max_bandwidth: u64) UploadState {
return UploadState{
.total_uploaded = atomic.Value(u64).init(0),
.active_uploads = atomic.Value(u32).init(0),
.completed_uploads = atomic.Value(u32).init(0),
.failed_uploads = atomic.Value(u32).init(0),
.total_uploaded = AtomicValue(u64).init(0),
.active_uploads = AtomicValue(u32).init(0),
.completed_uploads = AtomicValue(u32).init(0),
.failed_uploads = AtomicValue(u32).init(0),
// IMP-M4 FIX: Initialize cancelled counter
.cancelled_count = atomic.Value(u32).init(0),
.start_time = std.time.timestamp(),
.upload_bandwidth = atomic.Value(u64).init(0),
.cancelled_count = AtomicValue(u32).init(0),
.start_time = platform_time.timestamp(),
.upload_bandwidth = AtomicValue(u64).init(0),
.max_bandwidth = max_bandwidth,
};
}
@@ -242,7 +249,7 @@ pub const UploadState = struct {
/// Get upload speed (bytes per second)
/// Uses .acquire to ensure we see latest upload counts.
pub fn getUploadSpeed(self: *UploadState) f32 {
const elapsed = std.time.timestamp() - self.start_time;
const elapsed = platform_time.timestamp() - self.start_time;
if (elapsed <= 0) return 0.0;
const uploaded = self.total_uploaded.load(.acquire);
@@ -287,20 +294,20 @@ pub const NetworkSender = *const fn (peer_id: []const u8, data: []const u8, cont
/// MED-8 FIX: Made thread-safe with proper atomic operations
pub const BandwidthLimiter = struct {
/// MED-8 FIX: max_bandwidth is now atomic to prevent torn reads/writes
max_bandwidth: atomic.Value(u64),
current_bandwidth: atomic.Value(u64),
max_bandwidth: AtomicValue(u64),
current_bandwidth: AtomicValue(u64),
time_window: i64, // Time window for bandwidth calculation (seconds)
last_reset: atomic.Value(i64),
last_reset: AtomicValue(i64),
/// MED-8 FIX: Mutex to coordinate checkAndReset across threads
reset_mutex: std.Thread.Mutex = .{},
reset_mutex: Mutex = .{},
allocator: mem.Allocator,
pub fn init(max_bandwidth: u64, time_window: i64, allocator: mem.Allocator) BandwidthLimiter {
return BandwidthLimiter{
.max_bandwidth = atomic.Value(u64).init(max_bandwidth),
.current_bandwidth = atomic.Value(u64).init(0),
.max_bandwidth = AtomicValue(u64).init(max_bandwidth),
.current_bandwidth = AtomicValue(u64).init(0),
.time_window = time_window,
.last_reset = atomic.Value(i64).init(std.time.timestamp()),
.last_reset = AtomicValue(i64).init(platform_time.timestamp()),
.reset_mutex = .{},
.allocator = allocator,
};
@@ -406,7 +413,7 @@ pub const BandwidthLimiter = struct {
/// Reset bandwidth usage if time window has passed
/// MED-8 FIX: Uses mutex to prevent torn state from concurrent resets
fn checkAndReset(self: *BandwidthLimiter) void {
const now = std.time.timestamp();
const now = platform_time.timestamp();
const last_reset_time = self.last_reset.load(.acquire);
if (now - last_reset_time >= self.time_window) {
@@ -449,7 +456,7 @@ pub const UploadManager = struct {
/// Total file size for boundary checking
file_size: u64,
/// PERF FIX: Cached file handle to avoid open/close per piece
cached_file: ?std.fs.File,
cached_file: ?filesystem.File,
/// PERF: Memory-mapped file for zero-copy reads (used for large files)
mapped_file: ?MappedFile,
/// Network sender callback for transmitting data
@@ -459,7 +466,7 @@ pub const UploadManager = struct {
/// Message serializer for encoding protocol messages
message_serializer: serializer.MessageSerializer,
/// Mutex protecting all hashmaps and lists
manager_mutex: std.Thread.Mutex = .{},
manager_mutex: Mutex = .{},
pub fn init(
max_bandwidth: u64,
@@ -519,8 +526,8 @@ pub const UploadManager = struct {
}
// Close any existing cached file handle
if (self.cached_file) |file| {
file.close();
if (self.cached_file != null) {
self.cached_file.?.close();
self.cached_file = null;
}
@@ -536,7 +543,7 @@ pub const UploadManager = struct {
// PERF FIX: Open and cache the file handle for all future reads
// This is needed even when mmap is used, for fallback and getReadInfo() compatibility
self.cached_file = std.fs.cwd().openFile(file_path, .{}) catch |err| {
self.cached_file = FileSystem.openFile(file_path, .{}) catch |err| {
std.log.warn("setFilePath: failed to open file for caching: {}", .{err});
return Error.FileError;
};
@@ -544,8 +551,8 @@ pub const UploadManager = struct {
// PERF: Try to use mmap for large files (zero-copy reads)
// CASCADE FIX: Skip mmap for files being actively written - MAP_PRIVATE may
// return stale data when pages are modified via pwrite on another handle.
if (!disable_mmap and file_mod.shouldUseMmap(file_size)) {
if (MappedFile.initFromHandle(self.cached_file.?, file_size)) |mf| {
if (!is_wasm and !disable_mmap and file_mod.shouldUseMmap(file_size)) {
if (MappedFile.initFromHandle(self.cached_file.?.impl.real, file_size)) |mf| {
self.mapped_file = mf;
std.log.info("setFilePath: using mmap for {d} MB file", .{file_size / (1024 * 1024)});
} else |_| {
@@ -621,11 +628,11 @@ pub const UploadManager = struct {
// PERF FIX: Use cached file handle instead of opening file per piece
// Note: bandwidth is already consumed even if read fails (safer than over-consumption)
const cached = self.cached_file orelse {
if (self.cached_file == null) {
std.log.warn("readPieceData: no cached file handle", .{});
return Error.FileError;
};
const data = self.file_chunker.readPieceFromHandle(cached, piece_index, actual_length) catch |err| {
}
const data = self.file_chunker.readPieceFromHandle(&self.cached_file.?, piece_index, actual_length) catch |err| {
std.log.warn("readPieceData: readPieceFromHandle failed: {}", .{err});
return Error.FileError;
};
@@ -642,7 +649,7 @@ pub const UploadManager = struct {
/// PERF: Get info needed for mutex-free pread operations
/// Returns file handle and calculated absolute offset for direct pread
/// Call this while holding sessions_mutex, then release mutex and do pread directly
pub fn getReadInfo(self: *UploadManager, piece_index: u32, offset: u64, length: u32) Error!struct { file: std.fs.File, absolute_offset: u64, actual_length: u32, piece_available: bool } {
pub fn getReadInfo(self: *UploadManager, piece_index: u32, offset: u64, length: u32) Error!struct { file: filesystem.File, absolute_offset: u64, actual_length: u32, piece_available: bool } {
// Check piece availability
self.manager_mutex.lock();
const piece_available = self.available_pieces.contains(piece_index);
@@ -693,9 +700,9 @@ pub const UploadManager = struct {
// The file handle was closed by mmap deinit, clear cached_file
// to prevent double-close
self.cached_file = null;
} else if (self.cached_file) |file| {
} else if (self.cached_file != null) {
// Only close cached_file if mmap wasn't used
file.close();
self.cached_file.?.close();
self.cached_file = null;
}
// Free the owned file path copy
@@ -710,7 +717,7 @@ pub const UploadManager = struct {
const piece = AvailablePiece{
.index = piece_index,
.hash = hash,
.available_at = std.time.timestamp(),
.available_at = platform_time.timestamp(),
.upload_count = 0,
.is_verified = true,
};
@@ -827,7 +834,7 @@ pub const UploadManager = struct {
const active_upload = ActiveUpload{
.request = request,
.bytes_sent = 0,
.started_at = std.time.timestamp(),
.started_at = platform_time.timestamp(),
.status = .uploading,
};
@@ -1171,8 +1178,8 @@ fn compareUploadRequests(_: void, a: UploadRequest, b: UploadRequest) bool {
}
// Then by time waited (older first)
const time_a = std.time.timestamp() - a.requested_at;
const time_b = std.time.timestamp() - b.requested_at;
const time_a = platform_time.timestamp() - a.requested_at;
const time_b = platform_time.timestamp() - b.requested_at;
if (time_a != time_b) {
return time_a > time_b;
}
@@ -1301,7 +1308,7 @@ pub const UploadQueue = struct {
// IMP-M5 FIX: Use current time if no uploads exist
if (earliest_start == std.math.maxInt(i64)) {
earliest_start = std.time.timestamp();
earliest_start = platform_time.timestamp();
}
return CombinedUploadStats{
@@ -1329,7 +1336,7 @@ pub const CombinedUploadStats = struct {
/// Get average upload speed
/// IMP-M5 FIX: Now properly uses elapsed time for speed calculation
pub fn getAverageSpeed(self: CombinedUploadStats) f32 {
const now = std.time.timestamp();
const now = platform_time.timestamp();
const elapsed = now - self.start_time;
// IMP-M5 FIX: Guard against division by zero and negative elapsed
@@ -1341,7 +1348,7 @@ pub const CombinedUploadStats = struct {
/// Get elapsed time in seconds
pub fn getElapsedTime(self: CombinedUploadStats) i64 {
return std.time.timestamp() - self.start_time;
return platform_time.timestamp() - self.start_time;
}
};
@@ -1402,7 +1409,7 @@ test "upload request operations" {
try testing.expect(!request.isExpired(60)); // Not expired with 60s timeout
// Force expiration by setting requested_at in the past
request.requested_at = std.time.timestamp() - 10;
request.requested_at = platform_time.timestamp() - 10;
try testing.expect(request.isExpired(5)); // Expired: 10 seconds ago > 5s timeout
try testing.expect(!request.isExpired(15)); // Not expired: 10 seconds ago <= 15s timeout
}

View File

@@ -8,9 +8,15 @@
//! limits multi-peer download throughput.
const std = @import("std");
const atomic = std.atomic;
const platform_time = @import("platform").time;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const builtin = @import("builtin");
const mem = std.mem;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core");
const Error = core.errors.Error;
const hash_mod = @import("hash.zig");
@@ -97,29 +103,29 @@ pub const VerificationPool = struct {
/// Task queue for pending verifications
task_queue: std.ArrayList(VerificationTask),
task_mutex: std.Thread.Mutex,
/// Condition variable for worker wakeup
task_condition: std.Thread.Condition,
task_mutex: Mutex,
/// Condition variable for worker wakeup (not available on WASM)
task_condition: if (is_wasm) void else std.Thread.Condition,
/// Results queue (if use_results_queue is true)
results_queue: std.ArrayList(VerificationResult),
results_mutex: std.Thread.Mutex,
results_mutex: Mutex,
/// Worker threads
workers: std.ArrayList(std.Thread),
/// Worker threads (not available on WASM — use processSynchronously instead)
workers: if (is_wasm) void else std.ArrayList(std.Thread),
/// Shutdown flag
shutdown: atomic.Value(bool),
shutdown: AtomicValue(bool),
/// PERF: Pre-allocated buffer pool for piece data
buffer_pool: ?*PieceBufferPool,
/// Statistics
tasks_completed: atomic.Value(u64),
tasks_failed: atomic.Value(u64),
total_bytes_verified: atomic.Value(u64),
pool_hits: atomic.Value(u64),
pool_misses: atomic.Value(u64),
tasks_completed: AtomicValue(u64),
tasks_failed: AtomicValue(u64),
total_bytes_verified: AtomicValue(u64),
pool_hits: AtomicValue(u64),
pool_misses: AtomicValue(u64),
pub fn init(allocator: mem.Allocator, config: VerificationPoolConfig) Error!VerificationPool {
// Initialize buffer pool if configured
@@ -146,17 +152,17 @@ pub const VerificationPool = struct {
.config = config,
.task_queue = .{},
.task_mutex = .{},
.task_condition = .{},
.task_condition = if (is_wasm) {} else .{},
.results_queue = .{},
.results_mutex = .{},
.workers = .{},
.shutdown = atomic.Value(bool).init(false),
.workers = if (is_wasm) {} else .{},
.shutdown = AtomicValue(bool).init(false),
.buffer_pool = buffer_pool,
.tasks_completed = atomic.Value(u64).init(0),
.tasks_failed = atomic.Value(u64).init(0),
.total_bytes_verified = atomic.Value(u64).init(0),
.pool_hits = atomic.Value(u64).init(0),
.pool_misses = atomic.Value(u64).init(0),
.tasks_completed = AtomicValue(u64).init(0),
.tasks_failed = AtomicValue(u64).init(0),
.total_bytes_verified = AtomicValue(u64).init(0),
.pool_hits = AtomicValue(u64).init(0),
.pool_misses = AtomicValue(u64).init(0),
};
}
@@ -170,7 +176,7 @@ pub const VerificationPool = struct {
self.task_queue.deinit(self.allocator);
self.results_queue.deinit(self.allocator);
self.workers.deinit(self.allocator);
if (!is_wasm) self.workers.deinit(self.allocator);
// Clean up buffer pool
if (self.buffer_pool) |pool| {
@@ -179,8 +185,10 @@ pub const VerificationPool = struct {
}
}
/// Start worker threads
/// Start worker threads (no-op on WASM — use processSynchronously instead)
pub fn start(self: *VerificationPool) Error!void {
if (is_wasm) return;
const num_workers = if (self.config.num_workers == 0)
@as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4)))
else
@@ -197,8 +205,10 @@ pub const VerificationPool = struct {
}
}
/// Stop all worker threads
/// Stop all worker threads (no-op on WASM)
pub fn stop(self: *VerificationPool) void {
if (is_wasm) return;
self.shutdown.store(true, .release);
// Wake up all workers
@@ -213,6 +223,49 @@ pub const VerificationPool = struct {
self.workers.clearRetainingCapacity();
}
/// Process up to `max_tasks` pending verifications synchronously.
/// For WASM: call this from the update loop since threads are unavailable.
/// On native: this can also be used for single-threaded operation.
pub fn processSynchronously(self: *VerificationPool, max_tasks: u32) void {
var processed: u32 = 0;
while (processed < max_tasks) : (processed += 1) {
// Dequeue a task
var task: VerificationTask = undefined;
{
self.task_mutex.lock();
defer self.task_mutex.unlock();
if (self.task_queue.items.len == 0) break;
task = self.task_queue.orderedRemove(0);
}
// Process it
const task_data = task.getData();
const is_valid = HashUtils.verify(task_data, task.expected_hash) catch false;
const data_len = task_data.len;
const peer_id = task.peer_id;
task.deinit();
_ = self.tasks_completed.fetchAdd(1, .release);
_ = self.total_bytes_verified.fetchAdd(data_len, .release);
if (!is_valid) {
_ = self.tasks_failed.fetchAdd(1, .release);
}
if (self.config.use_results_queue) {
self.results_mutex.lock();
defer self.results_mutex.unlock();
self.results_queue.append(self.allocator, .{
.session_id = task.session_id,
.piece_index = task.piece_index,
.is_valid = is_valid,
.completed_at = platform_time.milliTimestamp(),
.peer_id = peer_id,
}) catch {};
}
}
}
/// Queue a piece for verification
/// The data is COPIED - caller can free their copy after this returns
/// Returns error if queue is full or allocation fails
@@ -268,7 +321,7 @@ pub const VerificationPool = struct {
.peer_id = peer_id,
}) catch return Error.OutOfMemory;
self.task_condition.signal();
if (!is_wasm) self.task_condition.signal();
}
/// Get next completed result (non-blocking)
@@ -354,7 +407,7 @@ pub const VerificationPool = struct {
.session_id = t.session_id,
.piece_index = t.piece_index,
.is_valid = is_valid,
.completed_at = std.time.milliTimestamp(),
.completed_at = platform_time.milliTimestamp(),
.peer_id = peer_id,
}) catch |err| {
std.log.err("Failed to queue verification result for piece {}: {} - result lost", .{ t.piece_index, err });

507
src/mwp/hole_punch.zig Normal file
View File

@@ -0,0 +1,507 @@
//! Mutual Witness Protocol - Hole Punch Engine
//!
//! Handles the actual NAT traversal via simultaneous connection attempts.
const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const platform = @import("platform");
const platform_time = platform.time;
const types = @import("types.zig");
const Allocator = std.mem.Allocator;
const os = if (!is_wasm) std.os else struct {};
const Address = types.Address;
const HolePunchPacket = types.HolePunchPacket;
const RendezvousParams = types.RendezvousParams;
const ConnectionResult = types.ConnectionResult;
const ConnectionInfo = types.ConnectionInfo;
const HolePunchError = types.HolePunchError;
const Defaults = types.Defaults;
/// Socket wrapper for cross-platform UDP
pub const UdpSocket = if (is_wasm) struct {
fd: u32 = 0,
bound_address: ?Address = null,
pub fn init() !UdpSocket {
return error.OperationNotSupported;
}
pub fn deinit(_: *UdpSocket) void {}
pub fn bind(_: *UdpSocket, _: u16) !void {
return error.OperationNotSupported;
}
pub fn sendTo(_: *UdpSocket, _: Address, _: []const u8) !void {
return error.OperationNotSupported;
}
pub fn recvFrom(_: *UdpSocket, _: []u8) !struct { len: usize, addr: Address } {
return error.OperationNotSupported;
}
} else struct {
fd: std.posix.socket_t,
bound_address: ?Address,
pub fn init() !UdpSocket {
const fd = try std.posix.socket(
std.posix.AF.INET,
std.posix.SOCK.DGRAM,
0,
);
// Set non-blocking (platform-independent approach)
const flags = try std.posix.fcntl(fd, std.posix.F.GETFL, 0);
const nonblock_bit = 1 << @bitOffsetOf(std.posix.O, "NONBLOCK");
_ = try std.posix.fcntl(fd, std.posix.F.SETFL, flags | nonblock_bit);
// Allow address reuse
try std.posix.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
return .{
.fd = fd,
.bound_address = null,
};
}
pub fn deinit(self: *UdpSocket) void {
std.posix.close(self.fd);
}
pub fn bind(self: *UdpSocket, port: u16) !void {
const addr = std.net.Address.initIp4(.{ 0, 0, 0, 0 }, port);
try std.posix.bind(self.fd, &addr.any, addr.getOsSockLen());
self.bound_address = Address.initV4(.{ 0, 0, 0, 0 }, port);
}
pub fn sendTo(self: *UdpSocket, addr: Address, data: []const u8) !void {
const sock_addr = addressToSockaddr(addr);
_ = try std.posix.sendto(
self.fd,
data,
0,
&sock_addr.any,
sock_addr.getOsSockLen(),
);
}
pub fn recvFrom(self: *UdpSocket, buf: []u8) !struct { len: usize, addr: Address } {
var src_addr: std.posix.sockaddr.storage = undefined;
var addr_len: std.posix.socklen_t = @sizeOf(@TypeOf(src_addr));
const len = std.posix.recvfrom(
self.fd,
buf,
0,
@ptrCast(&src_addr),
&addr_len,
) catch |err| {
if (err == error.WouldBlock) return error.WouldBlock;
return err;
};
const addr = sockaddrToAddress(&src_addr);
return .{ .len = len, .addr = addr };
}
fn addressToSockaddr(addr: Address) std.net.Address {
return switch (addr.addr_type) {
.ipv4 => std.net.Address.initIp4(addr.ip.v4, addr.port),
.ipv6 => std.net.Address.initIp6(addr.ip.v6, addr.port, 0, 0),
};
}
fn sockaddrToAddress(sockaddr: *const std.posix.sockaddr.storage) Address {
const family = sockaddr.family;
if (family == std.posix.AF.INET) {
const in_addr: *const std.posix.sockaddr.in = @ptrCast(sockaddr);
const ip_bytes: [4]u8 = @bitCast(in_addr.addr);
return Address.initV4(ip_bytes, std.mem.bigToNative(u16, in_addr.port));
} else {
const in6_addr: *const std.posix.sockaddr.in6 = @ptrCast(sockaddr);
return Address.initV6(in6_addr.addr, std.mem.bigToNative(u16, in6_addr.port));
}
}
};
/// Hole punch engine
pub const HolePunchEngine = struct {
allocator: Allocator,
our_keypair: KeyPair,
stats: types.Stats,
/// Ed25519 key pair
pub const KeyPair = struct {
public: [32]u8,
secret: [64]u8,
pub fn sign(self: KeyPair, message: [32]u8) error{InvalidKeyData}![64]u8 {
const secret_key = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch return error.InvalidKeyData;
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch return error.InvalidKeyData;
const key_pair = std.crypto.sign.Ed25519.KeyPair{
.secret_key = secret_key,
.public_key = public_key,
};
const sig = std.crypto.sign.Ed25519.KeyPair.sign(key_pair, &message, null) catch return error.InvalidKeyData;
return sig.toBytes();
}
};
/// Connection attempt context
const AttemptContext = struct {
socket: UdpSocket,
target_address: Address,
using_port_hint: bool,
};
/// Initialize hole punch engine
pub fn init(allocator: Allocator, keypair: KeyPair) HolePunchEngine {
return .{
.allocator = allocator,
.our_keypair = keypair,
.stats = .{},
};
}
/// Attempt connection to peer
pub fn attemptConnection(
self: *HolePunchEngine,
target_addresses: []const Address,
params: RendezvousParams,
options: types.ConnectOptions,
) ConnectionResult {
self.stats.attempts += 1;
const start_time = platform_time.milliTimestamp();
// Wait until rendezvous time
const now = platform_time.milliTimestamp();
if (params.rendezvous_time > now) {
const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms;
if (options.send_keepalives) {
self.waitWithKeepalives(target_addresses, wait_ns) catch {};
} else {
platform.time.sleep(wait_ns);
}
}
// Try with retries
for (Defaults.retry_intervals) |delay| {
if (delay > 0) {
platform.time.sleep(delay * std.time.ns_per_ms);
}
const result = self.singleAttempt(target_addresses, params, options);
switch (result) {
.success => |info| {
self.stats.successes += 1;
const elapsed = @as(u64, @intCast(platform_time.milliTimestamp() - start_time));
self.updateAvgTime(elapsed);
return .{ .success = info };
},
.hole_punch_failed => continue, // Retry
else => return result,
}
}
self.stats.failures += 1;
return .{ .hole_punch_failed = .all_addresses_failed };
}
/// Single connection attempt (no retries)
fn singleAttempt(
self: *HolePunchEngine,
target_addresses: []const Address,
params: RendezvousParams,
options: types.ConnectOptions,
) ConnectionResult {
var contexts: std.ArrayList(AttemptContext) = .{};
defer {
for (contexts.items) |*ctx| {
ctx.socket.deinit();
}
contexts.deinit(self.allocator);
}
// Create sockets for all target addresses
for (target_addresses) |addr| {
// Direct attempt
var socket = UdpSocket.init() catch continue;
contexts.append(self.allocator, .{
.socket = socket,
.target_address = addr,
.using_port_hint = false,
}) catch {
socket.deinit();
continue;
};
// Port hint attempt (if enabled)
if (options.use_port_hints) {
var hint_socket = UdpSocket.init() catch continue;
hint_socket.bind(params.port_hint) catch {
hint_socket.deinit();
continue;
};
const hint_addr = Address.initV4(
if (addr.addr_type == .ipv4) addr.ip.v4 else .{ 0, 0, 0, 0 },
params.port_hint,
);
contexts.append(self.allocator, .{
.socket = hint_socket,
.target_address = hint_addr,
.using_port_hint = true,
}) catch {
hint_socket.deinit();
continue;
};
}
}
if (contexts.items.len == 0) {
return .{ .hole_punch_failed = .all_addresses_failed };
}
// Create and send hole punch packets
const packet = self.createHolePunchPacket(params) catch |err| {
return .{ .other_error = err };
};
const packet_bytes = packet.serialize();
for (contexts.items) |*ctx| {
ctx.socket.sendTo(ctx.target_address, &packet_bytes) catch continue;
self.stats.hole_punch_sent += 1;
}
// Wait for responses
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(Defaults.hole_punch_timeout_ms));
var recv_buf: [256]u8 = undefined;
while (platform_time.milliTimestamp() < deadline) {
for (contexts.items) |*ctx| {
const result = ctx.socket.recvFrom(&recv_buf) catch |err| {
if (err == error.WouldBlock) continue;
continue;
};
self.stats.hole_punch_received += 1;
// Parse response
const response = HolePunchPacket.deserialize(recv_buf[0..result.len]) catch continue;
// Verify connection ID matches
if (!std.mem.eql(u8, &response.connection_id, &params.connection_id)) {
continue;
}
// Verify signature
if (!response.verify()) {
continue;
}
// Success!
const elapsed = @as(u64, @intCast(platform_time.milliTimestamp() -
(params.rendezvous_time - Defaults.rendezvous_buffer_ms)));
return .{
.success = .{
.peer_id = response.sender_id,
.remote_address = result.addr,
.local_address = ctx.socket.bound_address orelse
Address.initV4(.{ 0, 0, 0, 0 }, 0),
.connection_id = params.connection_id,
.establishment_time_ms = elapsed,
},
};
}
// Small sleep to avoid busy loop
platform.time.sleep(1 * std.time.ns_per_ms);
}
return .{ .hole_punch_failed = .timeout };
}
/// Create a hole punch packet
fn createHolePunchPacket(self: *HolePunchEngine, params: RendezvousParams) error{InvalidKeyData}!HolePunchPacket {
var packet = HolePunchPacket{
.connection_id = params.connection_id,
.sender_id = self.our_keypair.public,
.timestamp = platform_time.milliTimestamp(),
.signature = undefined,
};
const hash = packet.computeHash();
packet.signature = try self.our_keypair.sign(hash);
return packet;
}
/// Wait with periodic keepalive packets to maintain NAT mappings
fn waitWithKeepalives(
_: *HolePunchEngine,
target_addresses: []const Address,
total_wait_ns: u64,
) !void {
const interval_ns = Defaults.keepalive_interval_ms * std.time.ns_per_ms;
var remaining = total_wait_ns;
var socket = try UdpSocket.init();
defer socket.deinit();
// Simple keepalive packet (just magic + timestamp)
var keepalive: [12]u8 = undefined;
@memcpy(keepalive[0..4], "MWPK"); // Keepalive magic
while (remaining > 0) {
const sleep_time = @min(remaining, interval_ns);
platform.time.sleep(sleep_time);
remaining -= sleep_time;
if (remaining > 0) {
// Send keepalive to all addresses
std.mem.writeInt(i64, keepalive[4..12], platform_time.milliTimestamp(), .big);
for (target_addresses) |addr| {
socket.sendTo(addr, &keepalive) catch continue;
}
}
}
}
/// Update rolling average connection time
fn updateAvgTime(self: *HolePunchEngine, new_time: u64) void {
if (self.stats.successes == 1) {
self.stats.avg_connection_time_ms = new_time;
} else {
// Exponential moving average
self.stats.avg_connection_time_ms =
(self.stats.avg_connection_time_ms * 7 + new_time) / 8;
}
}
/// Get current statistics
pub fn getStats(self: *HolePunchEngine) types.Stats {
return self.stats;
}
/// Reset statistics
pub fn resetStats(self: *HolePunchEngine) void {
self.stats = .{};
}
};
/// Listen for incoming hole punch attempts
pub const HolePunchListener = struct {
allocator: Allocator,
socket: UdpSocket,
our_keypair: HolePunchEngine.KeyPair,
expected_connection_id: ?[16]u8,
pub fn init(
allocator: Allocator,
keypair: HolePunchEngine.KeyPair,
listen_port: u16,
) !HolePunchListener {
var socket = try UdpSocket.init();
try socket.bind(listen_port);
return .{
.allocator = allocator,
.socket = socket,
.our_keypair = keypair,
.expected_connection_id = null,
};
}
pub fn deinit(self: *HolePunchListener) void {
self.socket.deinit();
}
/// Set expected connection ID (from rendezvous params)
pub fn expectConnection(self: *HolePunchListener, connection_id: [16]u8) void {
self.expected_connection_id = connection_id;
}
/// Wait for incoming hole punch
pub fn waitForPunch(self: *HolePunchListener, timeout_ms: u64) !struct {
packet: HolePunchPacket,
from: Address,
} {
var buf: [256]u8 = undefined;
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (platform_time.milliTimestamp() < deadline) {
const result = self.socket.recvFrom(&buf) catch |err| {
if (err == error.WouldBlock) {
platform.time.sleep(1 * std.time.ns_per_ms);
continue;
}
return err;
};
const packet = HolePunchPacket.deserialize(buf[0..result.len]) catch continue;
// Check connection ID if we're expecting a specific one
if (self.expected_connection_id) |expected| {
if (!std.mem.eql(u8, &packet.connection_id, &expected)) {
continue;
}
}
// Verify signature
if (!packet.verify()) {
continue;
}
return .{ .packet = packet, .from = result.addr };
}
return error.Timeout;
}
/// Send response to hole punch
pub fn sendResponse(
self: *HolePunchListener,
to: Address,
connection_id: [16]u8,
) !void {
var packet = HolePunchPacket{
.connection_id = connection_id,
.sender_id = self.our_keypair.public,
.timestamp = platform_time.milliTimestamp(),
.signature = undefined,
};
const hash = packet.computeHash();
packet.signature = try self.our_keypair.sign(hash);
const bytes = packet.serialize();
try self.socket.sendTo(to, &bytes);
}
};
// Tests
test "HolePunchPacket roundtrip" {
var packet = HolePunchPacket{
.connection_id = [_]u8{0xAB} ** 16,
.sender_id = [_]u8{0xCD} ** 32,
.timestamp = 1234567890123,
.signature = [_]u8{0xEF} ** 64,
};
const serialized = packet.serialize();
const deserialized = try HolePunchPacket.deserialize(&serialized);
try std.testing.expect(std.mem.eql(u8, &packet.connection_id, &deserialized.connection_id));
try std.testing.expect(std.mem.eql(u8, &packet.sender_id, &deserialized.sender_id));
try std.testing.expectEqual(packet.timestamp, deserialized.timestamp);
}
test "UdpSocket creation" {
var socket = try UdpSocket.init();
defer socket.deinit();
try socket.bind(0); // Bind to any available port
try std.testing.expect(socket.bound_address != null);
}

350
src/mwp/meeting_point.zig Normal file
View File

@@ -0,0 +1,350 @@
//! Mutual Witness Protocol - Meeting Point Logic
//!
//! Handles the DHT-based meeting point where peers find each other.
const std = @import("std");
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
const types = @import("types.zig");
const Allocator = std.mem.Allocator;
const MeetingPublication = types.MeetingPublication;
const Address = types.Address;
const Defaults = types.Defaults;
/// DHT interface that MWP requires
pub const DHTInterface = struct {
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
/// Store value at key
put: *const fn (ptr: *anyopaque, key: [32]u8, value: []const u8) anyerror!void,
/// Get all values at key
getAll: *const fn (ptr: *anyopaque, key: [32]u8, allocator: Allocator) anyerror![][]u8,
/// Subscribe to changes at key (optional)
subscribe: ?*const fn (ptr: *anyopaque, key: [32]u8, callback: *const fn ([]const u8) void) anyerror!void,
};
pub fn put(self: DHTInterface, key: [32]u8, value: []const u8) !void {
return self.vtable.put(self.ptr, key, value);
}
pub fn getAll(self: DHTInterface, key: [32]u8, allocator: Allocator) ![][]u8 {
return self.vtable.getAll(self.ptr, key, allocator);
}
pub fn subscribe(self: DHTInterface, key: [32]u8, callback: *const fn ([]const u8) void) !void {
if (self.vtable.subscribe) |sub| {
return sub(self.ptr, key, callback);
}
return error.SubscribeNotSupported;
}
};
/// Meeting point manager
pub const MeetingPoint = struct {
allocator: Allocator,
dht: DHTInterface,
our_keypair: KeyPair,
our_addresses: []const Address,
next_sequence: u64,
/// Ed25519 key pair
pub const KeyPair = struct {
public: [32]u8,
secret: [64]u8,
/// Sign a message
pub fn sign(self: KeyPair, message: [32]u8) error{InvalidKeyData}![64]u8 {
const secret_key = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch return error.InvalidKeyData;
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch return error.InvalidKeyData;
const key_pair = std.crypto.sign.Ed25519.KeyPair{
.secret_key = secret_key,
.public_key = public_key,
};
const sig = std.crypto.sign.Ed25519.KeyPair.sign(key_pair, &message, null) catch return error.InvalidKeyData;
return sig.toBytes();
}
};
/// Initialize meeting point manager
pub fn init(
allocator: Allocator,
dht: DHTInterface,
keypair: KeyPair,
addresses: []const Address,
) MeetingPoint {
return .{
.allocator = allocator,
.dht = dht,
.our_keypair = keypair,
.our_addresses = addresses,
.next_sequence = 1,
};
}
/// Compute the deterministic meeting key for two peers
pub fn computeMeetingKey(our_pubkey: [32]u8, their_pubkey: [32]u8) [32]u8 {
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
// Protocol identifier
hasher.update("mwp-v1");
// Deterministic ordering of public keys
if (std.mem.lessThan(u8, &our_pubkey, &their_pubkey)) {
hasher.update(&our_pubkey);
hasher.update(&their_pubkey);
} else {
hasher.update(&their_pubkey);
hasher.update(&our_pubkey);
}
var result: [32]u8 = undefined;
hasher.final(&result);
return result;
}
/// Create a new publication
pub fn createPublication(self: *MeetingPoint, ttl: u32) error{InvalidKeyData}!MeetingPublication {
var pub_data = MeetingPublication{
.peer_id = self.our_keypair.public,
.addresses = self.our_addresses,
.nonce = undefined,
.timestamp = platform_time.milliTimestamp(),
.ttl = ttl,
.sequence = self.next_sequence,
.signature = undefined,
};
// Generate random nonce
platform_random.bytes(&pub_data.nonce);
// Sign
const hash = pub_data.computeHash();
pub_data.signature = try self.our_keypair.sign(hash);
self.next_sequence += 1;
return pub_data;
}
/// Publish to a meeting point
pub fn publish(self: *MeetingPoint, their_pubkey: [32]u8, ttl: u32) !MeetingPublication {
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
const publication = try self.createPublication(ttl);
const serialized = try publication.serialize(self.allocator);
defer self.allocator.free(serialized);
try self.dht.put(meeting_key, serialized);
return publication;
}
/// Wait for peer's publication at meeting point
pub fn waitForPeer(
self: *MeetingPoint,
their_pubkey: [32]u8,
timeout_ms: u64,
) !struct { publication: MeetingPublication, seen_time: i64 } {
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (platform_time.milliTimestamp() < deadline) {
// Query DHT
const entries = try self.dht.getAll(meeting_key, self.allocator);
defer {
for (entries) |entry| {
self.allocator.free(entry);
}
self.allocator.free(entries);
}
// Look for peer's publication
for (entries) |entry| {
var publication = MeetingPublication.deserialize(self.allocator, entry) catch continue;
// Is this from our target peer?
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
publication.deinit(self.allocator);
continue;
}
// Verify signature
if (!publication.verify()) {
publication.deinit(self.allocator);
continue;
}
// Check not expired
if (publication.isExpired()) {
publication.deinit(self.allocator);
continue;
}
// Found valid publication
return .{
.publication = publication,
.seen_time = platform_time.milliTimestamp(),
};
}
// Poll interval
platform.time.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms);
}
return error.Timeout;
}
/// Find peer's publication (non-blocking)
pub fn findPeer(
self: *MeetingPoint,
their_pubkey: [32]u8,
) !?MeetingPublication {
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
const entries = try self.dht.getAll(meeting_key, self.allocator);
defer {
for (entries) |entry| {
self.allocator.free(entry);
}
self.allocator.free(entries);
}
for (entries) |entry| {
var publication = MeetingPublication.deserialize(self.allocator, entry) catch continue;
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
publication.deinit(self.allocator);
continue;
}
if (!publication.verify()) {
publication.deinit(self.allocator);
continue;
}
if (publication.isExpired()) {
publication.deinit(self.allocator);
continue;
}
return publication;
}
return null;
}
/// Update our addresses and republish
pub fn updateAddresses(self: *MeetingPoint, new_addresses: []const Address) void {
self.our_addresses = new_addresses;
}
};
/// Compute shared rendezvous parameters from two publications
pub fn computeRendezvousParams(
our_pub: MeetingPublication,
their_pub: MeetingPublication,
seen_time: i64,
buffer_ms: i64,
) types.RendezvousParams {
// Combine nonces deterministically
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
if (std.mem.lessThan(u8, &our_pub.nonce, &their_pub.nonce)) {
hasher.update(&our_pub.nonce);
hasher.update(&their_pub.nonce);
} else {
hasher.update(&their_pub.nonce);
hasher.update(&our_pub.nonce);
}
var shared_randomness: [32]u8 = undefined;
hasher.final(&shared_randomness);
// Rendezvous time: relative to when we saw peer (robust to clock skew)
const rendezvous_time = seen_time + buffer_ms;
// Port hint from shared randomness
const port_offset = std.mem.readInt(u16, shared_randomness[0..2], .little);
const port_hint = 49152 + (port_offset % 16384);
// Connection ID from shared randomness
var connection_id: [16]u8 = undefined;
@memcpy(&connection_id, shared_randomness[16..32]);
return .{
.shared_randomness = shared_randomness,
.rendezvous_time = rendezvous_time,
.port_hint = port_hint,
.connection_id = connection_id,
};
}
// Tests
test "computeMeetingKey is deterministic" {
const key_a = [_]u8{1} ** 32;
const key_b = [_]u8{2} ** 32;
const result1 = MeetingPoint.computeMeetingKey(key_a, key_b);
const result2 = MeetingPoint.computeMeetingKey(key_b, key_a);
// Order shouldn't matter
try std.testing.expect(std.mem.eql(u8, &result1, &result2));
}
test "computeMeetingKey is unique per pair" {
const key_a = [_]u8{1} ** 32;
const key_b = [_]u8{2} ** 32;
const key_c = [_]u8{3} ** 32;
const result_ab = MeetingPoint.computeMeetingKey(key_a, key_b);
const result_ac = MeetingPoint.computeMeetingKey(key_a, key_c);
try std.testing.expect(!std.mem.eql(u8, &result_ab, &result_ac));
}
test "computeRendezvousParams produces same result for both peers" {
// Simulate two peers with their publications
var our_nonce: [32]u8 = undefined;
var their_nonce: [32]u8 = undefined;
platform_random.bytes(&our_nonce);
platform_random.bytes(&their_nonce);
const our_pub = MeetingPublication{
.peer_id = [_]u8{1} ** 32,
.addresses = &[_]Address{},
.nonce = our_nonce,
.timestamp = 1000,
.ttl = 300,
.sequence = 1,
.signature = [_]u8{0} ** 64,
};
const their_pub = MeetingPublication{
.peer_id = [_]u8{2} ** 32,
.addresses = &[_]Address{},
.nonce = their_nonce,
.timestamp = 1050,
.ttl = 300,
.sequence = 1,
.signature = [_]u8{0} ** 64,
};
// Both peers compute with their own seen_time
const our_params = computeRendezvousParams(our_pub, their_pub, 1100, 500);
const their_params = computeRendezvousParams(their_pub, our_pub, 1100, 500);
// Shared randomness should be identical
try std.testing.expect(std.mem.eql(u8, &our_params.shared_randomness, &their_params.shared_randomness));
// Port hint should be identical
try std.testing.expectEqual(our_params.port_hint, their_params.port_hint);
// Connection ID should be identical
try std.testing.expect(std.mem.eql(u8, &our_params.connection_id, &their_params.connection_id));
}

448
src/mwp/mutual_witness.zig Normal file
View File

@@ -0,0 +1,448 @@
//! Mutual Witness Protocol — Standalone Core
//!
//! This is the testable standalone implementation of MWP, using a `DHTInterface`
//! abstraction so it can run with `MockDHT` in unit tests. For the production
//! API wired to `*P2P`, see `src/mwp_integration.zig`.
//!
//! A novel NAT traversal and peer discovery protocol that requires
//! zero external infrastructure beyond a DHT.
//!
//! ## Overview
//!
//! The Mutual Witness Protocol (MWP) enables two peers to establish a direct
//! P2P connection when they know each other's public keys, using only a DHT
//! for coordination.
//!
//! ## Key Features
//!
//! - No STUN servers required
//! - No relay/signaling servers required
//! - No beacon chain or external timing source
//! - Only requires DHT (already present in most P2P networks)
//!
//! ## How It Works
//!
//! 1. Both peers compute the same deterministic "meeting key" from their public keys
//! 2. Both publish their connection info to the DHT at this key
//! 3. Each peer discovers the other's publication
//! 4. Both compute identical rendezvous parameters from their combined data
//! 5. Both attempt simultaneous connection at the computed time
//!
//! ## Example
//!
//! ```zig
//! const mwp = @import("mwp");
//!
//! // Initialize
//! var witness = mwp.MutualWitness.init(allocator, dht, keypair, our_addresses);
//!
//! // Connect to a peer by their public key
//! const result = witness.connect(target_pubkey, .{});
//!
//! switch (result) {
//! .success => |info| {
//! std.debug.print("Connected to {x} at {}:{}\n", .{
//! info.peer_id,
//! info.remote_address.ip.v4,
//! info.remote_address.port,
//! });
//! },
//! .peer_not_found => std.debug.print("Peer not found\n", .{}),
//! .timeout => std.debug.print("Timeout\n", .{}),
//! else => std.debug.print("Connection failed\n", .{}),
//! }
//! ```
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const types = @import("types.zig");
pub const meeting_point = @import("meeting_point.zig");
pub const hole_punch = @import("hole_punch.zig");
// Re-export common types
pub const Address = types.Address;
pub const MeetingPublication = types.MeetingPublication;
pub const RendezvousParams = types.RendezvousParams;
pub const HolePunchPacket = types.HolePunchPacket;
pub const ConnectionResult = types.ConnectionResult;
pub const ConnectionInfo = types.ConnectionInfo;
pub const ConnectOptions = types.ConnectOptions;
pub const Stats = types.Stats;
pub const Defaults = types.Defaults;
pub const MeetingPoint = meeting_point.MeetingPoint;
pub const DHTInterface = meeting_point.DHTInterface;
pub const HolePunchEngine = hole_punch.HolePunchEngine;
pub const HolePunchListener = hole_punch.HolePunchListener;
/// Ed25519 key pair for identity and signing
pub const KeyPair = struct {
public: [32]u8,
secret: [64]u8,
/// Generate a new random key pair
pub fn generate() KeyPair {
const kp = std.crypto.sign.Ed25519.KeyPair.generate();
return .{
.public = kp.public_key.toBytes(),
.secret = kp.secret_key.toBytes(),
};
}
/// Create from existing secret key bytes
pub fn fromSecretKey(secret: [64]u8) error{InvalidKeyData}!KeyPair {
const sk = std.crypto.sign.Ed25519.SecretKey.fromBytes(secret) catch return error.InvalidKeyData;
const kp = std.crypto.sign.Ed25519.KeyPair.fromSecretKey(sk) catch return error.InvalidKeyData;
return .{
.public = kp.public_key.toBytes(),
.secret = secret,
};
}
/// Sign a 32-byte hash
pub fn sign(self: KeyPair, hash: [32]u8) error{InvalidKeyData}![64]u8 {
const sk = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch return error.InvalidKeyData;
const pk = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch return error.InvalidKeyData;
const kp = std.crypto.sign.Ed25519.KeyPair{
.secret_key = sk,
.public_key = pk,
};
const sig = std.crypto.sign.Ed25519.KeyPair.sign(kp, &hash, null) catch return error.InvalidKeyData;
return sig.toBytes();
}
};
/// Main Mutual Witness Protocol handler
pub const MutualWitness = struct {
allocator: Allocator,
meeting: MeetingPoint,
hole_punch_engine: HolePunchEngine,
keypair: KeyPair,
our_addresses: []const Address,
stats: Stats,
/// Initialize the Mutual Witness Protocol handler
pub fn init(
allocator: Allocator,
dht: DHTInterface,
keypair: KeyPair,
addresses: []const Address,
) MutualWitness {
const mp_keypair = MeetingPoint.KeyPair{
.public = keypair.public,
.secret = keypair.secret,
};
const hp_keypair = HolePunchEngine.KeyPair{
.public = keypair.public,
.secret = keypair.secret,
};
return .{
.allocator = allocator,
.meeting = MeetingPoint.init(allocator, dht, mp_keypair, addresses),
.hole_punch_engine = HolePunchEngine.init(allocator, hp_keypair),
.keypair = keypair,
.our_addresses = addresses,
.stats = .{},
};
}
/// Connect to a peer by their public key
///
/// This is the main entry point for establishing connections via MWP.
/// The function will:
/// 1. Publish our connection info to the DHT meeting point
/// 2. Wait for the peer's publication
/// 3. Compute shared rendezvous parameters
/// 4. Attempt simultaneous hole punch
///
/// Returns a ConnectionResult indicating success or failure.
pub fn connect(
self: *MutualWitness,
target_pubkey: [32]u8,
options: ConnectOptions,
) ConnectionResult {
self.stats.attempts += 1;
// Step 1: Publish our meeting info
const our_publication = self.meeting.publish(
target_pubkey,
options.publication_ttl,
) catch |err| {
return .{ .other_error = err };
};
self.stats.publications_created += 1;
// Step 2: Wait for peer's publication
const peer_result = self.meeting.waitForPeer(
target_pubkey,
options.timeout_ms,
) catch |err| {
return switch (err) {
error.Timeout => .timeout,
else => .{ .other_error = err },
};
};
self.stats.publications_received += 1;
defer {
var pub_copy = peer_result.publication;
pub_copy.deinit(self.allocator);
}
// Step 3: Compute rendezvous parameters
const params = meeting_point.computeRendezvousParams(
our_publication,
peer_result.publication,
peer_result.seen_time,
options.rendezvous_buffer_ms,
);
// Step 4: Attempt connection
const result = self.hole_punch_engine.attemptConnection(
peer_result.publication.addresses,
params,
options,
);
// Update stats
switch (result) {
.success => self.stats.successes += 1,
else => self.stats.failures += 1,
}
return result;
}
/// Check if a peer is available at the meeting point (non-blocking)
pub fn findPeer(self: *MutualWitness, target_pubkey: [32]u8) !?MeetingPublication {
return self.meeting.findPeer(target_pubkey);
}
/// Publish availability for a specific peer to find us
pub fn publishFor(self: *MutualWitness, target_pubkey: [32]u8, ttl: u32) !MeetingPublication {
const pub_data = try self.meeting.publish(target_pubkey, ttl);
self.stats.publications_created += 1;
return pub_data;
}
/// Update our addresses (e.g., after NAT remapping)
pub fn updateAddresses(self: *MutualWitness, new_addresses: []const Address) void {
self.our_addresses = new_addresses;
self.meeting.updateAddresses(new_addresses);
}
/// Get our public key
pub fn getPublicKey(self: *MutualWitness) [32]u8 {
return self.keypair.public;
}
/// Get statistics
pub fn getStats(self: *MutualWitness) Stats {
return self.stats;
}
/// Reset statistics
pub fn resetStats(self: *MutualWitness) void {
self.stats = .{};
self.hole_punch_engine.resetStats();
}
/// Compute meeting key for a peer (useful for debugging)
pub fn computeMeetingKey(self: *MutualWitness, target_pubkey: [32]u8) [32]u8 {
return MeetingPoint.computeMeetingKey(self.keypair.public, target_pubkey);
}
};
/// Helper to create a mock DHT for testing
pub const MockDHT = struct {
allocator: Allocator,
storage: std.AutoHashMap([32]u8, std.ArrayList([]u8)),
pub fn init(allocator: Allocator) MockDHT {
return .{
.allocator = allocator,
.storage = std.AutoHashMap([32]u8, std.ArrayList([]u8)).init(allocator),
};
}
pub fn deinit(self: *MockDHT) void {
var it = self.storage.valueIterator();
while (it.next()) |list| {
for (list.items) |item| {
self.allocator.free(item);
}
var list_copy = list.*;
list_copy.deinit(self.allocator);
}
self.storage.deinit();
}
pub fn put(ptr: *anyopaque, key: [32]u8, value: []const u8) !void {
const self: *MockDHT = @ptrCast(@alignCast(ptr));
const entry = self.storage.getOrPut(key) catch return error.OutOfMemory;
if (!entry.found_existing) {
entry.value_ptr.* = .{};
}
const copy = self.allocator.dupe(u8, value) catch return error.OutOfMemory;
entry.value_ptr.append(self.allocator, copy) catch {
self.allocator.free(copy);
return error.OutOfMemory;
};
}
pub fn getAll(ptr: *anyopaque, key: [32]u8, allocator: Allocator) ![][]u8 {
const self: *MockDHT = @ptrCast(@alignCast(ptr));
const list = self.storage.get(key) orelse return &[_][]u8{};
var result = try allocator.alloc([]u8, list.items.len);
for (list.items, 0..) |item, i| {
result[i] = try allocator.dupe(u8, item);
}
return result;
}
pub fn interface(self: *MockDHT) DHTInterface {
return .{
.ptr = self,
.vtable = &.{
.put = put,
.getAll = getAll,
.subscribe = null,
},
};
}
};
// Tests
test "MutualWitness basic flow" {
const allocator = std.testing.allocator;
// Create mock DHT
var dht = MockDHT.init(allocator);
defer dht.deinit();
// Create two peers
const alice_keypair = KeyPair.generate();
const bob_keypair = KeyPair.generate();
const alice_addr = Address.initV4(.{ 192, 168, 1, 1 }, 9000);
const bob_addr = Address.initV4(.{ 192, 168, 1, 2 }, 9001);
var alice = MutualWitness.init(
allocator,
dht.interface(),
alice_keypair,
&[_]Address{alice_addr},
);
var bob = MutualWitness.init(
allocator,
dht.interface(),
bob_keypair,
&[_]Address{bob_addr},
);
// Both compute same meeting key
const alice_key = alice.computeMeetingKey(bob_keypair.public);
const bob_key = bob.computeMeetingKey(alice_keypair.public);
try std.testing.expect(std.mem.eql(u8, &alice_key, &bob_key));
// Alice publishes for Bob
const alice_pub = try alice.publishFor(bob_keypair.public, 300);
try std.testing.expect(alice_pub.verify());
// Bob can find Alice
const found = try bob.findPeer(alice_keypair.public);
try std.testing.expect(found != null);
if (found) |f| {
try std.testing.expect(std.mem.eql(u8, &f.peer_id, &alice_keypair.public));
var f_copy = f;
f_copy.deinit(allocator);
}
}
test "Meeting key is symmetric" {
const alice = [_]u8{1} ** 32;
const bob = [_]u8{2} ** 32;
const key1 = MeetingPoint.computeMeetingKey(alice, bob);
const key2 = MeetingPoint.computeMeetingKey(bob, alice);
try std.testing.expect(std.mem.eql(u8, &key1, &key2));
}
test "Publication signature verification" {
const allocator = std.testing.allocator;
var dht = MockDHT.init(allocator);
defer dht.deinit();
const keypair = KeyPair.generate();
const addr = Address.initV4(.{ 127, 0, 0, 1 }, 8080);
var witness = MutualWitness.init(
allocator,
dht.interface(),
keypair,
&[_]Address{addr},
);
const target = [_]u8{0xAB} ** 32;
const pub_data = try witness.publishFor(target, 300);
// Verify signature
try std.testing.expect(pub_data.verify());
// Tamper with data - signature should fail
var tampered = pub_data;
tampered.timestamp += 1;
try std.testing.expect(!tampered.verify());
}
test "Rendezvous params are deterministic" {
// Two publications
const nonce_a = [_]u8{1} ** 32;
const nonce_b = [_]u8{2} ** 32;
const pub_a = MeetingPublication{
.peer_id = [_]u8{0xAA} ** 32,
.addresses = &[_]Address{},
.nonce = nonce_a,
.timestamp = 1000,
.ttl = 300,
.sequence = 1,
.signature = [_]u8{0} ** 64,
};
const pub_b = MeetingPublication{
.peer_id = [_]u8{0xBB} ** 32,
.addresses = &[_]Address{},
.nonce = nonce_b,
.timestamp = 1050,
.ttl = 300,
.sequence = 1,
.signature = [_]u8{0} ** 64,
};
// Both peers compute params (with same seen_time for test)
const params_a = meeting_point.computeRendezvousParams(pub_a, pub_b, 1100, 500);
const params_b = meeting_point.computeRendezvousParams(pub_b, pub_a, 1100, 500);
// Should produce identical shared randomness
try std.testing.expect(std.mem.eql(u8, &params_a.shared_randomness, &params_b.shared_randomness));
// Should produce identical port hints
try std.testing.expectEqual(params_a.port_hint, params_b.port_hint);
// Should produce identical connection IDs
try std.testing.expect(std.mem.eql(u8, &params_a.connection_id, &params_b.connection_id));
}

37
src/mwp/mwp.zig Normal file
View File

@@ -0,0 +1,37 @@
//! Mutual Witness Protocol (MWP)
//!
//! A novel NAT traversal protocol requiring zero external infrastructure.
//!
//! See `mutual_witness.zig` for main documentation.
pub const mutual_witness = @import("mutual_witness.zig");
pub const types = @import("types.zig");
pub const meeting_point = @import("meeting_point.zig");
pub const hole_punch = @import("hole_punch.zig");
pub const p2p_dht_adapter = @import("p2p_dht_adapter.zig");
// Re-export main types for convenience
pub const MutualWitness = mutual_witness.MutualWitness;
pub const KeyPair = mutual_witness.KeyPair;
pub const MockDHT = mutual_witness.MockDHT;
pub const Address = types.Address;
pub const MeetingPublication = types.MeetingPublication;
pub const RendezvousParams = types.RendezvousParams;
pub const ConnectionResult = types.ConnectionResult;
pub const ConnectionInfo = types.ConnectionInfo;
pub const ConnectOptions = types.ConnectOptions;
pub const Stats = types.Stats;
pub const Defaults = types.Defaults;
pub const DHTInterface = meeting_point.DHTInterface;
pub const MeetingPoint = meeting_point.MeetingPoint;
pub const HolePunchEngine = hole_punch.HolePunchEngine;
pub const P2PDhtAdapter = p2p_dht_adapter.P2PDhtAdapter;
pub const P2PMeetingPoint = p2p_dht_adapter.P2PMeetingPoint;
test {
_ = @import("types.zig");
_ = @import("meeting_point.zig");
_ = @import("hole_punch.zig");
_ = @import("mutual_witness.zig");
_ = @import("p2p_dht_adapter.zig");
}

208
src/mwp/p2p_dht_adapter.zig Normal file
View File

@@ -0,0 +1,208 @@
//! P2P DHT Adapter for MWP
//!
//! Adapts zig-p2p's DHT to work with the Mutual Witness Protocol.
//!
//! Key insight: MWP's original design has both peers publish to the same
//! meeting key, then uses getAll() to retrieve all publications. However,
//! zig-p2p's DHT stores one value per key.
//!
//! Solution: We use peer-specific publication keys:
//! - Alice publishes at: hash(meeting_key || alice_pubkey)
//! - Bob publishes at: hash(meeting_key || bob_pubkey)
//! - When looking up, we query the peer's specific key
//!
//! This adapter wraps the P2P DHT and handles this key transformation.
const std = @import("std");
const types = @import("types.zig");
const meeting_point = @import("meeting_point.zig");
const Allocator = std.mem.Allocator;
const DHTInterface = meeting_point.DHTInterface;
/// Adapter to use zig-p2p's P2P DHT with MWP
pub const P2PDhtAdapter = struct {
allocator: Allocator,
/// Opaque pointer to zig-p2p P2P instance
/// This is *P2P from src/p2p/p2p.zig
p2p: *anyopaque,
/// Function pointers to P2P DHT methods (to avoid import cycle)
dht_store_fn: *const fn (p2p: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void,
dht_find_value_fn: *const fn (p2p: *anyopaque, key: [32]u8) anyerror!?[]u8,
/// Our public key (for computing publication keys)
our_pubkey: [32]u8,
/// The target peer's public key we're trying to meet
/// Set before put/getAll operations
target_pubkey: ?[32]u8,
/// Default TTL for publications (seconds)
default_ttl: u32,
pub const Config = struct {
allocator: Allocator,
p2p: *anyopaque,
dht_store_fn: *const fn (p2p: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void,
dht_find_value_fn: *const fn (p2p: *anyopaque, key: [32]u8) anyerror!?[]u8,
our_pubkey: [32]u8,
default_ttl: u32 = 300, // 5 minutes
};
pub fn init(config: Config) P2PDhtAdapter {
return .{
.allocator = config.allocator,
.p2p = config.p2p,
.dht_store_fn = config.dht_store_fn,
.dht_find_value_fn = config.dht_find_value_fn,
.our_pubkey = config.our_pubkey,
.target_pubkey = null,
.default_ttl = config.default_ttl,
};
}
/// Set the target peer for the next operations
/// Must be called before put/getAll when using the interface
pub fn setTarget(self: *P2PDhtAdapter, target_pubkey: [32]u8) void {
self.target_pubkey = target_pubkey;
}
/// Compute the publication key for a specific peer at a meeting point
/// publication_key = hash("mwp-pub" || meeting_key || publisher_pubkey)
fn computePublicationKey(meeting_key: [32]u8, publisher_pubkey: [32]u8) [32]u8 {
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
hasher.update("mwp-pub-v1");
hasher.update(&meeting_key);
hasher.update(&publisher_pubkey);
var result: [32]u8 = undefined;
hasher.final(&result);
return result;
}
/// DHTInterface.put implementation
/// Publishes our data at our publication key (meeting_key + our_pubkey)
fn put(ptr: *anyopaque, meeting_key: [32]u8, value: []const u8) anyerror!void {
const self: *P2PDhtAdapter = @ptrCast(@alignCast(ptr));
// Compute our publication key
const pub_key = computePublicationKey(meeting_key, self.our_pubkey);
// Store in DHT
try self.dht_store_fn(self.p2p, pub_key, value, self.default_ttl);
}
/// DHTInterface.getAll implementation
/// Looks up the target peer's publication key (meeting_key + target_pubkey)
fn getAll(ptr: *anyopaque, meeting_key: [32]u8, allocator: Allocator) anyerror![][]u8 {
const self: *P2PDhtAdapter = @ptrCast(@alignCast(ptr));
const target = self.target_pubkey orelse return error.TargetNotSet;
// Compute target's publication key
const pub_key = computePublicationKey(meeting_key, target);
// Query DHT
const value = try self.dht_find_value_fn(self.p2p, pub_key);
if (value) |v| {
// Return as single-element array (DHT returns one value per key)
const result = try allocator.alloc([]u8, 1);
result[0] = v;
return result;
}
// No value found
return &[_][]u8{};
}
/// Get the DHTInterface for use with MWP
pub fn interface(self: *P2PDhtAdapter) DHTInterface {
return .{
.ptr = self,
.vtable = &.{
.put = put,
.getAll = getAll,
.subscribe = null, // Not implemented yet
},
};
}
};
/// Wrapper for MeetingPoint that handles the target peer setup
pub const P2PMeetingPoint = struct {
allocator: Allocator,
adapter: *P2PDhtAdapter,
meeting: meeting_point.MeetingPoint,
pub fn init(
allocator: Allocator,
adapter: *P2PDhtAdapter,
keypair: meeting_point.MeetingPoint.KeyPair,
addresses: []const types.Address,
) P2PMeetingPoint {
return .{
.allocator = allocator,
.adapter = adapter,
.meeting = meeting_point.MeetingPoint.init(
allocator,
adapter.interface(),
keypair,
addresses,
),
};
}
/// Publish our availability for a specific peer
pub fn publish(self: *P2PMeetingPoint, their_pubkey: [32]u8, ttl: u32) !types.MeetingPublication {
// Set target before publishing (for key computation)
self.adapter.setTarget(their_pubkey);
return self.meeting.publish(their_pubkey, ttl);
}
/// Wait for a peer's publication
pub fn waitForPeer(
self: *P2PMeetingPoint,
their_pubkey: [32]u8,
timeout_ms: u64,
) !struct { publication: types.MeetingPublication, seen_time: i64 } {
// Set target before querying
self.adapter.setTarget(their_pubkey);
return self.meeting.waitForPeer(their_pubkey, timeout_ms);
}
/// Find a peer's publication (non-blocking)
pub fn findPeer(self: *P2PMeetingPoint, their_pubkey: [32]u8) !?types.MeetingPublication {
self.adapter.setTarget(their_pubkey);
return self.meeting.findPeer(their_pubkey);
}
/// Compute meeting key (for debugging)
pub fn computeMeetingKey(our_pubkey: [32]u8, their_pubkey: [32]u8) [32]u8 {
return meeting_point.MeetingPoint.computeMeetingKey(our_pubkey, their_pubkey);
}
};
// Tests
test "P2PDhtAdapter publication key is deterministic" {
const meeting_key = [_]u8{0xAA} ** 32;
const pubkey = [_]u8{0xBB} ** 32;
const key1 = P2PDhtAdapter.computePublicationKey(meeting_key, pubkey);
const key2 = P2PDhtAdapter.computePublicationKey(meeting_key, pubkey);
try std.testing.expect(std.mem.eql(u8, &key1, &key2));
}
test "P2PDhtAdapter publication key differs by publisher" {
const meeting_key = [_]u8{0xAA} ** 32;
const alice_pubkey = [_]u8{0xBB} ** 32;
const bob_pubkey = [_]u8{0xCC} ** 32;
const alice_key = P2PDhtAdapter.computePublicationKey(meeting_key, alice_pubkey);
const bob_key = P2PDhtAdapter.computePublicationKey(meeting_key, bob_pubkey);
// Different publishers = different publication keys
try std.testing.expect(!std.mem.eql(u8, &alice_key, &bob_key));
}

Some files were not shown because too many files have changed in this diff Show More