From e45bffbd8b100e3340d980aa6dd00d55e0ec70b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Wed, 11 Feb 2026 14:20:16 -0300 Subject: [PATCH] fix crypto: secure zeroization of handshake state, ephemeral keys, derived keys --- src/network/secure_connection.zig | 35 ++++--- src/protocol/crypto.zig | 60 +++++------- src/protocol/encryption.zig | 109 ++++++--------------- src/protocol/handler.zig | 10 +- src/protocol/replay_protection.zig | 84 ++++++++-------- tests/protocol/test_replay_integration.zig | 48 ++++----- tests/protocol/test_replay_protection.zig | 90 ++++++++--------- 7 files changed, 195 insertions(+), 241 deletions(-) diff --git a/src/network/secure_connection.zig b/src/network/secure_connection.zig index 29a0bbf..4a11d4c 100644 --- a/src/network/secure_connection.zig +++ b/src/network/secure_connection.zig @@ -22,6 +22,14 @@ const Role = noise.Role; /// Maximum message size for Noise protocol pub const MAX_MESSAGE_SIZE = noise.MAX_MESSAGE_SIZE; +/// Volatile secure zeroing (prevents compiler from eliding the write) +fn secureZeroBytes(bytes: []u8) void { + const volatile_ptr: [*]volatile u8 = @ptrCast(bytes.ptr); + for (0..bytes.len) |i| { + volatile_ptr[i] = 0; + } +} + /// Authentication tag size pub const TAG_SIZE = noise.TAG_SIZE; @@ -119,6 +127,9 @@ pub const SecureConnection = struct { self.transport = hs.split() catch return Error.HandshakeFailed; self.remote_static_key = hs.rs; self.handshake_complete = true; + + // Zeroize handshake state (ephemeral keys, symmetric state) + secureZeroBytes(std.mem.asBytes(&hs)); } /// Perform handshake as responder (server accepting connection) @@ -145,6 +156,9 @@ pub const SecureConnection = struct { self.transport = hs.split() catch return Error.HandshakeFailed; self.remote_static_key = hs.rs; self.handshake_complete = true; + + // Zeroize handshake state (ephemeral keys, symmetric state) + secureZeroBytes(std.mem.asBytes(&hs)); } /// Send encrypted data (blocking - will sleep on WouldBlock) @@ -333,19 +347,20 @@ pub const SecureConnection = struct { // Private helpers for raw socket I/O during handshake // ========================================================================= + /// Absolute wall-clock timeout for each handshake send/receive operation (nanoseconds) + const HANDSHAKE_TIMEOUT_NS: i128 = 5 * std.time.ns_per_s; + /// Send raw data (unencrypted, for handshake) fn sendRaw(self: *Self, data: []const u8) Error!void { var sent: usize = 0; - var retries: u32 = 0; - const max_retries: u32 = 500; // 5 seconds with 10ms sleep + const deadline = std.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS; while (sent < data.len) { const bytes = self.socket.send(data[sent..]) catch |err| { switch (err) { CoreError.ConnectionTimeout => { - // WouldBlock - retry - retries += 1; - if (retries > max_retries) return Error.HandshakeTimeout; + // WouldBlock - check absolute deadline + if (std.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout; std.Thread.sleep(10 * std.time.ns_per_ms); continue; }, @@ -353,7 +368,6 @@ pub const SecureConnection = struct { } }; sent += bytes; - retries = 0; } } @@ -361,16 +375,14 @@ pub const SecureConnection = struct { /// Returns actual bytes received fn receiveRaw(self: *Self, buffer: []u8, min_bytes: usize) Error!usize { var received: usize = 0; - var retries: u32 = 0; - const max_retries: u32 = 500; // 5 seconds with 10ms sleep + const deadline = std.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS; while (received < min_bytes) { const bytes = self.socket.receive(buffer[received..]) catch |err| { switch (err) { CoreError.ConnectionTimeout => { - // WouldBlock - retry - retries += 1; - if (retries > max_retries) return Error.HandshakeTimeout; + // WouldBlock - check absolute deadline + if (std.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout; std.Thread.sleep(10 * std.time.ns_per_ms); continue; }, @@ -379,7 +391,6 @@ pub const SecureConnection = struct { } }; received += bytes; - retries = 0; } return received; diff --git a/src/protocol/crypto.zig b/src/protocol/crypto.zig index 9b7a51a..820fd99 100644 --- a/src/protocol/crypto.zig +++ b/src/protocol/crypto.zig @@ -874,9 +874,11 @@ pub const CryptoManager = struct { /// CRY-M4 FIX: Derive HMAC key for file integrity from identity key fn deriveFileIntegrityKey(self: *const CryptoManager) [32]u8 { const secret_bytes = self.identity_keypair.secret_key.toBytes(); - const prk = hkdf.HkdfSha256.extract(&[_]u8{}, &secret_bytes); + var prk = hkdf.HkdfSha256.extract(&[_]u8{}, &secret_bytes); var integrity_key: [32]u8 = undefined; hkdf.HkdfSha256.expand(&integrity_key, "zig-p2p-tofu-file-integrity", prk); + // SECURITY: Zeroize PRK after use + secureZero([32]u8, &prk); return integrity_key; } @@ -1341,11 +1343,8 @@ pub const CryptoManager = struct { writer.writeAll(&salt) catch return CryptoError.SaveFailed; // Derive encryption key from password - const encryption_key = deriveKeyFromPassword(password, salt); - defer { - var key_copy = encryption_key; - secureZero([32]u8, &key_copy); - } + var encryption_key = deriveKeyFromPassword(password, salt); + defer secureZero([32]u8, &encryption_key); // Generate random nonce var nonce: [12]u8 = undefined; @@ -1438,11 +1437,8 @@ pub const CryptoManager = struct { reader.readNoEof(&salt) catch return CryptoError.InvalidFormat; // Derive decryption key from password - const decryption_key = deriveKeyFromPassword(password, salt); - defer { - var key_copy = decryption_key; - secureZero([32]u8, &key_copy); - } + var decryption_key = deriveKeyFromPassword(password, salt); + defer secureZero([32]u8, &decryption_key); // Read nonce var nonce: [12]u8 = undefined; @@ -1568,11 +1564,8 @@ pub const CryptoManager = struct { writer.writeAll(&salt) catch return CryptoError.SaveFailed; // Derive encryption key - const encryption_key = deriveKeyFromPassword(password, salt); - defer { - var key_copy = encryption_key; - secureZero([32]u8, &key_copy); - } + var encryption_key = deriveKeyFromPassword(password, salt); + defer secureZero([32]u8, &encryption_key); // Generate and write nonce var nonce: [12]u8 = undefined; @@ -1655,11 +1648,8 @@ pub const CryptoManager = struct { reader.readNoEof(&salt) catch return CryptoError.InvalidFormat; // Derive decryption key - const decryption_key = deriveKeyFromPassword(password, salt); - defer { - var key_copy = decryption_key; - secureZero([32]u8, &key_copy); - } + var decryption_key = deriveKeyFromPassword(password, salt); + defer secureZero([32]u8, &decryption_key); // Read nonce var nonce: [12]u8 = undefined; @@ -2456,8 +2446,8 @@ pub const CryptoManager = struct { // Generate our ephemeral key pair var key_pair = try KeyExchange.generateKeyPair(); - // CRY-H3 FIX: Zeroize ephemeral secret on error to prevent leakage - errdefer secureZero([32]u8, &key_pair.secret); + // Zeroize local stack copy after stored copy goes into key_exchanges + defer secureZero([32]u8, &key_pair.secret); // SECURITY: Sign our_public || our_timestamp || their_session_nonce // This binds our response to the specific initiator session @@ -2792,23 +2782,23 @@ pub const CryptoManager = struct { /// CRIT-4 FIX: Remove all keys for a peer (used when key confirmation fails) /// This invalidates the session and requires a new key exchange. pub fn removeKey(self: *CryptoManager, peer_id: [32]u8) void { - // Remove encryption key - if (self.peer_keys.fetchRemove(peer_id)) |entry| { - var key_copy = entry.value; - secureZero([32]u8, &key_copy); + // Zeroize encryption key in-place before removing from map + if (self.peer_keys.getPtr(peer_id)) |key_ptr| { + secureZero([32]u8, key_ptr); } + _ = self.peer_keys.remove(peer_id); - // Remove HMAC key - if (self.hmac_keys.fetchRemove(peer_id)) |entry| { - var key_copy = entry.value; - secureZero([32]u8, &key_copy); + // Zeroize HMAC key in-place before removing from map + if (self.hmac_keys.getPtr(peer_id)) |key_ptr| { + secureZero([32]u8, key_ptr); } + _ = self.hmac_keys.remove(peer_id); - // Remove any pending key exchange - if (self.key_exchanges.fetchRemove(peer_id)) |entry| { - var secret_copy = entry.value.our_secret; - secureZero([32]u8, &secret_copy); + // Zeroize key exchange secret in-place before removing + if (self.key_exchanges.getPtr(peer_id)) |exchange_ptr| { + secureZero([32]u8, &exchange_ptr.our_secret); } + _ = self.key_exchanges.remove(peer_id); // Remove ratchet counter _ = self.ratchet_counters.remove(peer_id); diff --git a/src/protocol/encryption.zig b/src/protocol/encryption.zig index 01369ff..75e9f45 100644 --- a/src/protocol/encryption.zig +++ b/src/protocol/encryption.zig @@ -186,72 +186,24 @@ pub const NonceTracker = struct { /// Internal record without locking (caller must hold mutex) fn recordLocked(self: *NonceTracker, nonce: [12]u8) !void { + const parsed = parseNonce(nonce); const nonce_key = self.nonceToFullKey(nonce); - // CRY-2 FIX: Proper eviction - remove oldest 25% of entries based on counter values - // instead of clearing everything (which opens replay window) - // CRIT-NEW-18 FIX: Loop to evict all needed entries instead of fixed 256 limit + // Track the highest counter we've seen for eviction threshold calculation + if (parsed.counter > self.highest_counter) { + self.highest_counter = parsed.counter; + } + + // Sliding-window eviction: when full, advance min_allowed_counter and clear. + // The min_allowed_counter check in checkLocked() rejects any replayed nonces + // that were evicted, so clearing the set is safe. if (self.seen_nonces.count() >= self.max_tracked_nonces) { - // Calculate eviction threshold - remove nonces with counters in lowest 25% - // This is based on the assumption that lower counters are older - const target_evict_count = self.max_tracked_nonces / 4; - var total_evicted: usize = 0; - var max_evicted_counter: u32 = 0; - - // CRIT-NEW-18 FIX: Loop until we've evicted enough entries - // Each iteration evicts up to BATCH_SIZE entries to avoid stack overflow - const BATCH_SIZE: usize = 256; - while (total_evicted < target_evict_count and self.seen_nonces.count() > 0) { - // Find minimum counter value to use as eviction threshold - var min_counter: u32 = std.math.maxInt(u32); - var iter1 = self.seen_nonces.keyIterator(); - while (iter1.next()) |key_ptr| { - const counter: u32 = @intCast((key_ptr.* >> 32) & 0xFFFFFFFF); - if (counter < min_counter) { - min_counter = counter; - } - } - - // Calculate threshold for this batch - const remaining_to_evict = target_evict_count - total_evicted; - const batch_evict = @min(remaining_to_evict, BATCH_SIZE); - const evict_range: u32 = @intCast(@min(batch_evict, std.math.maxInt(u32))); - const eviction_threshold = std.math.add(u32, min_counter, evict_range) catch std.math.maxInt(u32); - - // Collect keys to evict in this batch - var keys_to_evict: [BATCH_SIZE]u64 = undefined; - var evict_idx: usize = 0; - - var iter2 = self.seen_nonces.keyIterator(); - while (iter2.next()) |key_ptr| { - if (evict_idx >= BATCH_SIZE) break; - const counter: u32 = @intCast((key_ptr.* >> 32) & 0xFFFFFFFF); - if (counter < eviction_threshold) { - keys_to_evict[evict_idx] = key_ptr.*; - evict_idx += 1; - if (counter > max_evicted_counter) { - max_evicted_counter = counter; - } - } - } - - // No more entries to evict in this threshold - break to prevent infinite loop - if (evict_idx == 0) break; - - // Evict collected keys - for (0..evict_idx) |idx| { - _ = self.seen_nonces.remove(keys_to_evict[idx]); - } - total_evicted += evict_idx; - } - - // SEC-H4 FIX: Update min_allowed_counter to prevent replay of evicted nonces - // Any nonce with counter <= max_evicted_counter will be rejected - if (total_evicted > 0) { - // Add 1 because we want to reject counters UP TO AND INCLUDING the max evicted - self.min_allowed_counter = @max(self.min_allowed_counter, max_evicted_counter + 1); - std.log.debug("SEC-H4: Evicted {d} old nonces, min_allowed_counter now {d}", .{ total_evicted, self.min_allowed_counter }); - } + // Keep a window of 3/4 of max_tracked_nonces below highest_counter + const window: u32 = @intCast(@min(self.max_tracked_nonces * 3 / 4, std.math.maxInt(u32))); + const new_min = self.highest_counter -| window; + self.min_allowed_counter = @max(self.min_allowed_counter, new_min); + self.seen_nonces.clearRetainingCapacity(); + std.log.debug("Nonce tracker eviction: min_allowed_counter now {d}", .{self.min_allowed_counter}); } try self.seen_nonces.put(nonce_key, {}); } @@ -456,44 +408,36 @@ pub const EncryptionKey = struct { /// Returns a 12-byte nonce combining generation + counter + random /// Returns error if nonce space is exhausted and key rotation is required pub fn getNextNonce(self: *EncryptionKey) ![12]u8 { - // CRITICAL: Check for nonce exhaustion BEFORE using the counter - // This prevents nonce wraparound which would catastrophically break security - // CRIT-NEW-16 FIX: Use atomic load - const current_counter = self.nonce_counter.load(.acquire); + // Atomically claim a unique counter value. fetchAdd guarantees no two + // threads get the same counter regardless of memory ordering. + // Using .monotonic since we only need atomicity, not ordering — + // the nonce value is used locally and the encryption call provides + // its own barriers. + const current_counter = self.nonce_counter.fetchAdd(1, .monotonic); + if (current_counter >= NONCE_ROTATION_THRESHOLD) { self.needs_rotation = true; - // SECURITY FIX: Zeroize key material on nonce exhaustion self.onNonceExhaustion(); return crypto.CryptoError.NonceExhaustion; } var nonce: [12]u8 = undefined; - // MED-2 FIX: Validate generation fits in u32 before truncation - // This should never happen in practice (would require 2^32+ key rotations) - // but we check for defense in depth if (self.generation > std.math.maxInt(u32)) { - std.log.err("MED-2 SECURITY: Generation counter overflow - nonce uniqueness compromised!", .{}); + std.log.err("SECURITY: Generation counter overflow - nonce uniqueness compromised!", .{}); self.needs_rotation = true; return crypto.CryptoError.NonceExhaustion; } // First 4 bytes: generation (prevents nonce reuse across key rotations) - // SAFETY: Validated above that generation fits in u32 std.mem.writeInt(u32, nonce[0..4], @as(u32, @intCast(self.generation)), .little); - // Next 4 bytes: counter (prevents nonce reuse within key generation) - // SAFETY: nonce_counter is checked against NONCE_ROTATION_THRESHOLD (< u32 max) - // CRIT-NEW-16 FIX: Use value already loaded atomically above + // Next 4 bytes: counter (unique per fetchAdd, fits in u32 due to threshold) std.mem.writeInt(u32, nonce[4..8], @as(u32, @intCast(current_counter)), .little); // Last 4 bytes: random (additional entropy) std.crypto.random.bytes(nonce[8..12]); - // Increment counter atomically - // CRIT-NEW-16 FIX: Use atomic fetchAdd for thread safety - _ = self.nonce_counter.fetchAdd(1, .release); - return nonce; } @@ -828,13 +772,16 @@ pub const EncryptionManager = struct { var new_hmac_key: [32]u8 = undefined; // Derive encryption key - const enc_prk = std.crypto.kdf.hkdf.HkdfSha256.extract(&salt_buf, ¤t.key); + var enc_prk = std.crypto.kdf.hkdf.HkdfSha256.extract(&salt_buf, ¤t.key); std.crypto.kdf.hkdf.HkdfSha256.expand(&new_enc_key_bytes, enc_info, enc_prk); // SECURITY: Also derive new HMAC key from the same root key // This ensures HMAC and encryption keys are rotated together std.crypto.kdf.hkdf.HkdfSha256.expand(&new_hmac_key, hmac_info, enc_prk); + // Zeroize PRK after use + crypto.secureZero([32]u8, &enc_prk); + // Create new encryption key with previous key stored for in-flight messages // CRY-M2 FIX: Use setPreviousKey to track timestamp for expiry var new_enc_key = EncryptionKey.init(new_enc_key_bytes, new_generation); diff --git a/src/protocol/handler.zig b/src/protocol/handler.zig index 85bb759..9a01e05 100644 --- a/src/protocol/handler.zig +++ b/src/protocol/handler.zig @@ -1,5 +1,6 @@ //! Message handler framework const std = @import("std"); +const core = @import("core"); const protocol = @import("protocol.zig"); const message = @import("message.zig"); const serializer = @import("serializer.zig"); @@ -1024,6 +1025,8 @@ pub const HandlerRegistry = struct { self.context.source_peer_id = source_id; defer self.context.source_peer_id = null; + const msg_type = msg.getType(); + // SECURITY: Check for replay attack (compile-time enforced, cannot be disabled) if (comptime REQUIRE_REPLAY_PROTECTION) { self.replay_protector.checkMessage( @@ -1032,6 +1035,7 @@ pub const HandlerRegistry = struct { nonce, sequence, source_id, + @intFromEnum(msg_type), ) catch |err| { // Replay detected - reject message and record failure self.context.metrics.recordMessageFailed(); @@ -1049,8 +1053,6 @@ pub const HandlerRegistry = struct { }; } - const msg_type = msg.getType(); - // FIX: Copy handlers while holding lock, then release lock before calling handlers // This prevents deadlock if a handler tries to register/unregister handlers var handlers_copy: std.ArrayList(MessageHandler) = .{}; @@ -1301,8 +1303,6 @@ pub const DiscoveryHandler = struct { // 1. Add known nodes to peer list // MEM-M1 FIX: Use type-safe getter instead of direct cast if (context.getPeerManager() catch null) |pm| { - const core = @import("core"); - for (msg.known_nodes) |_| { // Create address from node ID (simplified - in production would use proper addressing) var addr = core.Address.init(); @@ -1377,7 +1377,7 @@ pub const DiscoveryHandler = struct { if (context.getPeerManager() catch null) |pm| { const network = @import("network"); const peer_id = network.PeerId{ .bytes = source_id }; - const core = @import("core"); + // Check if peer exists (getPeerById returns a copy for thread safety) if (pm.getPeerById(peer_id)) |_| { diff --git a/src/protocol/replay_protection.zig b/src/protocol/replay_protection.zig index 584dd38..28eced4 100644 --- a/src/protocol/replay_protection.zig +++ b/src/protocol/replay_protection.zig @@ -37,13 +37,15 @@ const MessageEntry = struct { const PeerMessageKey = struct { peer_id_prefix: [8]u8, // First 8 bytes of peer ID for compact storage msg_id: u64, + msg_type: u8, // Distinguishes request/response with same request_id - pub fn init(peer_id: [32]u8, msg_id: u64) PeerMessageKey { + pub fn init(peer_id: [32]u8, msg_id: u64, msg_type: u8) PeerMessageKey { var prefix: [8]u8 = undefined; @memcpy(&prefix, peer_id[0..8]); return .{ .peer_id_prefix = prefix, .msg_id = msg_id, + .msg_type = msg_type, }; } }; @@ -208,6 +210,7 @@ pub const ReplayProtector = struct { nonce: u64, sequence: u64, peer_id: [32]u8, + msg_type: u8, ) !void { self.mutex.lock(); defer self.mutex.unlock(); @@ -239,8 +242,9 @@ pub const ReplayProtector = struct { // 1. Validate timestamp try self.validateTimestamp(timestamp, current_time); - // 2. Check for duplicate message ID (per-peer to avoid collisions) - if (try self.isReplay(peer_id, msg_id, timestamp, nonce)) { + // 2. Check for duplicate message ID (per-peer, per-type to avoid collisions + // between request/response pairs that share the same request_id) + if (try self.isReplay(peer_id, msg_id, msg_type, timestamp, nonce)) { return ReplayError.DuplicateMessageId; } @@ -266,8 +270,8 @@ pub const ReplayProtector = struct { try self.checkSequence(peer_id, sequence, current_time); } - // 5. Record this message as seen (per-peer key) - const key = PeerMessageKey.init(peer_id, msg_id); + // 5. Record this message as seen (per-peer, per-type key) + const key = PeerMessageKey.init(peer_id, msg_id, msg_type); try self.seen_messages.put(key, .{ .timestamp = timestamp, .nonce = nonce, @@ -299,10 +303,10 @@ pub const ReplayProtector = struct { } /// Check if message ID was seen before (per-peer) - /// Uses PeerMessageKey to ensure message IDs are tracked per-peer, - /// avoiding collisions when different peers use the same sequence numbers - fn isReplay(self: *ReplayProtector, peer_id: [32]u8, msg_id: u64, timestamp: i64, nonce: u64) !bool { - const key = PeerMessageKey.init(peer_id, msg_id); + /// Uses PeerMessageKey to ensure message IDs are tracked per-peer and per-type, + /// avoiding collisions between request/response pairs that share the same request_id + fn isReplay(self: *ReplayProtector, peer_id: [32]u8, msg_id: u64, msg_type: u8, timestamp: i64, nonce: u64) !bool { + const key = PeerMessageKey.init(peer_id, msg_id, msg_type); if (self.seen_messages.get(key)) |entry| { // Found duplicate message ID from this peer // Additional check: if timestamp and nonce match, it's definitely a replay @@ -580,7 +584,7 @@ test "timestamp validation - reject old timestamps" { const old_timestamp = current_time - 7200; // 2 hours ago const peer_id = [_]u8{1} ** 32; - const result = protector.checkMessage(1, old_timestamp, 1000, 0, peer_id); + const result = protector.checkMessage(1, old_timestamp, 1000, 0, peer_id, 0); try std.testing.expectError(ReplayError.TimestampTooOld, result); } @@ -593,7 +597,7 @@ test "timestamp validation - reject future timestamps" { const future_timestamp = current_time + 600; // 10 minutes in future const peer_id = [_]u8{1} ** 32; - const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id); + const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id, 0); try std.testing.expectError(ReplayError.TimestampTooFarInFuture, result); } @@ -607,7 +611,7 @@ test "timestamp validation - accept valid timestamps" { const valid_timestamp = current_time - 5; const peer_id = [_]u8{1} ** 32; - try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id); + try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id, 0); const stats = protector.getStats(); try std.testing.expectEqual(@as(usize, 1), stats.tracked_messages); @@ -621,10 +625,10 @@ test "duplicate message ID detection" { const peer_id = [_]u8{1} ** 32; // First message should succeed - try protector.checkMessage(42, current_time, 1000, 0, peer_id); + try protector.checkMessage(42, current_time, 1000, 0, peer_id, 0); // Duplicate message ID should fail - const result = protector.checkMessage(42, current_time, 1001, 0, peer_id); + const result = protector.checkMessage(42, current_time, 1001, 0, peer_id, 0); try std.testing.expectError(ReplayError.DuplicateMessageId, result); } @@ -636,10 +640,10 @@ test "duplicate nonce detection" { const peer_id = [_]u8{1} ** 32; // First message with nonce 5000 - try protector.checkMessage(1, current_time, 5000, 0, peer_id); + try protector.checkMessage(1, current_time, 5000, 0, peer_id, 0); // Different message ID but same nonce should fail - const result = protector.checkMessage(2, current_time, 5000, 0, peer_id); + const result = protector.checkMessage(2, current_time, 5000, 0, peer_id, 0); try std.testing.expectError(ReplayError.DuplicateNonce, result); } @@ -651,9 +655,9 @@ test "sequence number enforcement - in order" { const peer_id = [_]u8{1} ** 32; // Send messages in order - try protector.checkMessage(1, current_time, 1000, 1, peer_id); - try protector.checkMessage(2, current_time + 1, 1001, 2, peer_id); - try protector.checkMessage(3, current_time + 2, 1002, 3, peer_id); + try protector.checkMessage(1, current_time, 1000, 1, peer_id, 0); + try protector.checkMessage(2, current_time + 1, 1001, 2, peer_id, 0); + try protector.checkMessage(3, current_time + 2, 1002, 3, peer_id, 0); const stats = protector.getStats(); try std.testing.expectEqual(@as(usize, 1), stats.tracked_peers); @@ -667,10 +671,10 @@ test "sequence number enforcement - out of order within window" { const peer_id = [_]u8{2} ** 32; // Send sequence 1, 2, 5, then 3 (out of order but within window) - try protector.checkMessage(1, current_time, 2000, 1, peer_id); - try protector.checkMessage(2, current_time + 1, 2001, 2, peer_id); - try protector.checkMessage(3, current_time + 2, 2002, 5, peer_id); - try protector.checkMessage(4, current_time + 3, 2003, 3, peer_id); + try protector.checkMessage(1, current_time, 2000, 1, peer_id, 0); + try protector.checkMessage(2, current_time + 1, 2001, 2, peer_id, 0); + try protector.checkMessage(3, current_time + 2, 2002, 5, peer_id, 0); + try protector.checkMessage(4, current_time + 3, 2003, 3, peer_id, 0); } test "sequence number enforcement - reject duplicate sequence" { @@ -681,10 +685,10 @@ test "sequence number enforcement - reject duplicate sequence" { const peer_id = [_]u8{3} ** 32; // Send sequence 1, 2, then 2 again - try protector.checkMessage(1, current_time, 3000, 1, peer_id); - try protector.checkMessage(2, current_time + 1, 3001, 2, peer_id); + try protector.checkMessage(1, current_time, 3000, 1, peer_id, 0); + try protector.checkMessage(2, current_time + 1, 3001, 2, peer_id, 0); - const result = protector.checkMessage(3, current_time + 2, 3002, 2, peer_id); + const result = protector.checkMessage(3, current_time + 2, 3002, 2, peer_id, 0); try std.testing.expectError(ReplayError.DuplicateMessageId, result); } @@ -696,9 +700,9 @@ test "sequence number enforcement - reject too old sequence" { const peer_id = [_]u8{4} ** 32; // Send sequence 100, then try to send sequence 1 (too old, outside window) - try protector.checkMessage(1, current_time, 4000, 100, peer_id); + try protector.checkMessage(1, current_time, 4000, 100, peer_id, 0); - const result = protector.checkMessage(2, current_time + 1, 4001, 1, peer_id); + const result = protector.checkMessage(2, current_time + 1, 4001, 1, peer_id, 0); try std.testing.expectError(ReplayError.SequenceTooOld, result); } @@ -710,13 +714,13 @@ test "sliding window - large sequence jump" { const peer_id = [_]u8{5} ** 32; // Small sequence - try protector.checkMessage(1, current_time, 5000, 10, peer_id); + try protector.checkMessage(1, current_time, 5000, 10, peer_id, 0); // Large jump (> window size) - try protector.checkMessage(2, current_time + 1, 5001, 200, peer_id); + try protector.checkMessage(2, current_time + 1, 5001, 200, peer_id, 0); // Should accept because window was reset - try protector.checkMessage(3, current_time + 2, 5002, 201, peer_id); + try protector.checkMessage(3, current_time + 2, 5002, 201, peer_id, 0); } test "cleanup removes old entries" { @@ -730,8 +734,8 @@ test "cleanup removes old entries" { const peer_id = [_]u8{6} ** 32; // Add messages with current timestamp (within TTL window) - try protector.checkMessage(1, base_time, 6000, 1, peer_id); - try protector.checkMessage(2, base_time, 6001, 2, peer_id); + try protector.checkMessage(1, base_time, 6000, 1, peer_id, 0); + try protector.checkMessage(2, base_time, 6001, 2, peer_id, 0); var stats = protector.getStats(); try std.testing.expectEqual(@as(usize, 2), stats.tracked_messages); @@ -754,14 +758,14 @@ test "peer sequence reset" { const peer_id = [_]u8{7} ** 32; // Send some messages - try protector.checkMessage(1, current_time, 7000, 5, peer_id); - try protector.checkMessage(2, current_time + 1, 7001, 6, peer_id); + try protector.checkMessage(1, current_time, 7000, 5, peer_id, 0); + try protector.checkMessage(2, current_time + 1, 7001, 6, peer_id, 0); // Reset peer sequence try protector.resetPeerSequence(peer_id); // Should be able to start from sequence 1 again - try protector.checkMessage(3, current_time + 2, 7002, 1, peer_id); + try protector.checkMessage(3, current_time + 2, 7002, 1, peer_id, 0); } test "multiple peers tracked independently" { @@ -773,10 +777,10 @@ test "multiple peers tracked independently" { const peer2 = [_]u8{2} ** 32; // Send messages from different peers - try protector.checkMessage(1, current_time, 8000, 1, peer1); - try protector.checkMessage(2, current_time, 8001, 1, peer2); - try protector.checkMessage(3, current_time + 1, 8002, 2, peer1); - try protector.checkMessage(4, current_time + 1, 8003, 2, peer2); + try protector.checkMessage(1, current_time, 8000, 1, peer1, 0); + try protector.checkMessage(2, current_time, 8001, 1, peer2, 0); + try protector.checkMessage(3, current_time + 1, 8002, 2, peer1, 0); + try protector.checkMessage(4, current_time + 1, 8003, 2, peer2, 0); const stats = protector.getStats(); try std.testing.expectEqual(@as(usize, 2), stats.tracked_peers); diff --git a/tests/protocol/test_replay_integration.zig b/tests/protocol/test_replay_integration.zig index 6c949f4..533b826 100644 --- a/tests/protocol/test_replay_integration.zig +++ b/tests/protocol/test_replay_integration.zig @@ -52,6 +52,7 @@ test "replay protection: old timestamp is rejected" { 1000, 0, peer_id, + 0, ); try testing.expectError(replay_protection.ReplayError.TimestampTooOld, result); @@ -75,6 +76,7 @@ test "replay protection: future timestamp is rejected" { 1000, 0, peer_id, + 0, ); try testing.expectError(replay_protection.ReplayError.TimestampTooFarInFuture, result); @@ -121,8 +123,8 @@ test "replay protection: cleanup removes old entries" { // Add some messages with old timestamps const old_time = std.time.timestamp() - 2; - _ = try registry.replay_protector.checkMessage(1, old_time, 1000, 1, peer_id); - _ = try registry.replay_protector.checkMessage(2, old_time, 1001, 2, peer_id); + _ = try registry.replay_protector.checkMessage(1, old_time, 1000, 1, peer_id, 0); + _ = try registry.replay_protector.checkMessage(2, old_time, 1001, 2, peer_id, 0); var stats = registry.getReplayStats(); try testing.expect(stats.tracked_messages > 0); @@ -147,20 +149,20 @@ test "replay protection: per-peer sequence tracking" { const current_time = std.time.timestamp(); // Peer 1 sends messages in order - try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer1); - try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 2, peer1); - try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 3, peer1); + try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer1, 0); + try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 2, peer1, 0); + try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 3, peer1, 0); // Peer 2 can use same sequences independently - try registry.replay_protector.checkMessage(10, current_time, 2000, 1, peer2); - try registry.replay_protector.checkMessage(11, current_time + 1, 2001, 2, peer2); + try registry.replay_protector.checkMessage(10, current_time, 2000, 1, peer2, 0); + try registry.replay_protector.checkMessage(11, current_time + 1, 2001, 2, peer2, 0); // Both peers tracked const stats = registry.getReplayStats(); try testing.expectEqual(@as(usize, 2), stats.tracked_peers); // Replay from peer1 should fail - const result = registry.replay_protector.checkMessage(4, current_time + 3, 1003, 2, peer1); + const result = registry.replay_protector.checkMessage(4, current_time + 3, 1003, 2, peer1, 0); try testing.expectError(replay_protection.ReplayError.DuplicateMessageId, result); } @@ -174,10 +176,10 @@ test "replay protection: nonce uniqueness" { const current_time = std.time.timestamp(); // First message with nonce 5000 - try registry.replay_protector.checkMessage(100, current_time, 5000, 0, peer_id); + try registry.replay_protector.checkMessage(100, current_time, 5000, 0, peer_id, 0); // Different message ID but same nonce should fail - const result = registry.replay_protector.checkMessage(101, current_time + 1, 5000, 0, peer_id); + const result = registry.replay_protector.checkMessage(101, current_time + 1, 5000, 0, peer_id, 0); try testing.expectError(replay_protection.ReplayError.DuplicateNonce, result); } @@ -191,12 +193,12 @@ test "replay protection: out-of-order messages within window" { const current_time = std.time.timestamp(); // Send sequence 1, 2, 5, then 3 (out of order but within window) - try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer_id); - try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 2, peer_id); - try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 5, peer_id); + try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer_id, 0); + try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 2, peer_id, 0); + try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 5, peer_id, 0); // Message 3 (out of order) should be accepted - try registry.replay_protector.checkMessage(4, current_time + 3, 1003, 3, peer_id); + try registry.replay_protector.checkMessage(4, current_time + 3, 1003, 3, peer_id, 0); } /// Test sequences too old (outside window) are rejected @@ -209,10 +211,10 @@ test "replay protection: sequences too old are rejected" { const current_time = std.time.timestamp(); // Send sequence 100 (establishes baseline) - try registry.replay_protector.checkMessage(1, current_time, 1000, 100, peer_id); + try registry.replay_protector.checkMessage(1, current_time, 1000, 100, peer_id, 0); // Try to send sequence 1 (too old, outside 64-message window) - const result = registry.replay_protector.checkMessage(2, current_time + 1, 1001, 1, peer_id); + const result = registry.replay_protector.checkMessage(2, current_time + 1, 1001, 1, peer_id, 0); try testing.expectError(replay_protection.ReplayError.SequenceTooOld, result); } @@ -226,14 +228,14 @@ test "replay protection: peer sequence reset" { const current_time = std.time.timestamp(); // Send some messages - try registry.replay_protector.checkMessage(1, current_time, 1000, 5, peer_id); - try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 6, peer_id); + try registry.replay_protector.checkMessage(1, current_time, 1000, 5, peer_id, 0); + try registry.replay_protector.checkMessage(2, current_time + 1, 1001, 6, peer_id, 0); // Reset peer sequence (simulating reconnection) try registry.resetPeerReplayState(peer_id); // Should be able to start from sequence 1 again - try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 1, peer_id); + try registry.replay_protector.checkMessage(3, current_time + 2, 1002, 1, peer_id, 0); } /// Test integration: message processing with replay protection enabled @@ -297,8 +299,8 @@ test "replay protection: statistics reporting" { const current_time = std.time.timestamp(); // Add some messages - try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer1); - try registry.replay_protector.checkMessage(2, current_time, 2000, 1, peer2); + try registry.replay_protector.checkMessage(1, current_time, 1000, 1, peer1, 0); + try registry.replay_protector.checkMessage(2, current_time, 2000, 1, peer2, 0); const stats = registry.getReplayStats(); @@ -321,14 +323,14 @@ test "replay protection: automatic cleanup during check" { // Add old message (already stale with 0 TTL) const old_time = std.time.timestamp() - 1; - _ = try registry.replay_protector.checkMessage(1, old_time, 1000, 1, peer_id); + _ = try registry.replay_protector.checkMessage(1, old_time, 1000, 1, peer_id, 0); // Brief wait to ensure cleanup can trigger std.time.sleep(50 * std.time.ns_per_ms); // Add new message (should trigger automatic cleanup) const current_time = std.time.timestamp(); - try registry.replay_protector.checkMessage(2, current_time, 2000, 2, peer_id); + try registry.replay_protector.checkMessage(2, current_time, 2000, 2, peer_id, 0); // Old message should have been cleaned up automatically const stats = registry.getReplayStats(); diff --git a/tests/protocol/test_replay_protection.zig b/tests/protocol/test_replay_protection.zig index b6d1941..1bce290 100644 --- a/tests/protocol/test_replay_protection.zig +++ b/tests/protocol/test_replay_protection.zig @@ -92,11 +92,11 @@ test "ReplayProtector: timestamp at exact TTL boundary" { // Message at exactly TTL boundary (10 seconds old with 10s TTL) // validateTimestamp uses (time_diff < -message_ttl), so exactly at boundary is accepted const boundary_timestamp = current_time - protector.message_ttl; - try protector.checkMessage(1, boundary_timestamp, 1000, 0, peer_id); + try protector.checkMessage(1, boundary_timestamp, 1000, 0, peer_id, 0); // Message just past TTL boundary should be rejected const past_boundary = current_time - protector.message_ttl - 1; - const result = protector.checkMessage(2, past_boundary, 1001, 0, peer_id); + const result = protector.checkMessage(2, past_boundary, 1001, 0, peer_id, 0); try testing.expectError(ReplayError.TimestampTooOld, result); } @@ -109,7 +109,7 @@ test "ReplayProtector: timestamp just within TTL" { // Message just within TTL boundary const valid_timestamp = current_time - protector.message_ttl + 1; - try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id); + try protector.checkMessage(1, valid_timestamp, 1000, 0, peer_id, 0); const stats = protector.getStats(); try testing.expectEqual(@as(usize, 1), stats.tracked_messages); @@ -125,7 +125,7 @@ test "ReplayProtector: timestamp at exact clock skew boundary" { // Message at exactly clock skew boundary (5 seconds in future with 5s skew) // This should be accepted const boundary_timestamp = current_time + protector.max_clock_skew; - try protector.checkMessage(1, boundary_timestamp, 1000, 0, peer_id); + try protector.checkMessage(1, boundary_timestamp, 1000, 0, peer_id, 0); const stats = protector.getStats(); try testing.expectEqual(@as(usize, 1), stats.tracked_messages); @@ -140,7 +140,7 @@ test "ReplayProtector: timestamp just beyond clock skew" { // Message just beyond clock skew boundary const future_timestamp = current_time + protector.max_clock_skew + 1; - const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id); + const result = protector.checkMessage(1, future_timestamp, 1000, 0, peer_id, 0); try testing.expectError(ReplayError.TimestampTooFarInFuture, result); } @@ -160,7 +160,7 @@ test "ReplayProtector: nonce with very future timestamp rejected" { const far_future = current_time + 120; // 2 minutes in future // This will be rejected by validateTimestamp first (TimestampTooFarInFuture) - const result = protector.checkMessage(1, far_future, 2000, 0, peer_id); + const result = protector.checkMessage(1, far_future, 2000, 0, peer_id, 0); try testing.expectError(ReplayError.TimestampTooFarInFuture, result); } @@ -175,7 +175,7 @@ test "ReplayProtector: nonce reuse after TTL expiry allowed" { const peer_id = [_]u8{3} ** 32; // Add a message with nonce 3000 - try protector.checkMessage(1, base_time, 3000, 0, peer_id); + try protector.checkMessage(1, base_time, 3000, 0, peer_id, 0); // Force cleanup with future time to expire the nonce protector.cleanup(base_time + 10); @@ -183,7 +183,7 @@ test "ReplayProtector: nonce reuse after TTL expiry allowed" { // Now nonce 3000 should be allowed again (with new message ID and timestamp) // Note: we need a valid timestamp relative to real current time const new_time = std.time.timestamp(); - try protector.checkMessage(2, new_time, 3000, 0, peer_id); + try protector.checkMessage(2, new_time, 3000, 0, peer_id, 0); } // ============================================================================ @@ -198,9 +198,9 @@ test "ReplayProtector: sequence 0 is always accepted" { const peer_id = [_]u8{4} ** 32; // Sequence 0 is reserved for non-ordered messages - try protector.checkMessage(1, current_time, 4000, 0, peer_id); - try protector.checkMessage(2, current_time + 1, 4001, 0, peer_id); - try protector.checkMessage(3, current_time + 2, 4002, 0, peer_id); + try protector.checkMessage(1, current_time, 4000, 0, peer_id, 0); + try protector.checkMessage(2, current_time + 1, 4001, 0, peer_id, 0); + try protector.checkMessage(3, current_time + 2, 4002, 0, peer_id, 0); // No peer should be tracked for sequence 0 messages const stats = protector.getStats(); @@ -215,13 +215,13 @@ test "ReplayProtector: sequence at window boundary" { const peer_id = [_]u8{5} ** 32; // Send sequence 100 - try protector.checkMessage(1, current_time, 5000, 100, peer_id); + try protector.checkMessage(1, current_time, 5000, 100, peer_id, 0); // Sequence 37 is at position 63 (100 - 37 = 63), which is the last bit in the window - try protector.checkMessage(2, current_time + 1, 5001, 37, peer_id); + try protector.checkMessage(2, current_time + 1, 5001, 37, peer_id, 0); // Sequence 36 is at position 64, which is outside the window (WINDOW_SIZE = 64) - const result = protector.checkMessage(3, current_time + 2, 5002, 36, peer_id); + const result = protector.checkMessage(3, current_time + 2, 5002, 36, peer_id, 0); try testing.expectError(ReplayError.SequenceTooOld, result); } @@ -233,12 +233,12 @@ test "ReplayProtector: sequence replay in sliding window" { const peer_id = [_]u8{6} ** 32; // Send sequences 1, 5, then 3 (out of order) - try protector.checkMessage(1, current_time, 6000, 1, peer_id); - try protector.checkMessage(2, current_time + 1, 6001, 5, peer_id); - try protector.checkMessage(3, current_time + 2, 6002, 3, peer_id); + try protector.checkMessage(1, current_time, 6000, 1, peer_id, 0); + try protector.checkMessage(2, current_time + 1, 6001, 5, peer_id, 0); + try protector.checkMessage(3, current_time + 2, 6002, 3, peer_id, 0); // Replay sequence 3 should fail (InvalidSequence - already in window) - const result = protector.checkMessage(4, current_time + 3, 6003, 3, peer_id); + const result = protector.checkMessage(4, current_time + 3, 6003, 3, peer_id, 0); try testing.expectError(ReplayError.InvalidSequence, result); } @@ -250,10 +250,10 @@ test "ReplayProtector: sequence exactly at last_sequence" { const peer_id = [_]u8{7} ** 32; // Send sequence 10 - try protector.checkMessage(1, current_time, 7000, 10, peer_id); + try protector.checkMessage(1, current_time, 7000, 10, peer_id, 0); // Send sequence 10 again (duplicate) - const result = protector.checkMessage(2, current_time + 1, 7001, 10, peer_id); + const result = protector.checkMessage(2, current_time + 1, 7001, 10, peer_id, 0); try testing.expectError(ReplayError.DuplicateMessageId, result); } @@ -265,13 +265,13 @@ test "ReplayProtector: large sequence jump resets window" { const peer_id = [_]u8{8} ** 32; // Send sequence 10 - try protector.checkMessage(1, current_time, 8000, 10, peer_id); + try protector.checkMessage(1, current_time, 8000, 10, peer_id, 0); // Large jump to 1000 (> WINDOW_SIZE=64) - try protector.checkMessage(2, current_time + 1, 8001, 1000, peer_id); + try protector.checkMessage(2, current_time + 1, 8001, 1000, peer_id, 0); // Sequence 5 is now way too old (1000 - 5 = 995 > 64) - const result = protector.checkMessage(3, current_time + 2, 8002, 5, peer_id); + const result = protector.checkMessage(3, current_time + 2, 8002, 5, peer_id, 0); try testing.expectError(ReplayError.SequenceTooOld, result); } @@ -289,8 +289,8 @@ test "ReplayProtector: forceCleanup removes expired entries" { const peer_id = [_]u8{9} ** 32; // Add messages - try protector.checkMessage(1, base_time, 9000, 0, peer_id); - try protector.checkMessage(2, base_time, 9001, 0, peer_id); + try protector.checkMessage(1, base_time, 9000, 0, peer_id, 0); + try protector.checkMessage(2, base_time, 9001, 0, peer_id, 0); var stats = protector.getStats(); try testing.expectEqual(@as(usize, 2), stats.tracked_messages); @@ -313,8 +313,8 @@ test "ReplayProtector: cleanup preserves recent entries" { const peer_id = [_]u8{10} ** 32; // Add messages with current timestamp - try protector.checkMessage(1, current_time, 10000, 1, peer_id); - try protector.checkMessage(2, current_time, 10001, 2, peer_id); + try protector.checkMessage(1, current_time, 10000, 1, peer_id, 0); + try protector.checkMessage(2, current_time, 10001, 2, peer_id, 0); var stats = protector.getStats(); try testing.expectEqual(@as(usize, 2), stats.tracked_messages); @@ -336,7 +336,7 @@ test "ReplayProtector: peer cleanup after 24 hours" { const peer_id = [_]u8{11} ** 32; // Add a peer - try protector.checkMessage(1, base_time, 11000, 1, peer_id); + try protector.checkMessage(1, base_time, 11000, 1, peer_id, 0); var stats = protector.getStats(); try testing.expectEqual(@as(usize, 1), stats.tracked_peers); @@ -374,17 +374,17 @@ test "ReplayProtector: resetPeerSequence allows restarting sequence" { const peer_id = [_]u8{13} ** 32; // Build up sequence to 100 (so that 1 is outside WINDOW_SIZE of 64) - try protector.checkMessage(1, current_time, 13000, 100, peer_id); + try protector.checkMessage(1, current_time, 13000, 100, peer_id, 0); // Sequence 1 would normally be too old (100 - 1 = 99 > 64) - const result = protector.checkMessage(2, current_time + 1, 13001, 1, peer_id); + const result = protector.checkMessage(2, current_time + 1, 13001, 1, peer_id, 0); try testing.expectError(ReplayError.SequenceTooOld, result); // Reset the peer try protector.resetPeerSequence(peer_id); // Now sequence 1 should work - try protector.checkMessage(3, current_time + 2, 13002, 1, peer_id); + try protector.checkMessage(3, current_time + 2, 13002, 1, peer_id, 0); } // ============================================================================ @@ -400,16 +400,16 @@ test "ReplayProtector: independent sequence tracking per peer" { const peer_b = [_]u8{0xBB} ** 32; // Peer A at sequence 100 - try protector.checkMessage(1, current_time, 14000, 100, peer_a); + try protector.checkMessage(1, current_time, 14000, 100, peer_a, 0); // Peer B can still use sequence 1 - try protector.checkMessage(2, current_time + 1, 14001, 1, peer_b); + try protector.checkMessage(2, current_time + 1, 14001, 1, peer_b, 0); // Peer A can advance to 101 - try protector.checkMessage(3, current_time + 2, 14002, 101, peer_a); + try protector.checkMessage(3, current_time + 2, 14002, 101, peer_a, 0); // Peer B can advance to 2 - try protector.checkMessage(4, current_time + 3, 14003, 2, peer_b); + try protector.checkMessage(4, current_time + 3, 14003, 2, peer_b, 0); const stats = protector.getStats(); try testing.expectEqual(@as(usize, 2), stats.tracked_peers); @@ -424,14 +424,14 @@ test "ReplayProtector: same message ID different peers" { const peer_b = [_]u8{0xDD} ** 32; // Peer A sends message ID 42 - try protector.checkMessage(42, current_time, 15000, 1, peer_a); + try protector.checkMessage(42, current_time, 15000, 1, peer_a, 0); // Peer B sends same message ID — allowed because replay protection is per-peer. // Each peer chooses IDs independently, so collisions between peers are expected. - try protector.checkMessage(42, current_time + 1, 15001, 1, peer_b); + try protector.checkMessage(42, current_time + 1, 15001, 1, peer_b, 0); // But Peer A replaying its own message ID should still be rejected - const result = protector.checkMessage(42, current_time + 2, 15002, 2, peer_a); + const result = protector.checkMessage(42, current_time + 2, 15002, 2, peer_a, 0); try testing.expectError(ReplayError.DuplicateMessageId, result); } @@ -453,7 +453,7 @@ test "ReplayProtector: stats reflect correct counts" { const msg_id: u64 = @as(u64, @intCast(i)) * 100; const nonce: u64 = 16000 + @as(u64, @intCast(i)); - try protector.checkMessage(msg_id, current_time, nonce, @as(u64, @intCast(i + 1)), peer_id); + try protector.checkMessage(msg_id, current_time, nonce, @as(u64, @intCast(i + 1)), peer_id, 0); } const stats = protector.getStats(); @@ -500,10 +500,10 @@ test "ReplayProtector: message with zero nonce" { const peer_id = [_]u8{17} ** 32; // Nonce 0 should work - try protector.checkMessage(1, current_time, 0, 0, peer_id); + try protector.checkMessage(1, current_time, 0, 0, peer_id, 0); // Duplicate nonce 0 should fail - const result = protector.checkMessage(2, current_time + 1, 0, 0, peer_id); + const result = protector.checkMessage(2, current_time + 1, 0, 0, peer_id, 0); try testing.expectError(ReplayError.DuplicateNonce, result); } @@ -515,7 +515,7 @@ test "ReplayProtector: message with max u64 values" { const peer_id = [_]u8{18} ** 32; // Max u64 message ID and nonce - try protector.checkMessage(std.math.maxInt(u64), current_time, std.math.maxInt(u64) - 1, 1, peer_id); + try protector.checkMessage(std.math.maxInt(u64), current_time, std.math.maxInt(u64) - 1, 1, peer_id, 0); const stats = protector.getStats(); try testing.expectEqual(@as(usize, 1), stats.tracked_messages); @@ -534,7 +534,7 @@ test "ReplayProtector: rapid message processing" { const nonce: u64 = 190000 + @as(u64, @intCast(i)); const seq: u64 = @as(u64, @intCast(i + 1)); - try protector.checkMessage(msg_id, current_time, nonce, seq, peer_id); + try protector.checkMessage(msg_id, current_time, nonce, seq, peer_id, 0); } const stats = protector.getStats(); @@ -557,7 +557,7 @@ test "ReplayProtector: periodic cleanup triggered by checkMessage" { const peer_id = [_]u8{20} ** 32; // Add initial message - try protector.checkMessage(1, base_time, 20000, 0, peer_id); + try protector.checkMessage(1, base_time, 20000, 0, peer_id, 0); var stats = protector.getStats(); try testing.expectEqual(@as(usize, 1), stats.tracked_messages); @@ -566,7 +566,7 @@ test "ReplayProtector: periodic cleanup triggered by checkMessage" { std.Thread.sleep(2 * std.time.ns_per_s); // New message should trigger periodic cleanup - try protector.checkMessage(2, std.time.timestamp(), 20001, 0, peer_id); + try protector.checkMessage(2, std.time.timestamp(), 20001, 0, peer_id, 0); stats = protector.getStats(); // Old message should be cleaned up, only new one remains