# Mutual Witness Protocol Specification **Version:** 1.0.0 **Status:** Draft **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 ### 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 | --- ## 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. Previously observed external addresses # (From successful past connections) addresses.extend(get_observed_addresses()) # 3. Predicted addresses # (From NAT behavior learning) if predicted := nat_predictor.predict(): addresses.append(predicted) # 4. UPnP-mapped address (if available) if upnp_addr := get_upnp_address(): addresses.append(upnp_addr) return addresses ``` --- ## 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: 1. Alice publishes to DHT (includes addresses) 2. Bob publishes to DHT (includes addresses) 3. Both find each other in DHT 4. Both attempt connection Difference: No STUN (addresses from observation), 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*