bidirectional ip reflection for listener address discovery

This commit is contained in:
2026-02-09 16:02:23 -03:00
parent 59e9e420be
commit 7b47ef155c
31 changed files with 3192 additions and 269 deletions

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:

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

@@ -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]
```

View File

@@ -43,30 +43,46 @@ MWP eliminates all three by having peers **witness each other**:
### Bundled STUN (IP Reflection)
MWP includes a novel **Bundled STUN** mechanism: every DHT response includes the requester's observed source address. This eliminates STUN servers entirely - peers discover their public IP from normal DHT traffic:
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)
Now Alice knows her public IP without any STUN server!
```
**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");
// Initialize with your DHT and keypair
var witness = mwp.MutualWitness.init(allocator, dht, keypair);
// 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 connection = try witness.connect(target_pubkey, .{
const result = witness.connect(target_pubkey, .{
.timeout_ms = 5000,
});
// Use connection...
defer connection.close();
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
@@ -106,7 +122,9 @@ defer connection.close();
- [SPEC.md](./SPEC.md) - Complete protocol specification
- [COMPARISON.md](./COMPARISON.md) - Detailed comparison with existing solutions
- [src/](./src/) - Implementation
- [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

View File

@@ -366,9 +366,9 @@ 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. This is the same information a STUN │
│ server would provide, but bundled into existing traffic. │
│ source address. │
│ │
│ Alice ──── DHT_REQUEST ───────────────> DHT Node │
│ src: 192.0.2.1:54321 │
@@ -376,24 +376,49 @@ MWP eliminates the need for external STUN servers through **IP Reflection**:
│ Alice <─── DHT_RESPONSE ─────────────── DHT Node │
│ observed_addr: 192.0.2.1:54321 │
│ │
│ Now Alice knows her public IP:port without any STUN! │
│ 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:**
**Wire Format (Response - Unidirectional):**
Each DHT response (FIND_NODE_RESPONSE, STORE_RESPONSE, FIND_VALUE_RESPONSE)
includes:
includes the requester's observed address:
```
+--------+--------+--------+--------+--------+--------+
| observed_addr (18 bytes) | addr_len (1 byte)|
+--------+--------+--------+--------+--------+--------+
+--------+--------+--------+
| addr_len (1 byte) | observed_addr (0-18 bytes, variable) |
+--------+--------+--------+
IPv4: 4 bytes IP + 2 bytes port = 6 bytes (addr_len = 6)
IPv6: 16 bytes IP + 2 bytes port = 18 bytes (addr_len = 18)
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 |
@@ -425,6 +450,38 @@ def on_dht_response(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