# Request ID and Nonce Design This document explains the roles of `request_id` and `nonce` in the zigp2p protocol, their distinct purposes, and how they work together to provide security. ## Overview The zigp2p protocol uses two different identifiers that serve complementary but distinct security purposes: 1. **Request ID** (`request_id`): Application-layer correlation identifier for DHT messages 2. **Nonce**: Cryptographic replay protection identifier at the protocol layer Understanding the difference between these two is crucial for proper protocol implementation. --- ## 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: ```zig next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1) ``` **Problem**: When multiple nodes started simultaneously, they would all generate the same sequence (1, 2, 3, ...). This caused **false positive replay attacks** at the protocol layer because the replay protection system tracked nonces globally. **Solution**: Initialize with a random value: ```zig var random_start: u64 = undefined; std.crypto.random.bytes(std.mem.asBytes(&random_start)); random_start |= 1; // Ensure non-zero dht.next_request_id.store(random_start, .monotonic); ``` This ensures each node starts from a different point in the u64 space, making collisions astronomically unlikely. ### Example Usage ```zig // Sending a FIND_NODE request const request_id = self.getNextRequestId(); const find_msg = DhtFindNode{ .request_id = request_id, .target_id = target, .sender_id = self.local_id, .auth = auth, }; // Later, match the response if (response.request_id == expected_request_id) { // Handle response } ``` --- ## Nonce (Protocol Layer) ### Purpose Nonces are used for **cryptographic replay protection** at the protocol layer to prevent attackers from replaying captured messages. ### Location - Defined in: `src/protocol/replay_protection.zig` - Checked by: `ReplayProtector.checkMessage()` - Tracked in: `seen_nonces` hash map ### Characteristics - **Type**: `u64` (64-bit unsigned integer) in replay protection - **Scope**: All protocol messages - **Generation**: Varies by layer (often derived from `request_id`) - **Uniqueness**: Must be globally unique across all peers - **Lifetime**: Tracked for `message_ttl` duration (default: 300 seconds) ### How Nonce Replay Protection Works ```zig pub fn checkMessage( self: *ReplayProtector, msg_id: u64, timestamp: i64, nonce: u64, // ← This must be unique globally sequence: u64, peer_id: [32]u8, msg_type: u8, ) !void { // Check nonce uniqueness if (try self.isDuplicateNonce(nonce, timestamp)) { return ReplayError.DuplicateNonce; } // Record nonce as seen try self.seen_nonces.put(nonce, timestamp); } ``` ### Important: Global Nonce Tracking The nonce is tracked **globally** across all peers: ```zig fn isDuplicateNonce(self: *ReplayProtector, nonce: u64, timestamp: i64) !bool { if (self.seen_nonces.get(nonce)) |seen_timestamp| { // Nonce was seen before - reject as replay return true; } return false; } ``` This means: - **Same nonce from different peers = Replay attack detected** - **Same nonce at different times = Replay attack detected** This is why randomizing `request_id` initialization is critical. --- ## MWP Protocol Nonces The **Mutual Witness Protocol (MWP)** uses a different kind of nonce with a different purpose. ### Purpose MWP nonces provide **unbiasable shared randomness** for rendezvous coordination between peers attempting to connect. ### Location - Defined in: `src/mwp/types.zig` - Used in: `MeetingPublication` - Generated during: Publication creation ### Characteristics - **Type**: `[32]u8` (256-bit random value) - **Scope**: MWP meeting point protocol only - **Generation**: Cryptographically random for each publication - **Purpose**: Compute shared rendezvous parameters ### How MWP Nonces Work ```zig pub const MeetingPublication = struct { peer_id: [32]u8, addresses: []const Address, nonce: [32]u8, // ← Random nonce for mutual witness timestamp: i64, ttl: u32, sequence: u64, signature: [64]u8, }; ``` When two peers want to connect: 1. **Alice** publishes with `nonce_A` (32 random bytes) 2. **Bob** publishes with `nonce_B` (32 random bytes) 3. Both compute shared parameters: ```zig shared_randomness = hash(sort(nonce_A, nonce_B)) rendezvous_time = computed from timestamps port_hint = derived from shared_randomness ``` ### Why MWP Nonces Are Different MWP nonces serve a **coordination** purpose, not replay protection: - They ensure neither peer can bias the connection parameters - They're included in DHT publications (not protocol messages) - They're 256 bits (not 64 bits) for stronger randomness guarantees - They don't need to be globally unique across the network --- ## Summary Table | Aspect | DHT Request ID | Protocol Nonce | MWP Nonce | |--------|---------------|----------------|-----------| | **Size** | 64 bits | 64 bits | 256 bits | | **Layer** | DHT Application | Protocol | MWP Application | | **Purpose** | Request/response correlation | Replay protection | Rendezvous coordination | | **Scope** | Per-DHT-node | Global (all peers) | Per-publication | | **Generation** | Random start + increment | Derived/random | Cryptographically random | | **Collision** | Must avoid globally | Must avoid globally | Only needs local uniqueness | | **Tracking** | In `pending_responses` | In `seen_nonces` | Not tracked | --- ## The Bug and Fix ### The Problem Before the fix, the DHT layer used: ```zig next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1) ``` **Scenario**: 1. Bootstrap node starts (request_id counter = 1) 2. Node 2 starts (request_id counter = 1) 3. Node 3 starts (request_id counter = 1) 4. Node 2 sends FIND_NODE to bootstrap (nonce = 1) 5. Node 3 sends FIND_NODE to bootstrap (nonce = 1) 6. Bootstrap node sees **duplicate nonce** → `DuplicateNonce` error **Error Log**: ``` error: SECURITY: Replay attack detected: DuplicateNonce (msg_id=64, peer_hint=d95e8842) warning: DHT: Failed to process message: error.DuplicateNonce ``` ### The Fix Initialize with random starting value: ```zig pub fn init(allocator: Allocator, routing_table: *KademliaRoutingTable, local_id: NodeId) DhtCoordinator { var random_start: u64 = undefined; std.crypto.random.bytes(std.mem.asBytes(&random_start)); random_start |= 1; // Ensure non-zero var dht = DhtCoordinator{ /* ... */ }; dht.next_request_id.store(random_start, .monotonic); return dht; } ``` **Result**: - Each node starts from a different random point in the u64 space - Probability of collision: ~1 in 2^64 (effectively zero) - No more false positive replay detections --- ## Best Practices 1. **Always randomize initial counters** when they're used as nonces 2. **Understand the scope** of your identifiers (per-peer vs global) 3. **Use appropriate sizes**: 64 bits for efficiency, 256 bits for strong randomness 4. **Don't reuse** protocol-layer nonces across different security contexts 5. **Log carefully**: Only log hints (first 4 bytes) of peer IDs for privacy --- ## Related Files - `src/network/dht.zig` - DHT request ID generation and tracking - `src/protocol/replay_protection.zig` - Protocol nonce replay detection - `src/mwp/types.zig` - MWP nonce for rendezvous coordination - `src/protocol/handler.zig` - Message processing with replay checks - `src/protocol/encryption.zig` - Encryption nonce tracking (separate system) --- ## Encryption Layer Nonces Note: There's also a third nonce system in the **encryption layer** (`src/protocol/encryption.zig`): - **Purpose**: Ensure unique initialization vectors for ChaCha20-Poly1305 - **Size**: 12 bytes (96 bits) - **Structure**: 4-byte generation + 8-byte counter - **Tracking**: Per-peer nonce tracker with sliding window This is orthogonal to the request_id and protocol nonce systems and serves purely cryptographic purposes.