//! DHT (Distributed Hash Table) Coordinator //! //! Implements Kademlia-style DHT operations including: //! - FIND_NODE: Locate K closest nodes to a target ID //! - STORE: Store key-value pairs in the network //! - FIND_VALUE: Retrieve values by key from the network //! //! The DHT coordinator works with the KademliaRoutingTable to maintain //! a distributed key-value store across the P2P network. const std = @import("std"); const Allocator = std.mem.Allocator; const routing = @import("routing.zig"); const peer_mod = @import("peer.zig"); const topology = @import("topology.zig"); const core = @import("core"); pub const KademliaRoutingTable = routing.KademliaRoutingTable; pub const PeerId = peer_mod.PeerId; const Address = core.Address; const NodePosition = topology.NodePosition; // Cryptographic primitives from std library const Ed25519 = std.crypto.sign.Ed25519; /// TOFU (Trust-On-First-Use) decision pub const TofuDecision = enum { accept, reject, ask_later, }; /// TOFU callback type for DHT peer verification pub const DhtTofuCallback = *const fn (peer_id: [32]u8, identity_key: [32]u8, fingerprint: [32]u8) TofuDecision; /// Format a public key fingerprint as hex string for display pub fn formatFingerprint(key: [32]u8) [64]u8 { var result: [64]u8 = undefined; const hex_chars = "0123456789abcdef"; for (key, 0..) |byte, i| { result[i * 2] = hex_chars[byte >> 4]; result[i * 2 + 1] = hex_chars[byte & 0x0F]; } return result; } /// Get fingerprint (SHA256 hash) of an identity key for display pub fn getIdentityFingerprint(identity_key: [32]u8) [32]u8 { var fingerprint: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(&identity_key, &fingerprint, .{}); return fingerprint; } /// DHT-specific errors pub const DhtError = error{ /// Value too large to store ValueTooLarge, /// Signature verification failed - possible attack SignatureVerificationFailed, /// No signature provided when required MissingSignature, /// No identity key provided when required MissingIdentityKey, /// Rate limit exceeded for this peer RateLimitExceeded, /// Invalid message format InvalidMessage, /// Out of memory OutOfMemory, /// Allocation failed during cleanup - logged but not fatal CleanupAllocationFailed, }; // NodeId is a [32]u8 array for node identifiers pub const NodeId = [32]u8; /// Kademlia K parameter - number of closest nodes to return pub const K: usize = 20; /// Alpha parameter - number of parallel lookups pub const ALPHA: usize = 3; /// Default TTL for stored values - MED-12 FIX: Use centralized config pub const DEFAULT_TTL: u32 = 3600; /// Get configured TTL at runtime pub fn getDefaultTTL() u32 { return core.limits.global.dht.ttl; } /// Maximum value size - MED-12 FIX: Use centralized config pub const MAX_VALUE_SIZE: usize = 65536; /// Get configured max value size at runtime pub fn getMaxValueSize() usize { return core.limits.global.dht.max_value_size; } /// MED-9 FIX: Anti-amplification limits /// Maximum nodes in a FIND_NODE response (limits response size amplification) /// MED-12 FIX: Use centralized config pub const MAX_RESPONSE_NODES: usize = 8; pub fn getMaxResponseNodes() usize { return core.limits.global.dht.max_response_nodes; } /// Maximum amplification factor (response_size / request_size) pub const MAX_AMPLIFICATION_FACTOR: usize = 10; pub fn getMaxAmplificationFactor() usize { return core.limits.global.dht.max_amplification_factor; } /// Minimum request size to respond (prevents tiny requests generating large responses) pub const MIN_REQUEST_SIZE: usize = 32; pub fn getMinRequestSize() usize { return core.limits.global.dht.min_request_size; } /// Node information for DHT responses pub const NodeInfo = struct { node_id: NodeId, address: [46]u8, address_len: u8, }; /// Signed DHT message wrapper - all DHT messages must be signed /// SECURITY: Prevents Sybil attacks and DHT poisoning pub const SignedDhtMessage = struct { /// Ed25519 signature over the message content signature: [64]u8, /// Sender's Ed25519 identity public key (for TOFU) identity_key: [32]u8, /// Timestamp when message was created (for replay protection) timestamp: i64, /// Maximum age of a DHT message in seconds (SECURITY: reduced from 5 minutes to 60 seconds) pub const MAX_MESSAGE_AGE: i64 = 60; /// Create signing data from message components pub fn createSigningData(allocator: Allocator, request_id: u64, sender_id: NodeId, msg_type: u8, payload: []const u8, timestamp: i64) ![]u8 { // SECURITY: Prevent integer overflow in allocation size calculation const total_size = std.math.add(usize, 49, payload.len) catch return error.OutOfMemory; const data = try allocator.alloc(u8, total_size); var offset: usize = 0; // Request ID std.mem.writeInt(u64, data[offset..][0..8], request_id, .little); offset += 8; // Sender ID @memcpy(data[offset..][0..32], &sender_id); offset += 32; // Message type data[offset] = msg_type; offset += 1; // Payload @memcpy(data[offset..][0..payload.len], payload); offset += payload.len; // Timestamp std.mem.writeInt(i64, data[offset..][0..8], timestamp, .little); return data; } /// Verify the signature and timestamp pub fn verify(self: SignedDhtMessage, signing_data: []const u8) DhtError!void { // Check timestamp is not too old const now = std.time.timestamp(); const age = now - self.timestamp; if (age > MAX_MESSAGE_AGE or age < -60) { // Allow 60 seconds clock skew std.log.warn("DHT: Rejected message with invalid timestamp (age: {d}s)", .{age}); return DhtError.SignatureVerificationFailed; } // Verify Ed25519 signature const sig = Ed25519.Signature.fromBytes(self.signature); const pubkey = Ed25519.PublicKey.fromBytes(self.identity_key) catch { std.log.err("DHT SECURITY: Invalid identity key format", .{}); return DhtError.SignatureVerificationFailed; }; sig.verify(signing_data, pubkey) catch { std.log.err("DHT SECURITY: Signature verification FAILED - possible Sybil attack!", .{}); return DhtError.SignatureVerificationFailed; }; } }; /// DHT message types (simple structures for network layer) pub const DhtFindNode = struct { request_id: u64, target_id: NodeId, sender_id: NodeId, /// SECURITY: Signature data for authentication auth: ?SignedDhtMessage = null, /// Message type identifier for signing pub const MSG_TYPE: u8 = 1; }; pub const DhtFindNodeResponse = struct { request_id: u64, closest_nodes: []const NodeInfo, /// SECURITY: Signature data for authentication auth: ?SignedDhtMessage = null, /// Message type identifier for signing pub const MSG_TYPE: u8 = 2; }; pub const DhtStore = struct { request_id: u64, key: [32]u8, value: []const u8, ttl: u32, sender_id: NodeId, /// SECURITY: Signature data for authentication auth: ?SignedDhtMessage = null, /// SECURITY: Publisher signature over (key || value || ttl) - proves ownership value_signature: ?[64]u8 = null, /// Message type identifier for signing pub const MSG_TYPE: u8 = 3; /// Create data to sign for value ownership proof pub fn createValueSigningData(allocator: Allocator, key: [32]u8, value: []const u8, ttl: u32) ![]u8 { // SECURITY: Prevent integer overflow in allocation size calculation const total_size = std.math.add(usize, 36, value.len) catch return error.OutOfMemory; const data = try allocator.alloc(u8, total_size); @memcpy(data[0..32], &key); @memcpy(data[32..][0..value.len], value); std.mem.writeInt(u32, data[32 + value.len ..][0..4], ttl, .little); return data; } }; pub const DhtStoreResponse = struct { request_id: u64, success: bool, /// Error message if success is false error_message: ?[]const u8 = null, /// SECURITY: Signature data for authentication auth: ?SignedDhtMessage = null, /// Message type identifier for signing pub const MSG_TYPE: u8 = 4; }; pub const DhtFindValue = struct { request_id: u64, key: [32]u8, sender_id: NodeId, /// SECURITY: Signature data for authentication auth: ?SignedDhtMessage = null, /// Message type identifier for signing pub const MSG_TYPE: u8 = 5; }; pub const DhtFindValueResponse = struct { request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const NodeInfo, /// SECURITY: Signature data for authentication auth: ?SignedDhtMessage = null, /// SECURITY: Original publisher's signature over the value (if found) value_signature: ?[64]u8 = null, /// SECURITY: Original publisher's identity key (if found) publisher_identity: ?[32]u8 = null, /// Message type identifier for signing pub const MSG_TYPE: u8 = 6; }; /// Stored value in the DHT pub const StoredValue = struct { /// The actual data data: []u8, /// When this value expires (unix timestamp) expires_at: i64, /// Who published this value publisher: NodeId, /// SECURITY: Publisher's Ed25519 signature over (key || value || ttl) publisher_signature: [64]u8, /// SECURITY: Publisher's identity public key for verification publisher_identity: [32]u8, /// Original key this value was stored under key: [32]u8, /// Original TTL value for signature verification original_ttl: u32, pub fn deinit(self: StoredValue, allocator: Allocator) void { allocator.free(self.data); } /// SECURITY: Verify the publisher's signature over the stored value pub fn verifyPublisherSignature(self: *const StoredValue, allocator: Allocator) !bool { // Create the signing data const signing_data = try DhtStore.createValueSigningData(allocator, self.key, self.data, self.original_ttl); defer allocator.free(signing_data); // Verify the signature const sig = Ed25519.Signature.fromBytes(self.publisher_signature); const pubkey = Ed25519.PublicKey.fromBytes(self.publisher_identity) catch return false; sig.verify(signing_data, pubkey) catch return false; return true; } }; /// State of an ongoing lookup operation pub const LookupState = struct { allocator: Allocator, /// Target we're searching for target: [32]u8, /// Closest nodes we've seen so far closest_seen: std.ArrayListUnmanaged(NodeId), /// Nodes we've already queried queried: std.AutoHashMapUnmanaged(NodeId, void), /// Result value (if doing FIND_VALUE) result: ?[]u8 = null, /// Whether lookup is complete done: bool = false, /// Number of queries in flight queries_in_flight: usize = 0, // CRIT-7 FIX: Track limits for memory safety max_closest_seen: usize, max_queried: usize, pub fn init(allocator: Allocator, target: [32]u8) LookupState { return initWithLimits( allocator, target, core.limits.global.dht.max_closest_seen_per_lookup, core.limits.global.dht.max_queried_per_lookup, ); } /// CRIT-7 FIX: Initialize with explicit limits pub fn initWithLimits(allocator: Allocator, target: [32]u8, max_closest: usize, max_queried_limit: usize) LookupState { return .{ .allocator = allocator, .target = target, .closest_seen = .{}, .queried = .{}, .max_closest_seen = max_closest, .max_queried = max_queried_limit, }; } pub fn deinit(self: *LookupState) void { self.closest_seen.deinit(self.allocator); self.queried.deinit(self.allocator); if (self.result) |res| { self.allocator.free(res); } } /// CRIT-7 FIX: Add node to closest_seen with limit check pub fn addClosestSeen(self: *LookupState, node_id: NodeId) DhtError!void { if (self.closest_seen.items.len >= self.max_closest_seen) { std.log.debug("CRIT-7: LookupState closest_seen limit reached ({})", .{self.max_closest_seen}); return; // Silently ignore - not an error, just at capacity } self.closest_seen.append(self.allocator, node_id) catch return DhtError.OutOfMemory; } /// CRIT-7 FIX: Add node to queried with limit check pub fn addQueried(self: *LookupState, node_id: NodeId) DhtError!void { if (self.queried.count() >= self.max_queried) { std.log.debug("CRIT-7: LookupState queried limit reached ({})", .{self.max_queried}); return DhtError.OutOfMemory; // Can't query more - this is a real limit } self.queried.put(self.allocator, node_id, {}) catch return DhtError.OutOfMemory; } }; /// Network sender callback for DHT propagation /// This allows the DHT to send messages to peers without depending on the network layer directly pub const NetworkSender = struct { /// Callback context context: ?*anyopaque = null, /// Callback to send a FIND_NODE message to a peer send_find_node: ?*const fn (peer_id: NodeId, msg: DhtFindNode, ctx: ?*anyopaque) bool = null, /// Callback to send a STORE message to a peer send_store: ?*const fn (peer_id: NodeId, msg: DhtStore, ctx: ?*anyopaque) bool = null, /// Callback to send a FIND_VALUE message to a peer send_find_value: ?*const fn (peer_id: NodeId, msg: DhtFindValue, ctx: ?*anyopaque) bool = null, pub fn hasSender(self: NetworkSender) bool { return self.send_find_node != null and self.send_store != null and self.send_find_value != null; } pub fn sendFindNode(self: NetworkSender, peer_id: NodeId, msg: DhtFindNode) bool { if (self.send_find_node) |send_fn| { return send_fn(peer_id, msg, self.context); } return false; } pub fn sendStore(self: NetworkSender, peer_id: NodeId, msg: DhtStore) bool { if (self.send_store) |send_fn| { return send_fn(peer_id, msg, self.context); } return false; } pub fn sendFindValue(self: NetworkSender, peer_id: NodeId, msg: DhtFindValue) bool { if (self.send_find_value) |send_fn| { return send_fn(peer_id, msg, self.context); } return false; } }; /// Pending response for a network query pub const PendingResponse = struct { request_id: u64, target: NodeId, query_type: QueryType, sent_at: i64, responded: bool = false, /// Key being searched (for FIND_VALUE queries) search_key: ?[32]u8 = null, pub const QueryType = enum { find_node, store, find_value, }; }; /// Rate limiting state for a peer const PeerRateLimit = struct { last_request_time: i64, request_count_this_minute: u32, minute_start: i64, }; /// Discovered peer entry - keeps peer and position alive for routing table const DiscoveredPeer = struct { peer: *peer_mod.Peer, position: *NodePosition, discovered_at: i64, fn deinit(self: *DiscoveredPeer, allocator: Allocator) void { self.position.deinit(); allocator.destroy(self.position); allocator.destroy(self.peer); } }; /// DHT Coordinator - manages distributed hash table operations pub const DhtCoordinator = struct { allocator: Allocator, /// Routing table for peer management routing_table: *KademliaRoutingTable, /// Our node ID local_id: NodeId, /// Local storage for key-value pairs storage: std.AutoHashMap([32]u8, StoredValue), /// Pending lookup operations pending_lookups: std.AutoHashMap(u64, *LookupState), /// Pending network responses pending_responses: std.AutoHashMap(u64, PendingResponse), /// Network sender for propagation (set by P2P layer) network_sender: NetworkSender = .{}, /// Next request ID (atomic for thread safety). /// Starts at 1 on all nodes — this is safe because replay protection uses per-message /// random wire_nonce (not request_id) for global deduplication. request_id is only used /// for correlating request/response pairs within a single node. next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1), /// Mutex for thread safety mutex: std.Thread.Mutex = .{}, // SECURITY: Authentication infrastructure /// Ed25519 identity keypair for signing DHT messages identity_keypair: Ed25519.KeyPair, /// Known peer identity public keys (peer_id -> identity_key) peer_identity_keys: std.AutoHashMap(NodeId, [32]u8), /// SECURITY: Rate limiting per peer (prevents DoS) peer_rate_limits: std.AutoHashMap(NodeId, PeerRateLimit), /// TOFU callback for new peer confirmation tofu_callback: ?DhtTofuCallback = null, /// CRIT-2 FIX: Require TOFU callback for new peers (reject if not configured) /// When true, unknown peers are rejected if no TOFU callback is set. /// Set this to false ONLY for testing/development. require_tofu: bool = true, /// Suppress security warnings in development/test mode /// When true, uses debug level instead of warn for insecure mode messages suppress_dev_warnings: bool = false, /// Discovered peers from DHT lookups (keeps them alive for routing table) discovered_peers: std.AutoHashMap(NodeId, DiscoveredPeer), /// Maximum requests per peer per minute pub const MAX_REQUESTS_PER_MINUTE: u32 = 60; /// Minimum interval between requests from same peer (milliseconds) pub const MIN_REQUEST_INTERVAL_MS: i64 = 100; // SECURITY: Size limits to prevent DoS via memory exhaustion pub const MAX_PENDING_RESPONSES: usize = 10_000; pub const MAX_PENDING_LOOKUPS: usize = 1_000; pub const MAX_STORAGE_ENTRIES: usize = 100_000; pub const MAX_PEER_IDENTITY_KEYS: usize = 10_000; pub const MAX_PEER_RATE_LIMITS: usize = 10_000; pub const MAX_DISCOVERED_PEERS: usize = 5_000; pub fn init(allocator: Allocator, routing_table: *KademliaRoutingTable, local_id: NodeId) DhtCoordinator { // Generate Ed25519 identity keypair for signing const identity_keypair = Ed25519.KeyPair.generate(); return DhtCoordinator{ .allocator = allocator, .routing_table = routing_table, .local_id = local_id, .storage = std.AutoHashMap([32]u8, StoredValue).init(allocator), .pending_lookups = std.AutoHashMap(u64, *LookupState).init(allocator), .pending_responses = std.AutoHashMap(u64, PendingResponse).init(allocator), .identity_keypair = identity_keypair, .peer_identity_keys = std.AutoHashMap(NodeId, [32]u8).init(allocator), .peer_rate_limits = std.AutoHashMap(NodeId, PeerRateLimit).init(allocator), .discovered_peers = std.AutoHashMap(NodeId, DiscoveredPeer).init(allocator), }; } /// Initialize with custom TOFU callback for peer verification (recommended for production) pub fn initWithTofu(allocator: Allocator, routing_table: *KademliaRoutingTable, local_id: NodeId, tofu_callback: DhtTofuCallback) DhtCoordinator { var dht = init(allocator, routing_table, local_id); dht.tofu_callback = tofu_callback; std.log.info("CRIT-2: DHT initialized with TOFU callback (secure mode)", .{}); return dht; } /// CRIT-2 FIX: Initialize for development/testing only - disables TOFU requirement /// WARNING: Do NOT use this in production! Unknown peers will be auto-accepted. pub fn initInsecureForDevelopment(allocator: Allocator, routing_table: *KademliaRoutingTable, local_id: NodeId) DhtCoordinator { var dht = init(allocator, routing_table, local_id); dht.require_tofu = false; dht.suppress_dev_warnings = true; std.log.debug("DHT initialized in development mode (TOFU disabled)", .{}); return dht; } /// Set the TOFU callback for peer verification pub fn setTofuCallback(self: *DhtCoordinator, callback: DhtTofuCallback) void { self.tofu_callback = callback; std.log.info("CRIT-2: TOFU callback configured", .{}); } /// Check if DHT is in secure mode (TOFU required) pub fn isSecureMode(self: *const DhtCoordinator) bool { return self.require_tofu and self.tofu_callback != null; } /// Get our identity public key for sharing with peers pub fn getIdentityPublicKey(self: *const DhtCoordinator) [32]u8 { return self.identity_keypair.public_key.toBytes(); } /// Register a known peer's identity key (after out-of-band verification) pub fn registerPeerIdentityKey(self: *DhtCoordinator, peer_id: NodeId, identity_key: [32]u8) !void { self.mutex.lock(); defer self.mutex.unlock(); // Check for key change (potential attack) - timing-safe comparison if (self.peer_identity_keys.get(peer_id)) |existing| { if (!std.crypto.timing_safe.eql([32]u8, existing, identity_key)) { std.log.err("DHT SECURITY CRITICAL: Identity key change detected for peer! Possible attack.", .{}); return DhtError.SignatureVerificationFailed; } return; // Same key, nothing to do } // Enforce size limit to prevent DoS if (self.peer_identity_keys.count() >= MAX_PEER_IDENTITY_KEYS) { std.log.warn("SECURITY: peer_identity_keys at capacity ({}), rejecting new key", .{MAX_PEER_IDENTITY_KEYS}); return DhtError.OutOfMemory; } try self.peer_identity_keys.put(peer_id, identity_key); } /// Set the network sender for propagation pub fn setNetworkSender(self: *DhtCoordinator, sender: NetworkSender) void { self.mutex.lock(); defer self.mutex.unlock(); self.network_sender = sender; } /// Generate a unique request ID (thread-safe using atomic) fn getNextRequestId(self: *DhtCoordinator) u64 { return self.next_request_id.fetchAdd(1, .monotonic); } /// SECURITY: Check rate limit for a peer /// Returns error if rate limit exceeded fn checkPeerRateLimit(self: *DhtCoordinator, peer_id: NodeId) DhtError!void { // Skip rate limiting in development/insecure mode if (!self.isSecureMode()) { return; } const now = std.time.timestamp(); const now_ms = std.time.milliTimestamp(); if (self.peer_rate_limits.getPtr(peer_id)) |rate_limit| { // Check minimum interval if (now_ms - rate_limit.last_request_time < MIN_REQUEST_INTERVAL_MS) { std.log.warn("DHT: Rate limit exceeded for peer (too frequent)", .{}); return DhtError.RateLimitExceeded; } // Reset minute counter if a minute has passed if (now - rate_limit.minute_start >= 60) { rate_limit.minute_start = now; rate_limit.request_count_this_minute = 0; } // Check requests per minute if (rate_limit.request_count_this_minute >= MAX_REQUESTS_PER_MINUTE) { std.log.warn("DHT: Rate limit exceeded for peer (per-minute limit)", .{}); return DhtError.RateLimitExceeded; } // Update rate limit rate_limit.last_request_time = now_ms; rate_limit.request_count_this_minute += 1; } else { // Enforce size limit before adding new peer if (self.peer_rate_limits.count() >= MAX_PEER_RATE_LIMITS) { std.log.warn("SECURITY: peer_rate_limits at capacity, rejecting", .{}); return DhtError.OutOfMemory; } // First request from this peer self.peer_rate_limits.put(peer_id, .{ .last_request_time = now_ms, .request_count_this_minute = 1, .minute_start = now, }) catch return DhtError.OutOfMemory; } } /// SECURITY: Verify message authentication and apply TOFU fn verifyMessageAuth(self: *DhtCoordinator, sender_id: NodeId, auth: ?SignedDhtMessage, msg_type: u8, payload: []const u8, request_id: u64) DhtError!void { const auth_data = auth orelse { // In development/insecure mode, allow unauthenticated messages if (!self.isSecureMode()) { std.log.debug("DHT: Processing unauthenticated message (insecure mode)", .{}); return; } std.log.err("DHT SECURITY: Message rejected - no authentication provided", .{}); return DhtError.MissingSignature; }; // Create signing data for verification const signing_data = SignedDhtMessage.createSigningData( self.allocator, request_id, sender_id, msg_type, payload, auth_data.timestamp, ) catch return DhtError.OutOfMemory; defer self.allocator.free(signing_data); // Get or register identity key via TOFU const verification_key = self.peer_identity_keys.get(sender_id) orelse blk: { // Check size limit before adding new peer if (self.peer_identity_keys.count() >= MAX_PEER_IDENTITY_KEYS) { std.log.warn("SECURITY: peer_identity_keys at capacity, rejecting new peer", .{}); return DhtError.OutOfMemory; } // New peer - apply TOFU if (self.tofu_callback) |callback| { const fingerprint = getIdentityFingerprint(auth_data.identity_key); const decision = callback(sender_id, auth_data.identity_key, fingerprint); switch (decision) { .accept => { self.peer_identity_keys.put(sender_id, auth_data.identity_key) catch return DhtError.OutOfMemory; const fp_str = formatFingerprint(fingerprint); std.log.info("DHT TOFU: Accepted new peer with fingerprint: {s}", .{fp_str[0..16]}); break :blk auth_data.identity_key; }, .reject => { std.log.warn("DHT TOFU: User rejected peer", .{}); return DhtError.SignatureVerificationFailed; }, .ask_later => { std.log.warn("DHT TOFU: Deferred - treating as rejection", .{}); return DhtError.SignatureVerificationFailed; }, } } else { // No TOFU callback - check if we require one if (self.require_tofu) { std.log.err("DHT SECURITY: Rejecting unknown peer - no TOFU callback configured (required in production mode)", .{}); return DhtError.SignatureVerificationFailed; } else { // Development mode only - auto-accept if (!self.suppress_dev_warnings) { std.log.warn("DHT SECURITY WARNING: Auto-accepting peer without TOFU (require_tofu=false)", .{}); } self.peer_identity_keys.put(sender_id, auth_data.identity_key) catch return DhtError.OutOfMemory; break :blk auth_data.identity_key; } } }; // Verify the identity key matches what we have stored (timing-safe comparison) if (!std.crypto.timing_safe.eql([32]u8, verification_key, auth_data.identity_key)) { std.log.err("DHT SECURITY CRITICAL: Identity key mismatch - possible impersonation attack!", .{}); return DhtError.SignatureVerificationFailed; } // Verify signature and timestamp try auth_data.verify(signing_data); } /// SECURITY: Sign a message for sending fn signMessage(self: *DhtCoordinator, request_id: u64, msg_type: u8, payload: []const u8) !SignedDhtMessage { const timestamp = std.time.timestamp(); const signing_data = try SignedDhtMessage.createSigningData( self.allocator, request_id, self.local_id, msg_type, payload, timestamp, ); defer self.allocator.free(signing_data); const sig = self.identity_keypair.sign(signing_data, null) catch { return DhtError.InvalidMessage; }; return SignedDhtMessage{ .signature = sig.toBytes(), .identity_key = self.identity_keypair.public_key.toBytes(), .timestamp = timestamp, }; } pub fn deinit(self: *DhtCoordinator) void { // Clean up stored values var storage_it = self.storage.iterator(); while (storage_it.next()) |entry| { entry.value_ptr.deinit(self.allocator); } self.storage.deinit(); // Clean up pending lookups var lookups_it = self.pending_lookups.iterator(); while (lookups_it.next()) |entry| { entry.value_ptr.*.deinit(); self.allocator.destroy(entry.value_ptr.*); } self.pending_lookups.deinit(); // Clean up pending responses self.pending_responses.deinit(); // Clean up security infrastructure self.peer_identity_keys.deinit(); self.peer_rate_limits.deinit(); // Clean up discovered peers var discovered_it = self.discovered_peers.iterator(); while (discovered_it.next()) |entry| { var discovered = entry.value_ptr; discovered.deinit(self.allocator); } self.discovered_peers.deinit(); // SECURITY: Zeroize identity secret key var secret_key_bytes = self.identity_keypair.secret_key.toBytes(); for (&secret_key_bytes) |*byte| { const volatile_ptr: *volatile u8 = byte; volatile_ptr.* = 0; } } /// Find the K closest nodes to a target ID /// This implements the iterative FIND_NODE algorithm from Kademlia pub fn findNode(self: *DhtCoordinator, target_id: NodeId) ![]NodeId { self.mutex.lock(); defer self.mutex.unlock(); // Create lookup state var state = LookupState.init(self.allocator, target_id); defer state.deinit(); // Seed with closest nodes from our routing table const peer_id = PeerId{ .bytes = target_id }; const initial_peers = try self.routing_table.findClosestPeers(peer_id, K); defer self.allocator.free(initial_peers); for (initial_peers) |peer_entry| { // CRIT-7 FIX: Use safe method with limit check state.addClosestSeen(peer_entry.peer.id.bytes) catch |err| { std.log.debug("DHT: Failed to add initial peer to closest_seen: {}", .{err}); }; } // If we have no peers, return empty result if (state.closest_seen.items.len == 0) { return try self.allocator.alloc(NodeId, 0); } // Perform iterative lookup try self.lookupIteration(&state); // Return the closest K nodes const result_count = @min(K, state.closest_seen.items.len); const result = try self.allocator.alloc(NodeId, result_count); @memcpy(result, state.closest_seen.items[0..result_count]); return result; } /// Perform one iteration of the lookup algorithm /// This implements the Kademlia iterative lookup: sends FIND_NODE queries to ALPHA unqueried nodes fn lookupIteration(self: *DhtCoordinator, state: *LookupState) !void { // Sort closest_seen by distance to target const target_peer_id = PeerId{ .bytes = state.target }; std.mem.sort(NodeId, state.closest_seen.items, target_peer_id, compareNodeDistance); // Pick ALPHA nodes to query that we haven't queried yet var queries_sent: usize = 0; for (state.closest_seen.items) |node_id| { if (queries_sent >= ALPHA) break; // Skip if already queried if (state.queried.contains(node_id)) continue; // Don't query ourselves // SECURITY: Timing-safe comparison for node ID if (std.crypto.timing_safe.eql([32]u8, node_id, self.local_id)) continue; // Mark as queried - CRIT-7 FIX: Use safe method with limit check state.addQueried(node_id) catch |err| { std.log.debug("DHT: Failed to mark node as queried: {}", .{err}); break; // Stop querying if we hit the limit }; // Send FIND_NODE RPC via network sender if (self.network_sender.hasSender()) { const request_id = self.getNextRequestId(); // SECURITY: Sign the FIND_NODE message const auth = self.signMessage(request_id, DhtFindNode.MSG_TYPE, &state.target) catch |err| { std.log.warn("DHT: Failed to sign FIND_NODE message: {}", .{err}); continue; }; const find_msg = DhtFindNode{ .request_id = request_id, .target_id = state.target, .sender_id = self.local_id, .auth = auth, }; if (self.network_sender.sendFindNode(node_id, find_msg)) { // Track pending response with limit enforcement self.trackPendingResponse(request_id, .{ .request_id = request_id, .target = node_id, .query_type = .find_node, .sent_at = std.time.timestamp(), }); queries_sent += 1; state.queries_in_flight += 1; std.log.debug("DHT: Sent FIND_NODE to node (request_id={d})", .{request_id}); } } } // If no more queries to send or no network sender, we're done // In local-only mode (no network sender), we can't get responses so complete immediately if (queries_sent == 0 or !self.network_sender.hasSender()) { state.done = true; } } /// Start an asynchronous iterative node lookup /// Returns a lookup ID that can be used to check status and get results pub fn findNodeAsync(self: *DhtCoordinator, target_id: NodeId) !u64 { self.mutex.lock(); defer self.mutex.unlock(); // CRIT-7 FIX: Check pending lookups limit to prevent memory exhaustion const max_lookups = core.limits.global.dht.max_pending_lookups; if (self.pending_lookups.count() >= max_lookups) { std.log.warn("CRIT-7: Maximum pending lookups reached ({}), rejecting new lookup", .{max_lookups}); return DhtError.OutOfMemory; } // Create lookup state const state = try self.allocator.create(LookupState); state.* = LookupState.init(self.allocator, target_id); errdefer { state.deinit(); self.allocator.destroy(state); } // Seed with closest nodes from our routing table const peer_id = PeerId{ .bytes = target_id }; const initial_peers = try self.routing_table.findClosestPeers(peer_id, K); defer self.allocator.free(initial_peers); for (initial_peers) |peer_entry| { // CRIT-7 FIX: Use safe method with limit check state.addClosestSeen(peer_entry.peer.id.bytes) catch |err| { std.log.debug("DHT: Failed to add initial peer to closest_seen: {}", .{err}); }; } // Generate a lookup ID const lookup_id = self.getNextRequestId(); // Enforce size limit before storing lookup state if (self.pending_lookups.count() >= MAX_PENDING_LOOKUPS) { std.log.warn("SECURITY: pending_lookups at capacity ({}), rejecting", .{MAX_PENDING_LOOKUPS}); state.deinit(); self.allocator.destroy(state); return DhtError.OutOfMemory; } // Store the lookup state try self.pending_lookups.put(lookup_id, state); // Start initial queries if we have peers if (state.closest_seen.items.len > 0) { try self.lookupIteration(state); } else { state.done = true; } std.log.info("DHT: Started FIND_NODE lookup {d} for target, initial peers: {d}", .{ lookup_id, initial_peers.len }); return lookup_id; } /// Handle incoming FIND_NODE response - processes the response and continues iterative lookup /// SECURITY: Verifies message signature before processing pub fn handleFindNodeResponse(self: *DhtCoordinator, response: DhtFindNodeResponse, sender_id: NodeId) !void { self.mutex.lock(); defer self.mutex.unlock(); // Mark the request as completed const pending = self.pending_responses.fetchRemove(response.request_id); if (pending == null) { std.log.warn("DHT: Received FIND_NODE response for unknown request {d}", .{response.request_id}); return; } // SECURITY: Verify response authentication if (response.auth) |auth| { // Create empty payload for response verification (responses don't include target in signature) self.verifyMessageAuth( sender_id, auth, DhtFindNodeResponse.MSG_TYPE, &[_]u8{}, response.request_id, ) catch |err| { std.log.err("DHT FIND_NODE response authentication failed: {}", .{err}); return; }; } else { // SECURITY: Reject unsigned responses in secure mode if (self.isSecureMode()) { std.log.warn("SECURITY: DHT FIND_NODE response rejected - unsigned response not allowed in secure mode", .{}); return; } std.log.debug("DHT: Processing unsigned FIND_NODE response (insecure mode)", .{}); } // Find the lookup this response belongs to var lookup_state: ?*LookupState = null; var lookup_id: u64 = 0; var lookup_it = self.pending_lookups.iterator(); while (lookup_it.next()) |entry| { // Check if this response is for nodes close to this lookup's target const target_peer_id = PeerId{ .bytes = entry.value_ptr.*.target }; const response_peer_id = PeerId{ .bytes = pending.?.value.target }; const distance = routing.XORDistance.init(target_peer_id, response_peer_id); // This is a heuristic - find the lookup where the sender was queried if (entry.value_ptr.*.queried.contains(pending.?.value.target)) { lookup_state = entry.value_ptr.*; lookup_id = entry.key_ptr.*; break; } _ = distance; } if (lookup_state == null) { std.log.debug("DHT: No active lookup found for FIND_NODE response", .{}); return; } const state = lookup_state.?; // Incorporate new nodes from the response var new_nodes_added: usize = 0; for (response.closest_nodes) |node_info| { // Skip nodes we've already seen var already_seen = false; for (state.closest_seen.items) |existing| { // SECURITY: Timing-safe comparison for node ID if (std.crypto.timing_safe.eql([32]u8, existing, node_info.node_id)) { already_seen = true; break; } } if (!already_seen) { // CRIT-7 FIX: Use safe method with limit check state.addClosestSeen(node_info.node_id) catch |err| { std.log.warn("DHT: Failed to add node to lookup (limit reached or OOM): {}", .{err}); continue; }; new_nodes_added += 1; // Also add to routing table for future lookups const addr_len = node_info.address_len; const addr_str = node_info.address[0..addr_len]; if (Address.parse(addr_str)) |addr| { const new_peer_id = PeerId{ .bytes = node_info.node_id }; // CRIT-7 FIX: Check discovered peers limit before adding new peers const max_discovered = core.limits.global.dht.max_discovered_peers; if (self.discovered_peers.count() >= max_discovered) { std.log.debug("DHT: Maximum discovered peers reached ({d}), skipping new peer", .{max_discovered}); continue; } // Check if we already have this peer if (self.discovered_peers.contains(node_info.node_id)) { continue; } // Allocate peer and position on heap to keep them alive const peer_ptr = self.allocator.create(peer_mod.Peer) catch |err| { std.log.debug("DHT: Failed to allocate peer: {}", .{err}); continue; }; errdefer self.allocator.destroy(peer_ptr); const position_ptr = self.allocator.create(NodePosition) catch |err| { std.log.debug("DHT: Failed to allocate position: {}", .{err}); self.allocator.destroy(peer_ptr); continue; }; errdefer { position_ptr.deinit(); self.allocator.destroy(position_ptr); } peer_ptr.* = peer_mod.Peer.init(new_peer_id, addr); position_ptr.* = NodePosition.init(self.allocator, new_peer_id); // Add to routing table self.routing_table.addPeer(peer_ptr, position_ptr) catch |err| { std.log.debug("DHT: Could not add discovered peer to routing table: {}", .{err}); position_ptr.deinit(); self.allocator.destroy(position_ptr); self.allocator.destroy(peer_ptr); continue; }; // Track the discovered peer (with size limit) if (self.discovered_peers.count() < MAX_DISCOVERED_PEERS) { self.discovered_peers.put(node_info.node_id, .{ .peer = peer_ptr, .position = position_ptr, .discovered_at = std.time.timestamp(), }) catch |err| { std.log.debug("DHT: Failed to track discovered peer: {}", .{err}); }; } else { std.log.debug("DHT: discovered_peers at capacity, skipping tracking", .{}); } } else |_| { std.log.debug("DHT: Could not parse address from FIND_NODE response", .{}); } } } // Decrement in-flight counter if (state.queries_in_flight > 0) { state.queries_in_flight -= 1; } std.log.debug("DHT: FIND_NODE response added {d} new nodes, {d} queries in flight", .{ new_nodes_added, state.queries_in_flight }); // Check if we should continue the lookup if (state.done) { return; } // Check termination conditions const have_k_queried = state.queried.count() >= K; const no_more_to_query = blk: { for (state.closest_seen.items) |node_id| { // SECURITY: Timing-safe comparison for node ID if (!state.queried.contains(node_id) and !std.crypto.timing_safe.eql([32]u8, node_id, self.local_id)) { break :blk false; } } break :blk true; }; if (have_k_queried or no_more_to_query) { state.done = true; std.log.info("DHT: Lookup {d} complete - queried {d} nodes, found {d} closest", .{ lookup_id, state.queried.count(), state.closest_seen.items.len, }); return; } // Continue with more queries if we got new nodes if (new_nodes_added > 0 or state.queries_in_flight < ALPHA) { self.lookupIteration(state) catch |err| { std.log.warn("DHT: Failed to continue lookup iteration: {}", .{err}); }; } } /// Check if an async lookup is complete pub fn isLookupComplete(self: *DhtCoordinator, lookup_id: u64) bool { self.mutex.lock(); defer self.mutex.unlock(); if (self.pending_lookups.get(lookup_id)) |state| { return state.done; } return true; // Not found means already completed/cleaned } /// Get the result of a completed async lookup /// Returns null if lookup is still in progress /// Caller owns the returned slice pub fn getLookupResult(self: *DhtCoordinator, lookup_id: u64) !?[]NodeId { self.mutex.lock(); defer self.mutex.unlock(); const entry = self.pending_lookups.fetchRemove(lookup_id); if (entry == null) { return null; // Already retrieved or never existed } const state = entry.?.value; if (!state.done) { // Not done yet - put it back (do NOT destroy) self.pending_lookups.put(lookup_id, state) catch { // Can't reinsert - must clean up to avoid leak state.deinit(); self.allocator.destroy(state); return error.OutOfMemory; }; return null; } // Lookup is complete - extract results then destroy state defer { state.deinit(); self.allocator.destroy(state); } const target_peer_id = PeerId{ .bytes = state.target }; std.mem.sort(NodeId, state.closest_seen.items, target_peer_id, compareNodeDistance); const result_count = @min(K, state.closest_seen.items.len); const result = try self.allocator.alloc(NodeId, result_count); @memcpy(result, state.closest_seen.items[0..result_count]); return result; } /// Cancel an in-progress lookup and clean up resources pub fn cancelLookup(self: *DhtCoordinator, lookup_id: u64) void { self.mutex.lock(); defer self.mutex.unlock(); if (self.pending_lookups.fetchRemove(lookup_id)) |entry| { var state = entry.value; state.deinit(); self.allocator.destroy(state); } } /// Store a key-value pair in the DHT /// This implements the full Kademlia STORE operation: /// 1. Store locally with our signature /// 2. Propagate to K closest nodes in the network pub fn store(self: *DhtCoordinator, key: [32]u8, value: []const u8, ttl: u32) !void { if (value.len > MAX_VALUE_SIZE) { return error.ValueTooLarge; } self.mutex.lock(); defer self.mutex.unlock(); // SECURITY: Sign the value to prove ownership const value_signing_data = try DhtStore.createValueSigningData(self.allocator, key, value, ttl); defer self.allocator.free(value_signing_data); const value_sig = self.identity_keypair.sign(value_signing_data, null) catch { return DhtError.InvalidMessage; }; const value_signature = value_sig.toBytes(); const identity_key = self.identity_keypair.public_key.toBytes(); // Find K closest nodes to the key const closest = try self.findNodeUnlocked(key); defer self.allocator.free(closest); // Store locally with signature try self.storeLocalWithSignature(key, value, ttl, self.local_id, value_signature, identity_key); // NETWORK PROPAGATION: Send STORE RPCs to all K closest nodes if (self.network_sender.hasSender()) { var sent_count: usize = 0; for (closest) |node_id| { // Don't send to ourselves // SECURITY: Timing-safe comparison for node ID if (std.crypto.timing_safe.eql([32]u8, node_id, self.local_id)) continue; const request_id = self.getNextRequestId(); // SECURITY: Sign the message const auth = self.signMessage(request_id, DhtStore.MSG_TYPE, value) catch |err| { std.log.warn("DHT: Failed to sign STORE message: {}", .{err}); continue; }; const store_msg = DhtStore{ .request_id = request_id, .key = key, .value = value, .ttl = ttl, .sender_id = self.local_id, .auth = auth, .value_signature = value_signature, }; if (self.network_sender.sendStore(node_id, store_msg)) { // Track pending response with limit enforcement self.trackPendingResponse(request_id, .{ .request_id = request_id, .target = node_id, .query_type = .store, .sent_at = std.time.timestamp(), }); sent_count += 1; } } std.log.info("DHT STORE propagated to {d} nodes", .{sent_count}); } } /// Find value by key in the DHT /// This implements the full Kademlia FIND_VALUE operation: /// 1. Check local storage first /// 2. If not found, query K closest nodes pub fn findValue(self: *DhtCoordinator, key: [32]u8) !?[]u8 { self.mutex.lock(); defer self.mutex.unlock(); // Check local storage first if (self.storage.get(key)) |stored| { const now = std.time.timestamp(); if (stored.expires_at > now) { // Return a copy of the value return try self.allocator.dupe(u8, stored.data); } else { // Value expired, remove it const entry = self.storage.fetchRemove(key); if (entry) |e| { e.value.deinit(self.allocator); } } } // NETWORK PROPAGATION: Query K closest nodes for the value // Note: This initiates async queries - responses are handled by handleFindValueResponse if (self.network_sender.hasSender()) { const closest = try self.findNodeUnlocked(key); defer self.allocator.free(closest); var sent_count: usize = 0; for (closest) |node_id| { // Don't query ourselves // SECURITY: Timing-safe comparison for node ID if (std.crypto.timing_safe.eql([32]u8, node_id, self.local_id)) continue; const request_id = self.getNextRequestId(); const find_msg = DhtFindValue{ .request_id = request_id, .key = key, .sender_id = self.local_id, }; if (self.network_sender.sendFindValue(node_id, find_msg)) { // Track pending response with limit enforcement self.trackPendingResponse(request_id, .{ .request_id = request_id, .target = node_id, .query_type = .find_value, .sent_at = std.time.timestamp(), .search_key = key, }); sent_count += 1; // Only query ALPHA nodes in parallel (Kademlia concurrency) if (sent_count >= ALPHA) break; } } std.log.debug("DHT FIND_VALUE initiated for key, querying {d} nodes", .{sent_count}); } // Value not found locally, network queries initiated // The caller should poll or wait for responses via handleFindValueResponse return null; } /// Handle incoming FIND_VALUE response and process the result /// Call this when receiving a response to a FIND_VALUE query we sent pub fn handleFindValueResponse(self: *DhtCoordinator, response: DhtFindValueResponse) !?[]u8 { self.mutex.lock(); defer self.mutex.unlock(); // Get the search key from pending responses var search_key: ?[32]u8 = null; if (self.pending_responses.fetchRemove(response.request_id)) |pending| { search_key = pending.value.search_key; } // If value was found, cache it locally for future findValue() calls if (response.found) { if (response.value) |value| { // Cache locally if we know the key if (search_key) |key| { // Store unsigned since we're caching a remote response self.storeLocalUnsigned(key, value, 300, self.local_id) catch |err| { std.log.debug("DHT: Failed to cache FIND_VALUE result: {}", .{err}); }; } // Return a copy of the value return try self.allocator.dupe(u8, value); } } // Value not found at this node // The caller could use closest_nodes to continue the search return null; } /// Handle incoming STORE response pub fn handleStoreResponse(self: *DhtCoordinator, response: DhtStoreResponse) void { self.mutex.lock(); defer self.mutex.unlock(); // Remove from pending responses if (self.pending_responses.fetchRemove(response.request_id)) |pending| { if (!response.success) { std.log.warn("DHT STORE failed for node {any}", .{pending.value.target}); } } } /// Clean up timed out pending responses /// MEM-M3 FIX: Use resilient cleanup pattern - continue collecting even on OOM /// This avoids iterator invalidation by using two-pass approach and handles /// allocation failures gracefully without leaving the map in an inconsistent state pub fn cleanupPendingResponses(self: *DhtCoordinator, timeout_seconds: i64) void { self.mutex.lock(); defer self.mutex.unlock(); const now = std.time.timestamp(); var to_remove: std.ArrayListUnmanaged(u64) = .{}; defer to_remove.deinit(self.allocator); // First pass: collect expired entries (safe iteration - no modification) var it = self.pending_responses.iterator(); var skipped_oom: usize = 0; while (it.next()) |entry| { if (now - entry.value_ptr.sent_at > timeout_seconds) { // MEM-M3 FIX: Continue on OOM instead of failing entirely to_remove.append(self.allocator, entry.key_ptr.*) catch { skipped_oom += 1; continue; }; } } if (skipped_oom > 0) { std.log.warn("DHT cleanup: skipped {} expired entries due to OOM", .{skipped_oom}); } // Second pass: remove collected entries (safe - separate iteration) for (to_remove.items) |request_id| { _ = self.pending_responses.remove(request_id); } } /// Track a pending response with limit enforcement /// Automatically cleans up stale entries if at limit /// This should be called with mutex already held fn trackPendingResponse(self: *DhtCoordinator, request_id: u64, response: PendingResponse) void { // Check if we're at the limit if (self.pending_responses.count() >= MAX_PENDING_RESPONSES) { std.log.warn("DHT: Pending response limit reached ({}), forcing cleanup", .{MAX_PENDING_RESPONSES}); // Force cleanup of old entries (30 second timeout for forced cleanup) const now = std.time.timestamp(); var to_remove: std.ArrayListUnmanaged(u64) = .{}; defer to_remove.deinit(self.allocator); var it = self.pending_responses.iterator(); var skipped_oom: usize = 0; while (it.next()) |entry| { // More aggressive 30s timeout for forced cleanup if (now - entry.value_ptr.sent_at > 30) { to_remove.append(self.allocator, entry.key_ptr.*) catch { skipped_oom += 1; continue; }; } } if (skipped_oom > 0) { std.log.warn("DHT cleanup: skipped {} entries due to OOM", .{skipped_oom}); } for (to_remove.items) |id| { _ = self.pending_responses.remove(id); } // If still at limit after cleanup, skip tracking this one if (self.pending_responses.count() >= MAX_PENDING_RESPONSES) { std.log.err("DHT: Still at pending response limit after cleanup - possible DoS attack", .{}); return; } } // Track the pending response self.pending_responses.put(request_id, response) catch |err| { std.log.warn("DHT: Failed to track pending response: {}", .{err}); }; } /// Handle incoming FIND_NODE request /// SECURITY: Verifies message signature and applies rate limiting /// MED-9 FIX: Applies amplification limits to response size pub fn handleFindNode(self: *DhtCoordinator, msg: DhtFindNode) !DhtFindNodeResponse { self.mutex.lock(); defer self.mutex.unlock(); // SECURITY: Rate limit check try self.checkPeerRateLimit(msg.sender_id); // SECURITY: Verify message authentication try self.verifyMessageAuth( msg.sender_id, msg.auth, DhtFindNode.MSG_TYPE, &msg.target_id, msg.request_id, ); const target_peer_id = PeerId{ .bytes = msg.target_id }; // MED-9 FIX: Limit response to MAX_RESPONSE_NODES to prevent amplification const max_nodes = @min(K, MAX_RESPONSE_NODES); const closest_peers = try self.routing_table.findClosestPeers(target_peer_id, max_nodes); defer self.allocator.free(closest_peers); // Convert peer entries to NodeInfo var nodes = try self.allocator.alloc(NodeInfo, closest_peers.len); defer self.allocator.free(nodes); for (closest_peers, 0..) |peer_entry, i| { // Convert address to string format var addr_buf: [128]u8 = undefined; const addr_str = peer_entry.peer.address.toStringBuf(&addr_buf); var address_buf: [46]u8 = [_]u8{0} ** 46; const addr_len = @min(addr_str.len, 46); @memcpy(address_buf[0..addr_len], addr_str[0..addr_len]); nodes[i] = .{ .node_id = peer_entry.peer.id.bytes, .address = address_buf, .address_len = @intCast(addr_len), }; } // Create a copy for the response const nodes_copy = try self.allocator.alloc(NodeInfo, nodes.len); // MEM-3 FIX: Add errdefer to prevent memory leak if signMessage fails errdefer self.allocator.free(nodes_copy); @memcpy(nodes_copy, nodes); // SECURITY: Sign the response const auth = try self.signMessage(msg.request_id, DhtFindNodeResponse.MSG_TYPE, &[_]u8{}); return DhtFindNodeResponse{ .request_id = msg.request_id, .closest_nodes = nodes_copy, .auth = auth, }; } /// Handle incoming STORE request /// SECURITY: Verifies message signature, value signature, and applies rate limiting pub fn handleStore(self: *DhtCoordinator, msg: DhtStore) !DhtStoreResponse { self.mutex.lock(); defer self.mutex.unlock(); // SECURITY: Rate limit check self.checkPeerRateLimit(msg.sender_id) catch |err| { const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = if (err == DhtError.RateLimitExceeded) "Rate limit exceeded" else "Error", .auth = auth, }; }; // SECURITY: Verify message authentication self.verifyMessageAuth( msg.sender_id, msg.auth, DhtStore.MSG_TYPE, msg.value, msg.request_id, ) catch |err| { std.log.err("DHT STORE rejected: authentication failed", .{}); const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Auth failed" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = if (err == DhtError.SignatureVerificationFailed) "Signature verification failed" else "Authentication error", .auth = auth, }; }; // Check value size if (msg.value.len > MAX_VALUE_SIZE) { const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value too large" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value too large", .auth = auth, }; } // SECURITY: Verify value signature (proves publisher ownership) // In development/insecure mode, allow storing without signatures if (!self.isSecureMode()) { // Development mode: store without signature verification std.log.debug("DHT: Storing value in insecure mode (no signature verification)", .{}); try self.storeLocalUnsigned(msg.key, msg.value, msg.ttl, msg.sender_id); } else { const value_sig = msg.value_signature orelse { std.log.err("DHT STORE rejected: no value signature provided", .{}); const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing value signature" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing value signature", .auth = auth, }; }; // Get the sender's identity key (already verified via TOFU) const identity_key = if (msg.auth) |auth_data| auth_data.identity_key else { const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing identity key" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing identity key", .auth = auth, }; }; // Verify value signature const value_signing_data = DhtStore.createValueSigningData(self.allocator, msg.key, msg.value, msg.ttl) catch { const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error", .auth = auth, }; }; defer self.allocator.free(value_signing_data); const sig = Ed25519.Signature.fromBytes(value_sig); const pubkey = Ed25519.PublicKey.fromBytes(identity_key) catch { const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Invalid identity key" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Invalid identity key", .auth = auth, }; }; sig.verify(value_signing_data, pubkey) catch { std.log.err("DHT STORE rejected: value signature verification failed", .{}); const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch { return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value signature failed" }; }; return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value signature verification failed", .auth = auth, }; }; // Store the value with signature for future verification try self.storeLocalWithSignature(msg.key, msg.value, msg.ttl, msg.sender_id, value_sig, identity_key); } // Sign and return success response const auth = try self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}); return DhtStoreResponse{ .request_id = msg.request_id, .success = true, .auth = auth, }; } /// Store value locally with publisher signature (assumes lock is held) fn storeLocalWithSignature( self: *DhtCoordinator, key: [32]u8, value: []const u8, ttl: u32, publisher: NodeId, publisher_signature: [64]u8, publisher_identity: [32]u8, ) !void { // Remove old value if it exists const had_existing = if (self.storage.fetchRemove(key)) |old| blk: { old.value.deinit(self.allocator); break :blk true; } else false; // CRIT-7 FIX: Check storage limit for new entries if (!had_existing) { const max_storage = core.limits.global.dht.max_storage_entries; if (self.storage.count() >= max_storage) { std.log.warn("DHT: Storage limit reached ({d} entries), rejecting new entry", .{max_storage}); return DhtError.OutOfMemory; } } // Store new value with signature const value_copy = try self.allocator.dupe(u8, value); errdefer self.allocator.free(value_copy); const now = std.time.timestamp(); try self.storage.put(key, .{ .data = value_copy, .expires_at = now + @as(i64, @intCast(ttl)), .publisher = publisher, .publisher_signature = publisher_signature, .publisher_identity = publisher_identity, .key = key, .original_ttl = ttl, }); } /// Store value locally without signature verification (for insecure/development mode) fn storeLocalUnsigned( self: *DhtCoordinator, key: [32]u8, value: []const u8, ttl: u32, publisher: NodeId, ) !void { // Remove old value if it exists const had_existing = if (self.storage.fetchRemove(key)) |old| blk: { old.value.deinit(self.allocator); break :blk true; } else false; // CRIT-7 FIX: Check storage limit for new entries if (!had_existing) { const max_storage = core.limits.global.dht.max_storage_entries; if (self.storage.count() >= max_storage) { std.log.warn("DHT: Storage limit reached ({d} entries), rejecting new entry", .{max_storage}); return DhtError.OutOfMemory; } } // Store new value without signature (insecure mode) const value_copy = try self.allocator.dupe(u8, value); errdefer self.allocator.free(value_copy); const now = std.time.timestamp(); try self.storage.put(key, .{ .data = value_copy, .expires_at = now + @as(i64, @intCast(ttl)), .publisher = publisher, .publisher_signature = [_]u8{0} ** 64, // No signature in insecure mode .publisher_identity = [_]u8{0} ** 32, // No identity in insecure mode .key = key, .original_ttl = ttl, }); } /// Handle incoming FIND_VALUE request /// SECURITY: Verifies message signature and applies rate limiting pub fn handleFindValue(self: *DhtCoordinator, msg: DhtFindValue) !DhtFindValueResponse { self.mutex.lock(); defer self.mutex.unlock(); // SECURITY: Rate limit check try self.checkPeerRateLimit(msg.sender_id); // SECURITY: Verify message authentication try self.verifyMessageAuth( msg.sender_id, msg.auth, DhtFindValue.MSG_TYPE, &msg.key, msg.request_id, ); // Check local storage if (self.storage.get(msg.key)) |stored| { const now = std.time.timestamp(); if (stored.expires_at > now) { // SECURITY: Sign the response const auth = try self.signMessage(msg.request_id, DhtFindValueResponse.MSG_TYPE, stored.data); // Found the value - include publisher signature for verification return DhtFindValueResponse{ .request_id = msg.request_id, .found = true, .value = stored.data, .closest_nodes = &.{}, .auth = auth, .value_signature = stored.publisher_signature, .publisher_identity = stored.publisher_identity, }; } else { // Value expired, remove it const entry = self.storage.fetchRemove(msg.key); if (entry) |e| { e.value.deinit(self.allocator); } } } // Value not found, return closest nodes // SECURITY: Limit to MAX_RESPONSE_NODES to prevent amplification (same as FIND_NODE) const max_nodes = @min(K, MAX_RESPONSE_NODES); const target_peer_id = PeerId{ .bytes = msg.key }; const closest_peers = try self.routing_table.findClosestPeers(target_peer_id, max_nodes); defer self.allocator.free(closest_peers); var nodes = try self.allocator.alloc(NodeInfo, closest_peers.len); defer self.allocator.free(nodes); for (closest_peers, 0..) |peer_entry, i| { // Convert address to string format var addr_buf: [128]u8 = undefined; const addr_str = peer_entry.peer.address.toStringBuf(&addr_buf); var address_buf: [46]u8 = [_]u8{0} ** 46; const addr_len = @min(addr_str.len, 46); @memcpy(address_buf[0..addr_len], addr_str[0..addr_len]); nodes[i] = .{ .node_id = peer_entry.peer.id.bytes, .address = address_buf, .address_len = @intCast(addr_len), }; } const nodes_copy = try self.allocator.alloc(NodeInfo, nodes.len); // MEM-4 FIX: Add errdefer to prevent memory leak if signMessage fails errdefer self.allocator.free(nodes_copy); @memcpy(nodes_copy, nodes); // SECURITY: Sign the response const auth = try self.signMessage(msg.request_id, DhtFindValueResponse.MSG_TYPE, &[_]u8{}); return DhtFindValueResponse{ .request_id = msg.request_id, .found = false, .value = null, .closest_nodes = nodes_copy, .auth = auth, }; } /// Periodic maintenance - expire old values pub fn refresh(self: *DhtCoordinator) !void { self.mutex.lock(); defer self.mutex.unlock(); const now = std.time.timestamp(); var to_remove: std.ArrayListUnmanaged([32]u8) = .{}; defer to_remove.deinit(self.allocator); // Find expired values var it = self.storage.iterator(); while (it.next()) |entry| { if (entry.value_ptr.expires_at < now) { try to_remove.append(self.allocator, entry.key_ptr.*); } } // Remove expired values for (to_remove.items) |key| { if (self.storage.fetchRemove(key)) |removed| { removed.value.deinit(self.allocator); } } // Refresh routing table buckets try self.routing_table.maintain(); } /// Internal helper: find nodes without locking (assumes lock is held) fn findNodeUnlocked(self: *DhtCoordinator, target_id: NodeId) ![]NodeId { const peer_id = PeerId{ .bytes = target_id }; const peers = try self.routing_table.findClosestPeers(peer_id, K); defer self.allocator.free(peers); const result = try self.allocator.alloc(NodeId, peers.len); for (peers, 0..) |peer_entry, i| { result[i] = peer_entry.peer.id.bytes; } return result; } }; /// Compare node distance to target for sorting fn compareNodeDistance(target_id: PeerId, a: NodeId, b: NodeId) bool { const distance_a = routing.XORDistance.init(target_id, PeerId{ .bytes = a }); const distance_b = routing.XORDistance.init(target_id, PeerId{ .bytes = b }); return distance_a.compare(distance_b) == .lt; } test "DHT coordinator initialization" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Verify initialization try std.testing.expectEqual(@as(usize, 0), dht.storage.count()); try std.testing.expectEqual(@as(usize, 0), dht.pending_lookups.count()); } test "DHT store and retrieve" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Store a value var key: [32]u8 = undefined; std.crypto.random.bytes(&key); const value = "test value"; try dht.store(key, value, DEFAULT_TTL); // Retrieve the value const retrieved = try dht.findValue(key); try std.testing.expect(retrieved != null); if (retrieved) |val| { defer allocator.free(val); try std.testing.expectEqualStrings(value, val); } } test "DHT value expiration" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Store a value with 1 second TTL var key: [32]u8 = undefined; std.crypto.random.bytes(&key); const value = "expiring value"; try dht.store(key, value, 1); // Value should exist immediately { const retrieved = try dht.findValue(key); try std.testing.expect(retrieved != null); if (retrieved) |val| { allocator.free(val); } } // Wait for expiration std.Thread.sleep(2 * std.time.ns_per_s); // Run refresh to clean up expired values try dht.refresh(); // Value should be gone const retrieved = try dht.findValue(key); try std.testing.expect(retrieved == null); } /// Helper to create a signed DHT message for testing fn createTestSignedMessage( allocator: Allocator, keypair: Ed25519.KeyPair, request_id: u64, sender_id: NodeId, msg_type: u8, payload: []const u8, ) !SignedDhtMessage { const timestamp = std.time.timestamp(); const signing_data = try SignedDhtMessage.createSigningData( allocator, request_id, sender_id, msg_type, payload, timestamp, ); defer allocator.free(signing_data); // Signing should not fail in tests with valid input, but handle it properly const sig = keypair.sign(signing_data, null) catch |err| { std.log.err("Test helper: Failed to sign message: {}", .{err}); return DhtError.InvalidMessage; }; return SignedDhtMessage{ .signature = sig.toBytes(), .identity_key = keypair.public_key.toBytes(), .timestamp = timestamp, }; } test "DHT handle FIND_NODE" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); // Use insecure mode for testing - disables TOFU requirement var dht = DhtCoordinator.initInsecureForDevelopment(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Create a sender keypair for signing const sender_keypair = Ed25519.KeyPair.generate(); // Create a FIND_NODE request var target_id: [32]u8 = undefined; std.crypto.random.bytes(&target_id); var request_id: [8]u8 = undefined; std.crypto.random.bytes(&request_id); const req_id = std.mem.readInt(u64, &request_id, .little); // Create authentication const auth = try createTestSignedMessage( allocator, sender_keypair, req_id, local_id.bytes, DhtFindNode.MSG_TYPE, &target_id, ); const request = DhtFindNode{ .request_id = req_id, .target_id = target_id, .sender_id = local_id.bytes, .auth = auth, }; // Handle the request const response = try dht.handleFindNode(request); defer allocator.free(response.closest_nodes); // Should return a valid response (even if empty) try std.testing.expectEqual(request.request_id, response.request_id); } test "DHT handle STORE" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); // Use insecure mode for testing - disables TOFU requirement var dht = DhtCoordinator.initInsecureForDevelopment(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Create a sender keypair for signing const sender_keypair = Ed25519.KeyPair.generate(); // Create a STORE request var key: [32]u8 = undefined; std.crypto.random.bytes(&key); const value = "stored value"; const ttl = DEFAULT_TTL; var request_id: [8]u8 = undefined; std.crypto.random.bytes(&request_id); const req_id = std.mem.readInt(u64, &request_id, .little); // Create message authentication const auth = try createTestSignedMessage( allocator, sender_keypair, req_id, local_id.bytes, DhtStore.MSG_TYPE, value, ); // Create value signature (proves ownership) const value_signing_data = try DhtStore.createValueSigningData(allocator, key, value, ttl); defer allocator.free(value_signing_data); const value_sig = sender_keypair.sign(value_signing_data, null) catch |err| { std.log.err("Test: Failed to sign value: {}", .{err}); return err; }; const request = DhtStore{ .request_id = req_id, .key = key, .value = value, .ttl = ttl, .sender_id = local_id.bytes, .auth = auth, .value_signature = value_sig.toBytes(), }; // Handle the request const response = try dht.handleStore(request); // Should succeed try std.testing.expect(response.success); try std.testing.expectEqual(request.request_id, response.request_id); // Verify value was stored const retrieved = try dht.findValue(key); try std.testing.expect(retrieved != null); if (retrieved) |val| { defer allocator.free(val); try std.testing.expectEqualStrings(value, val); } } test "DHT async lookup initiates correctly" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Create target to search for var target_id: [32]u8 = undefined; std.crypto.random.bytes(&target_id); // Start async lookup (should complete immediately with no peers) const lookup_id = try dht.findNodeAsync(target_id); try std.testing.expect(lookup_id > 0); // With no peers, lookup should be immediately complete try std.testing.expect(dht.isLookupComplete(lookup_id)); // Get the (empty) result const result = try dht.getLookupResult(lookup_id); try std.testing.expect(result != null); if (result) |nodes| { defer allocator.free(nodes); try std.testing.expectEqual(@as(usize, 0), nodes.len); } } test "DHT async lookup with peers" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); // Add some peers to the routing table // Need to keep peers alive for the duration of the test var peers: [5]peer_mod.Peer = undefined; var positions: [5]NodePosition = undefined; for (0..5) |i| { const new_peer_id = PeerId.init(); const addr = Address.parse("127.0.0.1:8000") catch |err| { std.log.err("Test: Failed to parse address: {}", .{err}); return err; }; peers[i] = peer_mod.Peer.init(new_peer_id, addr); positions[i] = NodePosition.init(allocator, new_peer_id); try routing_table.addPeer(&peers[i], &positions[i]); } defer { for (0..5) |i| { positions[i].deinit(); } } var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Create target to search for var target_id: [32]u8 = undefined; std.crypto.random.bytes(&target_id); // Start async lookup const lookup_id = try dht.findNodeAsync(target_id); try std.testing.expect(lookup_id > 0); // Without a network sender, lookup should complete after marking nodes as queried // (in local-only mode) try std.testing.expect(dht.isLookupComplete(lookup_id)); // Get result - should have the peers we added const result = try dht.getLookupResult(lookup_id); try std.testing.expect(result != null); if (result) |nodes| { defer allocator.free(nodes); try std.testing.expect(nodes.len > 0); try std.testing.expect(nodes.len <= K); } } test "DHT cancel lookup" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Create target to search for var target_id: [32]u8 = undefined; std.crypto.random.bytes(&target_id); // Start and immediately cancel const lookup_id = try dht.findNodeAsync(target_id); dht.cancelLookup(lookup_id); // Should no longer be tracked const result = try dht.getLookupResult(lookup_id); try std.testing.expect(result == null); } test "DHT handle FIND_NODE response with authentication" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); // Use insecure mode for testing - disables TOFU requirement var dht = DhtCoordinator.initInsecureForDevelopment(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Add a peer and start a lookup const peer_id = PeerId.init(); const addr = Address.parse("127.0.0.1:8000") catch |err| { std.log.err("Test: Failed to parse address: {}", .{err}); return err; }; var peer = peer_mod.Peer.init(peer_id, addr); var position = NodePosition.init(allocator, peer_id); defer position.deinit(); try routing_table.addPeer(&peer, &position); var target_id: [32]u8 = undefined; std.crypto.random.bytes(&target_id); // Start async lookup - this will mark the peer as queried const lookup_id = try dht.findNodeAsync(target_id); _ = lookup_id; // Create a mock response (normally would come from network) const responder_keypair = Ed25519.KeyPair.generate(); var req_id_bytes: [8]u8 = undefined; std.crypto.random.bytes(&req_id_bytes); const req_id = std.mem.readInt(u64, &req_id_bytes, .little); // Track a pending response manually for testing dht.mutex.lock(); try dht.pending_responses.put(req_id, .{ .request_id = req_id, .target = peer_id.bytes, .query_type = .find_node, .sent_at = std.time.timestamp(), }); dht.mutex.unlock(); // Create signed response const auth = try createTestSignedMessage( allocator, responder_keypair, req_id, peer_id.bytes, DhtFindNodeResponse.MSG_TYPE, &[_]u8{}, ); // Create some nodes to return var nodes: [2]NodeInfo = undefined; for (0..2) |i| { var node_id: [32]u8 = undefined; std.crypto.random.bytes(&node_id); nodes[i] = .{ .node_id = node_id, .address = [_]u8{'1', '2', '7', '.', '0', '.', '0', '.', '1', ':', '8', '0', '0', '0'} ++ [_]u8{0} ** 32, .address_len = 14, }; } const response = DhtFindNodeResponse{ .request_id = req_id, .closest_nodes = &nodes, .auth = auth, }; // Handle response - should incorporate new nodes try dht.handleFindNodeResponse(response, peer_id.bytes); // The response should be processed without error // (exact behavior depends on lookup state) } test "DHT formatFingerprint" { const key = [_]u8{0xAB} ** 32; const fingerprint = formatFingerprint(key); // Verify fingerprint is 64 hex chars try std.testing.expectEqual(@as(usize, 64), fingerprint.len); // All bytes should be valid hex for (fingerprint) |c| { try std.testing.expect((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f')); } } test "DHT getIdentityFingerprint" { const identity = [_]u8{0xCD} ** 32; const fingerprint = getIdentityFingerprint(identity); // Fingerprint should be 32 bytes try std.testing.expectEqual(@as(usize, 32), fingerprint.len); } test "DHT limit functions" { // Test all limit functions return sensible values (module-level functions) try std.testing.expect(getDefaultTTL() > 0); try std.testing.expect(getMaxValueSize() > 0); try std.testing.expect(getMaxResponseNodes() > 0); try std.testing.expect(getMaxAmplificationFactor() > 0); try std.testing.expect(getMinRequestSize() > 0); } test "LookupState basic operations" { const allocator = std.testing.allocator; const target = [_]u8{0xEF} ** 32; var lookup = LookupState.init(allocator, target); defer lookup.deinit(); // Initial state try std.testing.expectEqual(target, lookup.target); try std.testing.expectEqual(@as(usize, 0), lookup.closest_seen.items.len); try std.testing.expectEqual(@as(usize, 0), lookup.queried.count()); } test "LookupState initWithLimits" { const allocator = std.testing.allocator; const target = [_]u8{0x12} ** 32; var lookup = LookupState.initWithLimits(allocator, target, 10, 50); defer lookup.deinit(); try std.testing.expectEqual(target, lookup.target); } test "LookupState addClosestSeen and addQueried" { const allocator = std.testing.allocator; const target = [_]u8{0x34} ** 32; var lookup = LookupState.init(allocator, target); defer lookup.deinit(); // Add some nodes const node1 = [_]u8{0x56} ** 32; const node2 = [_]u8{0x78} ** 32; try lookup.addClosestSeen(node1); try lookup.addClosestSeen(node2); try std.testing.expectEqual(@as(usize, 2), lookup.closest_seen.items.len); // Add to queried try lookup.addQueried(node1); try std.testing.expectEqual(@as(usize, 1), lookup.queried.count()); } test "NetworkSender hasSender" { // Test with no sender - all callbacks are null by default const empty_sender = NetworkSender{}; try std.testing.expect(!empty_sender.hasSender()); } test "DhtCoordinator isSecureMode" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = routing.KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); // Default initialization has require_tofu true but no callback var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // isSecureMode requires both require_tofu=true AND tofu_callback set // Without callback, it's not in secure mode try std.testing.expect(!dht.isSecureMode()); } test "DhtCoordinator initInsecureForDevelopment" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = routing.KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); // Insecure mode for development var dht = DhtCoordinator.initInsecureForDevelopment(allocator, &routing_table, local_id.bytes); defer dht.deinit(); try std.testing.expect(!dht.isSecureMode()); } test "DhtCoordinator getIdentityPublicKey" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = routing.KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); const pub_key = dht.getIdentityPublicKey(); // Key should be set try std.testing.expectEqual(@as(usize, 32), pub_key.len); } test "DhtCoordinator isLookupComplete with unknown lookup" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = routing.KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Unknown lookup should return true (considered complete) try std.testing.expect(dht.isLookupComplete(999999)); } test "DhtCoordinator cancelLookup with unknown lookup" { const allocator = std.testing.allocator; const local_id = PeerId.init(); var routing_table = routing.KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); var dht = DhtCoordinator.init(allocator, &routing_table, local_id.bytes); defer dht.deinit(); // Should not crash when canceling unknown lookup dht.cancelLookup(999999); }