//! Message definitions and types for the protocol const std = @import("std"); const protocol = @import("protocol.zig"); /// Unique message identifier pub const MessageId = u64; /// Node identifier (32 bytes for cryptographic hash) pub const NodeId = [protocol.Network.NODE_ID_SIZE]u8; /// Network address pub const NetworkAddress = struct { ip: [protocol.Network.ADDRESS_SIZE]u8, port: u16, pub fn format(self: NetworkAddress, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; const ip_str = std.net.Ip4Address.init(self.ip, 0).toString(); try writer.print("{s}:{d}", .{ ip_str, self.port }); } }; /// Message header structure pub const MessageHeader = struct { /// Magic number for protocol identification magic: u32 = protocol.Serialization.MAGIC_NUMBER, /// Protocol version version: u16 = protocol.PROTOCOL_VERSION, /// Message type msg_type: protocol.MessageType, /// Message flags flags: u8 = 0, /// Message identifier id: MessageId, /// Source node ID source: NodeId, /// Destination node ID (0xFF...FF for broadcast) dest: NodeId, /// Message priority priority: protocol.Priority = .normal, /// TTL (time to live) in hops ttl: u8 = protocol.Limits.MAX_HOPS, /// Timestamp when message was created timestamp: i64, /// Reserved field for future use reserved: u8 = 0, pub fn init(msg_type: protocol.MessageType, id: MessageId, source: NodeId, dest: NodeId) MessageHeader { return .{ .msg_type = msg_type, .id = id, .source = source, .dest = dest, .timestamp = std.time.timestamp(), }; } }; /// Base message structure pub const BaseMessage = struct { header: MessageHeader, payload: []const u8, pub fn getType(self: BaseMessage) protocol.MessageType { return self.header.msg_type; } pub fn getId(self: BaseMessage) MessageId { return self.header.id; } pub fn getSource(self: BaseMessage) NodeId { return self.header.source; } pub fn getDest(self: BaseMessage) NodeId { return self.header.dest; } pub fn isBroadcast(self: BaseMessage) bool { return self.header.flags & protocol.MessageFlags.BROADCAST != 0; } pub fn isEncrypted(self: BaseMessage) bool { return self.header.flags & protocol.MessageFlags.ENCRYPTED != 0; } pub fn requiresCleanup(self: BaseMessage) bool { return self.isEncrypted(); } pub fn decrementTTL(self: *BaseMessage) bool { if (self.header.ttl == 0) return false; self.header.ttl -= 1; return self.header.ttl > 0; } }; /// Discovery messages /// MED-4 FIX: Discovery messages now include signatures to prevent spoofing pub const DiscoveryHello = struct { pub const msg_type: protocol.MessageType = .discovery_hello; /// Protocol version version: u16, /// Node capabilities capabilities: u32, /// Network address address: NetworkAddress, /// MED-4 FIX: Ed25519 signature over (version || capabilities || address || timestamp || signer_id) signature: [64]u8 = [_]u8{0} ** 64, /// MED-4 FIX: Node ID of the signer signer_id: NodeId = [_]u8{0} ** 32, /// MED-4 FIX: Timestamp for replay prevention timestamp: i64 = 0, pub fn init(version: u16, capabilities: u32, addr: NetworkAddress) DiscoveryHello { return .{ .version = version, .capabilities = capabilities, .address = addr }; } /// MED-4 FIX: Initialize with signature for authenticated discovery pub fn initSigned( version: u16, capabilities: u32, addr: NetworkAddress, signer_id: NodeId, timestamp: i64, signature: [64]u8, ) DiscoveryHello { return .{ .version = version, .capabilities = capabilities, .address = addr, .signature = signature, .signer_id = signer_id, .timestamp = timestamp, }; } /// MED-4 FIX: Check if this message has a signature (constant-time) /// Uses constant-time comparison to prevent timing side-channels pub fn isSigned(self: *const DiscoveryHello) bool { // Accumulate result without early return for constant-time behavior var result: u8 = 0; for (self.signature) |byte| { result |= byte; } return result != 0; } }; pub const DiscoveryResponse = struct { pub const msg_type: protocol.MessageType = .discovery_response; /// Original message ID original_id: MessageId, /// Responding node capabilities capabilities: u32, /// Node's network address address: NetworkAddress, /// List of known nodes known_nodes: []const NodeId, /// MED-4 FIX: Ed25519 signature signature: [64]u8 = [_]u8{0} ** 64, /// MED-4 FIX: Node ID of the signer signer_id: NodeId = [_]u8{0} ** 32, /// MED-4 FIX: Timestamp for replay prevention timestamp: i64 = 0, pub fn init(original_id: MessageId, capabilities: u32, address: NetworkAddress) DiscoveryResponse { return .{ .original_id = original_id, .capabilities = capabilities, .address = address, .known_nodes = &.{} }; } /// MED-4 FIX: Check if this message has a signature (constant-time) pub fn isSigned(self: *const DiscoveryResponse) bool { // Accumulate result without early return for constant-time behavior var result: u8 = 0; for (self.signature) |byte| { result |= byte; } return result != 0; } }; pub const DiscoveryAnnounce = struct { pub const msg_type: protocol.MessageType = .discovery_announce; /// Default TTL for discovery announce (prevents amplification attacks) pub const DEFAULT_TTL: u8 = 5; /// Node capabilities capabilities: u32, /// Network address address: NetworkAddress, /// Time-to-live: decremented on each hop, message dropped when 0 ttl: u8, /// MED-4 FIX: Ed25519 signature signature: [64]u8 = [_]u8{0} ** 64, /// MED-4 FIX: Node ID of the signer signer_id: NodeId = [_]u8{0} ** 32, /// MED-4 FIX: Timestamp for replay prevention timestamp: i64 = 0, pub fn init(capabilities: u32, address: NetworkAddress) DiscoveryAnnounce { return .{ .capabilities = capabilities, .address = address, .ttl = DEFAULT_TTL }; } pub fn initWithTtl(capabilities: u32, address: NetworkAddress, ttl: u8) DiscoveryAnnounce { return .{ .capabilities = capabilities, .address = address, .ttl = ttl }; } /// Decrement TTL and return whether the message should be forwarded pub fn decrementTtl(self: *DiscoveryAnnounce) bool { if (self.ttl == 0) return false; self.ttl -= 1; return self.ttl > 0; } /// MED-4 FIX: Check if this message has a signature (constant-time) pub fn isSigned(self: *const DiscoveryAnnounce) bool { // Accumulate result without early return for constant-time behavior var result: u8 = 0; for (self.signature) |byte| { result |= byte; } return result != 0; } }; /// Topology messages pub const TopologyQuery = struct { pub const msg_type: protocol.MessageType = .topology_query; /// Query ID query_id: MessageId, /// Requested topology type topology_type: u8, pub fn init(query_id: MessageId, topology_type: u8) TopologyQuery { return .{ .query_id = query_id, .topology_type = topology_type }; } }; pub const TopologyResponse = struct { pub const msg_type: protocol.MessageType = .topology_response; /// Original query ID query_id: MessageId, /// Topology data topology_data: []const u8, pub fn init(query_id: MessageId, topology_data: []const u8) TopologyResponse { return .{ .query_id = query_id, .topology_data = topology_data }; } }; pub const TopologyUpdate = struct { pub const msg_type: protocol.MessageType = .topology_update; /// Default TTL for topology updates (prevents amplification attacks) pub const DEFAULT_TTL: u8 = 5; /// Update sequence number sequence: u32, /// Time-to-live: decremented on each hop, message dropped when 0 ttl: u8, /// Nodes added to the topology added_nodes: []const [32]u8, /// Nodes removed from the topology removed_nodes: []const [32]u8, /// Additional topology changes (legacy/extensible field) changes: []const u8, pub fn init(sequence: u32, added_nodes: []const [32]u8, removed_nodes: []const [32]u8) TopologyUpdate { return .{ .sequence = sequence, .ttl = DEFAULT_TTL, .added_nodes = added_nodes, .removed_nodes = removed_nodes, .changes = &[_]u8{}, }; } pub fn initWithTtl(sequence: u32, ttl: u8, added_nodes: []const [32]u8, removed_nodes: []const [32]u8) TopologyUpdate { return .{ .sequence = sequence, .ttl = ttl, .added_nodes = added_nodes, .removed_nodes = removed_nodes, .changes = &[_]u8{}, }; } /// Initialize from raw changes buffer (used during deserialization) /// This is for backward compatibility when the wire format only has sequence + changes pub fn initFromChanges(sequence: u32, changes: []const u8) TopologyUpdate { return .{ .sequence = sequence, .ttl = DEFAULT_TTL, .added_nodes = &[_][32]u8{}, .removed_nodes = &[_][32]u8{}, .changes = changes, }; } /// Decrement TTL and return whether the message should be forwarded pub fn decrementTtl(self: *TopologyUpdate) bool { if (self.ttl == 0) return false; self.ttl -= 1; return self.ttl > 0; } }; /// Data transfer messages pub const DataRequest = struct { pub const msg_type: protocol.MessageType = .data_request; /// Request ID request_id: MessageId, /// Data identifier data_id: []const u8, /// Offset in data offset: u64, /// Requested size size: u32, pub fn init(request_id: MessageId, data_id: []const u8, offset: u64, size: u32) DataRequest { return .{ .request_id = request_id, .data_id = data_id, .offset = offset, .size = size }; } }; pub const DataResponse = struct { pub const msg_type: protocol.MessageType = .data_response; /// Original request ID request_id: MessageId, /// Data identifier data_id: []const u8, /// Actual data data: []const u8, /// Total size if this is the final chunk total_size: ?u64, pub fn init(request_id: MessageId, data_id: []const u8, data: []const u8) DataResponse { return .{ .request_id = request_id, .data_id = data_id, .data = data, .total_size = null }; } }; pub const DataChunk = struct { pub const msg_type: protocol.MessageType = .data_chunk; /// Chunk sequence number sequence: u32, /// Data identifier data_id: []const u8, /// Chunk data chunk_data: []const u8, /// Is this the final chunk is_final: bool, pub fn init(sequence: u32, data_id: []const u8, chunk_data: []const u8, is_final: bool) DataChunk { return .{ .sequence = sequence, .data_id = data_id, .chunk_data = chunk_data, .is_final = is_final }; } }; /// Routing messages pub const RouteQuery = struct { pub const msg_type: protocol.MessageType = .route_query; /// Query ID query_id: MessageId, /// Target node ID target: NodeId, /// Query parameters params: []const u8, pub fn init(query_id: MessageId, target: NodeId) RouteQuery { return .{ .query_id = query_id, .target = target, .params = &.{} }; } }; pub const RouteResponse = struct { pub const msg_type: protocol.MessageType = .route_response; /// Original query ID query_id: MessageId, /// Route information route_info: []const u8, /// Next hop information next_hop: ?NodeId, /// SECURITY: Ed25519 signature over route data (proves authenticity) signature: [64]u8, /// SECURITY: Signer's node ID for verification signer_id: NodeId, /// HIGH-5 FIX: Timestamp when signature was created (for replay protection) timestamp: i64, /// HIGH-5 FIX: Origin node ID (destination of the route, for signature verification) origin: NodeId, pub fn init(query_id: MessageId, route_info: []const u8) RouteResponse { return .{ .query_id = query_id, .route_info = route_info, .next_hop = null, .signature = [_]u8{0} ** 64, .signer_id = [_]u8{0} ** 32, .timestamp = 0, .origin = [_]u8{0} ** 32, }; } pub fn initSigned( query_id: MessageId, route_info: []const u8, next_hop: ?NodeId, signature: [64]u8, signer_id: NodeId, timestamp: i64, origin: NodeId, ) RouteResponse { return .{ .query_id = query_id, .route_info = route_info, .next_hop = next_hop, .signature = signature, .signer_id = signer_id, .timestamp = timestamp, .origin = origin, }; } }; pub const RouteUpdate = struct { pub const msg_type: protocol.MessageType = .route_update; /// Update sequence number sequence: u32, /// Route changes route_changes: []const u8, /// SECURITY: Ed25519 signature over update data (proves authenticity) signature: [64]u8, /// SECURITY: Signer's node ID for verification signer_id: NodeId, pub fn init(sequence: u32, route_changes: []const u8) RouteUpdate { return .{ .sequence = sequence, .route_changes = route_changes, .signature = [_]u8{0} ** 64, .signer_id = [_]u8{0} ** 32, }; } pub fn initSigned( sequence: u32, route_changes: []const u8, signature: [64]u8, signer_id: NodeId, ) RouteUpdate { return .{ .sequence = sequence, .route_changes = route_changes, .signature = signature, .signer_id = signer_id, }; } }; /// Control messages pub const Ping = struct { pub const msg_type: protocol.MessageType = .ping; /// Ping sequence number sequence: u32, /// Additional data data: []const u8, pub fn init(sequence: u32) Ping { return .{ .sequence = sequence, .data = &.{} }; } }; pub const Pong = struct { pub const msg_type: protocol.MessageType = .pong; /// Original ping sequence sequence: u32, /// Round-trip time in milliseconds rtt: u32, pub fn init(sequence: u32, rtt: u32) Pong { return .{ .sequence = sequence, .rtt = rtt }; } }; pub const Error = struct { pub const msg_type: protocol.MessageType = .err; /// Original message ID (if applicable) original_id: ?MessageId, /// Error code error_code: protocol.ErrorCode, /// Error message message: []const u8, pub fn init(original_id: ?MessageId, error_code: protocol.ErrorCode, message: []const u8) Error { return .{ .original_id = original_id, .error_code = error_code, .message = message }; } }; /// Application-specific messages pub const AppData = struct { pub const msg_type: protocol.MessageType = .app_data; /// Application identifier app_id: u16, /// Application data data: []const u8, pub fn init(app_id: u16, data: []const u8) AppData { return .{ .app_id = app_id, .data = data }; } }; pub const AppControl = struct { pub const msg_type: protocol.MessageType = .app_control; /// Application identifier app_id: u16, /// Control command command: u16, /// Control parameters params: []const u8, pub fn init(app_id: u16, command: u16, params: []const u8) AppControl { return .{ .app_id = app_id, .command = command, .params = params }; } }; /// DHT messages for distributed hash table operations pub const DhtFindNode = struct { pub const msg_type: protocol.MessageType = .dht_find_node; request_id: u64, target_id: NodeId, sender_id: NodeId, /// Bidirectional IP Reflection: The observed address of the TARGET (receiver) /// This tells the receiver what their address looks like from our perspective target_observed_addr: [18]u8 = [_]u8{0} ** 18, target_observed_addr_len: u8 = 0, /// Per-message random salt for per-peer replay detection wire_nonce: u64 = 0, /// Sender timestamp for temporal replay validation wire_timestamp: i64 = 0, pub fn init(target: NodeId, sender: NodeId) DhtFindNode { return .{ .request_id = generateRequestId(), .target_id = target, .sender_id = sender, .target_observed_addr = [_]u8{0} ** 18, .target_observed_addr_len = 0, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } pub fn initWithTargetObserved(target: NodeId, sender: NodeId, addr: [18]u8, addr_len: u8) DhtFindNode { return .{ .request_id = generateRequestId(), .target_id = target, .sender_id = sender, .target_observed_addr = addr, .target_observed_addr_len = addr_len, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } }; pub const DhtFindNodeResponse = struct { pub const msg_type: protocol.MessageType = .dht_find_node_response; request_id: u64, closest_nodes: []const NodeInfo, /// IP Reflection: The observed source address of the requester (bundled STUN) /// Format: IPv4 = 6 bytes (4 IP + 2 port), IPv6 = 18 bytes (16 IP + 2 port) observed_addr: [18]u8 = [_]u8{0} ** 18, observed_addr_len: u8 = 0, /// Per-message random salt for per-peer replay detection wire_nonce: u64 = 0, /// Sender timestamp for temporal replay validation wire_timestamp: i64 = 0, pub const NodeInfo = struct { node_id: NodeId, address: [46]u8, address_len: u8, }; pub fn init(request_id: u64, closest_nodes: []const NodeInfo) DhtFindNodeResponse { return .{ .request_id = request_id, .closest_nodes = closest_nodes, .observed_addr = [_]u8{0} ** 18, .observed_addr_len = 0, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } pub fn initWithObserved(request_id: u64, closest_nodes: []const NodeInfo, addr: [18]u8, addr_len: u8) DhtFindNodeResponse { return .{ .request_id = request_id, .closest_nodes = closest_nodes, .observed_addr = addr, .observed_addr_len = addr_len, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } }; pub const DhtStore = struct { pub const msg_type: protocol.MessageType = .dht_store; request_id: u64, key: [32]u8, value: []const u8, ttl: u32, sender_id: NodeId, /// Bidirectional IP Reflection: The observed address of the TARGET (receiver) /// This tells the receiver what their address looks like from our perspective target_observed_addr: [18]u8 = [_]u8{0} ** 18, target_observed_addr_len: u8 = 0, /// Per-message random salt for per-peer replay detection wire_nonce: u64 = 0, /// Sender timestamp for temporal replay validation wire_timestamp: i64 = 0, pub fn init(key: [32]u8, value: []const u8, ttl: u32, sender: NodeId) DhtStore { return .{ .request_id = generateRequestId(), .key = key, .value = value, .ttl = ttl, .sender_id = sender, .target_observed_addr = [_]u8{0} ** 18, .target_observed_addr_len = 0, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } pub fn initWithTargetObserved(key: [32]u8, value: []const u8, ttl: u32, sender: NodeId, addr: [18]u8, addr_len: u8) DhtStore { return .{ .request_id = generateRequestId(), .key = key, .value = value, .ttl = ttl, .sender_id = sender, .target_observed_addr = addr, .target_observed_addr_len = addr_len, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } }; pub const DhtStoreResponse = struct { pub const msg_type: protocol.MessageType = .dht_store_response; request_id: u64, success: bool, /// IP Reflection: The observed source address of the requester (bundled STUN) observed_addr: [18]u8 = [_]u8{0} ** 18, observed_addr_len: u8 = 0, /// Per-message random salt for per-peer replay detection wire_nonce: u64 = 0, /// Sender timestamp for temporal replay validation wire_timestamp: i64 = 0, pub fn init(request_id: u64, success: bool) DhtStoreResponse { return .{ .request_id = request_id, .success = success, .observed_addr = [_]u8{0} ** 18, .observed_addr_len = 0, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } pub fn initWithObserved(request_id: u64, success: bool, addr: [18]u8, addr_len: u8) DhtStoreResponse { return .{ .request_id = request_id, .success = success, .observed_addr = addr, .observed_addr_len = addr_len, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } }; pub const DhtFindValue = struct { pub const msg_type: protocol.MessageType = .dht_find_value; request_id: u64, key: [32]u8, sender_id: NodeId, /// Bidirectional IP Reflection: The observed address of the TARGET (receiver) /// This tells the receiver what their address looks like from our perspective target_observed_addr: [18]u8 = [_]u8{0} ** 18, target_observed_addr_len: u8 = 0, /// Per-message random salt for per-peer replay detection wire_nonce: u64 = 0, /// Sender timestamp for temporal replay validation wire_timestamp: i64 = 0, pub fn init(key: [32]u8, sender: NodeId) DhtFindValue { return .{ .request_id = generateRequestId(), .key = key, .sender_id = sender, .target_observed_addr = [_]u8{0} ** 18, .target_observed_addr_len = 0, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } pub fn initWithTargetObserved(key: [32]u8, sender: NodeId, addr: [18]u8, addr_len: u8) DhtFindValue { return .{ .request_id = generateRequestId(), .key = key, .sender_id = sender, .target_observed_addr = addr, .target_observed_addr_len = addr_len, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } }; pub const DhtFindValueResponse = struct { pub const msg_type: protocol.MessageType = .dht_find_value_response; request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const DhtFindNodeResponse.NodeInfo, /// IP Reflection: The observed source address of the requester (bundled STUN) observed_addr: [18]u8 = [_]u8{0} ** 18, observed_addr_len: u8 = 0, /// Per-message random salt for per-peer replay detection wire_nonce: u64 = 0, /// Sender timestamp for temporal replay validation wire_timestamp: i64 = 0, pub fn init(request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const DhtFindNodeResponse.NodeInfo) DhtFindValueResponse { return .{ .request_id = request_id, .found = found, .value = value, .closest_nodes = closest_nodes, .observed_addr = [_]u8{0} ** 18, .observed_addr_len = 0, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } pub fn initWithObserved(request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const DhtFindNodeResponse.NodeInfo, addr: [18]u8, addr_len: u8) DhtFindValueResponse { return .{ .request_id = request_id, .found = found, .value = value, .closest_nodes = closest_nodes, .observed_addr = addr, .observed_addr_len = addr_len, .wire_nonce = generateWireNonce(), .wire_timestamp = std.time.timestamp(), }; } }; /// Generate a cryptographically random wire nonce for replay detection pub fn generateWireNonce() u64 { var bytes: [8]u8 = undefined; std.crypto.random.bytes(&bytes); return std.mem.readInt(u64, &bytes, .little); } /// Generate a unique request ID for correlating DHT request/response pairs. /// Replay detection is handled by wire_nonce, so this only needs to be unique /// enough to match responses to their pending requests. fn generateRequestId() u64 { var bytes: [8]u8 = undefined; std.crypto.random.bytes(&bytes); return std.mem.readInt(u64, &bytes, .little); } /// Security messages for key exchange pub const KeyExchangeInit = struct { pub const msg_type: protocol.MessageType = .key_exchange_init; /// Initiator's ephemeral public key (X25519) initiator_public_key: [32]u8, /// SECURITY: Ed25519 signature over signing_data (proves identity and freshness) /// signing_data = ephemeral_key || timestamp || session_nonce signature: [64]u8, /// SECURITY: Initiator's Ed25519 identity public key identity_key: [32]u8, /// SECURITY: Random session nonce for unique key derivation session_nonce: [32]u8, /// SECURITY FIX: Timestamp to prevent replay attacks (Unix timestamp in seconds) timestamp: i64, /// Maximum allowed age of key exchange messages (SECURITY: reduced from 5 minutes to 60 seconds) pub const MAX_MESSAGE_AGE: i64 = 60; /// Maximum allowed clock skew (30 seconds) pub const MAX_CLOCK_SKEW: i64 = 30; pub fn init(initiator_public_key: [32]u8, signature: [64]u8, identity_key: [32]u8, session_nonce: [32]u8, timestamp: i64) KeyExchangeInit { return .{ .initiator_public_key = initiator_public_key, .signature = signature, .identity_key = identity_key, .session_nonce = session_nonce, .timestamp = timestamp, }; } /// Build the data that should be signed for this message pub fn buildSigningData(self: *const KeyExchangeInit) [72]u8 { var data: [72]u8 = undefined; @memcpy(data[0..32], &self.initiator_public_key); std.mem.writeInt(i64, data[32..40], self.timestamp, .little); @memcpy(data[40..72], &self.session_nonce); return data; } /// Validate timestamp is within acceptable range pub fn validateTimestamp(self: *const KeyExchangeInit, current_time: i64) bool { const age = current_time - self.timestamp; // Reject if too old if (age > MAX_MESSAGE_AGE) return false; // Reject if too far in future (clock skew) if (age < -MAX_CLOCK_SKEW) return false; return true; } }; pub const KeyExchangeResponse = struct { pub const msg_type: protocol.MessageType = .key_exchange_response; /// Responder's ephemeral public key (X25519) responder_public_key: [32]u8, /// SECURITY: Ed25519 signature over signing_data (proves identity and freshness) /// signing_data = ephemeral_key || timestamp || initiator_session_nonce signature: [64]u8, /// SECURITY: Responder's Ed25519 identity public key identity_key: [32]u8, /// SECURITY FIX: Timestamp to prevent replay attacks (Unix timestamp in seconds) timestamp: i64, /// SECURITY FIX: Echo back initiator's session nonce to confirm receipt initiator_session_nonce: [32]u8, /// Maximum allowed age of key exchange messages (SECURITY: reduced from 5 minutes to 60 seconds) pub const MAX_MESSAGE_AGE: i64 = 60; /// Maximum allowed clock skew (30 seconds) pub const MAX_CLOCK_SKEW: i64 = 30; pub fn init(responder_public_key: [32]u8, signature: [64]u8, identity_key: [32]u8, timestamp: i64, initiator_session_nonce: [32]u8) KeyExchangeResponse { return .{ .responder_public_key = responder_public_key, .signature = signature, .identity_key = identity_key, .timestamp = timestamp, .initiator_session_nonce = initiator_session_nonce, }; } /// Build the data that should be signed for this message pub fn buildSigningData(self: *const KeyExchangeResponse) [72]u8 { var data: [72]u8 = undefined; @memcpy(data[0..32], &self.responder_public_key); std.mem.writeInt(i64, data[32..40], self.timestamp, .little); @memcpy(data[40..72], &self.initiator_session_nonce); return data; } /// Validate timestamp is within acceptable range pub fn validateTimestamp(self: *const KeyExchangeResponse, current_time: i64) bool { const age = current_time - self.timestamp; // Reject if too old if (age > MAX_MESSAGE_AGE) return false; // Reject if too far in future (clock skew) if (age < -MAX_CLOCK_SKEW) return false; return true; } }; /// SEC-H2 FIX: Key confirmation message to prove both parties derived the same keys /// Sent after key exchange completes. Each party generates a confirmation tag /// using HMAC(derived_hmac_key, "confirm" || role || transcript) and sends it. /// Both parties must verify the other's tag before considering the channel secure. pub const KeyConfirmation = struct { pub const msg_type: protocol.MessageType = .key_confirmation; /// HMAC-based key confirmation tag (32 bytes) /// Generated using KeyExchange.generateKeyConfirmation() confirmation_tag: [32]u8, pub fn init(confirmation_tag: [32]u8) KeyConfirmation { return .{ .confirmation_tag = confirmation_tag, }; } }; /// Per-process random SipHash key for deterministic nonce/ID computation. /// Used only on the receiver side (getIdForReplay), /// so it does NOT need to agree between sender and receiver. A per-process /// random key prevents attackers from precomputing hash collisions. /// /// Thread safety: Uses std.once to ensure exactly one initialization even when /// multiple HandlerRegistry instances (e.g. TestP2PPair server + client) call /// getReplaySiphashKey() concurrently from different processing_mutex scopes. var replay_siphash_key: [16]u8 = undefined; var replay_siphash_key_once = std.once(initReplaySiphashKey); fn initReplaySiphashKey() void { std.crypto.random.bytes(&replay_siphash_key); } fn getReplaySiphashKey() *const [16]u8 { replay_siphash_key_once.call(); return &replay_siphash_key; } /// Union of all message types pub const Message = union(protocol.MessageType) { discovery_hello: DiscoveryHello, discovery_response: DiscoveryResponse, discovery_announce: DiscoveryAnnounce, topology_query: TopologyQuery, topology_response: TopologyResponse, topology_update: TopologyUpdate, data_request: DataRequest, data_response: DataResponse, data_chunk: DataChunk, route_query: RouteQuery, route_response: RouteResponse, route_update: RouteUpdate, ping: Ping, pong: Pong, err: Error, key_exchange_init: KeyExchangeInit, key_exchange_response: KeyExchangeResponse, key_confirmation: KeyConfirmation, dht_find_node: DhtFindNode, dht_find_node_response: DhtFindNodeResponse, dht_store: DhtStore, dht_store_response: DhtStoreResponse, dht_find_value: DhtFindValue, dht_find_value_response: DhtFindValueResponse, app_data: AppData, app_control: AppControl, /// Get the message type pub fn getType(self: Message) protocol.MessageType { return @as(protocol.MessageType, @enumFromInt(@intFromEnum(self))); } /// Get the message ID (if applicable) pub fn getId(self: Message) ?MessageId { return switch (self) { .discovery_response => |msg| msg.original_id, .topology_query => |msg| msg.query_id, .topology_response => |msg| msg.query_id, .data_request => |msg| msg.request_id, .data_response => |msg| msg.request_id, .route_query => |msg| msg.query_id, .route_response => |msg| msg.query_id, .ping => |msg| @as(MessageId, msg.sequence), .pong => |msg| @as(MessageId, msg.sequence), .err => |msg| msg.original_id, .dht_find_node => |msg| msg.request_id, .dht_find_node_response => |msg| msg.request_id, .dht_store => |msg| msg.request_id, .dht_store_response => |msg| msg.request_id, .dht_find_value => |msg| msg.request_id, .dht_find_value_response => |msg| msg.request_id, else => null, }; } /// Get message ID for replay protection (derives stable ID when not available) pub fn getIdForReplay(self: Message) MessageId { return self.getId() orelse switch (self) { // Discovery messages: derive ID from signer identity + timestamp .discovery_hello => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(m.signer_id[0..8]); hasher.update(std.mem.asBytes(&m.timestamp)); break :blk hasher.finalInt(); }, .discovery_announce => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(m.signer_id[0..8]); hasher.update(std.mem.asBytes(&m.timestamp)); break :blk hasher.finalInt(); }, // App messages: derive ID from app_id + content .app_data => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(std.mem.asBytes(&m.app_id)); const data_prefix = m.data[0..@min(m.data.len, 64)]; hasher.update(data_prefix); break :blk hasher.finalInt(); }, .app_control => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(std.mem.asBytes(&m.app_id)); hasher.update(std.mem.asBytes(&m.command)); break :blk hasher.finalInt(); }, // Sequenced types: derive ID from sequence + content prefix. // These also have sliding window protection via checkSequence(). .topology_update => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(std.mem.asBytes(&m.sequence)); hasher.update(std.mem.asBytes(&m.ttl)); const changes_prefix = m.changes[0..@min(m.changes.len, 32)]; hasher.update(changes_prefix); break :blk hasher.finalInt(); }, .data_chunk => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(std.mem.asBytes(&m.sequence)); const id_prefix = m.data_id[0..@min(m.data_id.len, 32)]; hasher.update(id_prefix); break :blk hasher.finalInt(); }, .route_update => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(std.mem.asBytes(&m.sequence)); hasher.update(m.signer_id[0..8]); break :blk hasher.finalInt(); }, // Key exchange: derive from unique cryptographic material .key_exchange_response => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(&m.responder_public_key); hasher.update(std.mem.asBytes(&m.timestamp)); break :blk hasher.finalInt(); }, .key_confirmation => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(&m.confirmation_tag); break :blk hasher.finalInt(); }, .key_exchange_init => |m| blk: { var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(getReplaySiphashKey()); hasher.update(&m.initiator_public_key); hasher.update(std.mem.asBytes(&m.timestamp)); break :blk hasher.finalInt(); }, else => blk: { // All known message types are handled above or by getId(). // If we reach here, a new message type was added without updating // this switch. Using random means replay protection relies solely // on per-peer msg_id dedup and Noise AEAD. var id: [8]u8 = undefined; std.crypto.random.bytes(&id); break :blk std.mem.readInt(u64, &id, .little); }, }; } /// Get timestamp for replay protection. /// /// Returns the sender-provided timestamp where available, enabling the replay /// protector to reject stale or future-dated messages. Types without an embedded /// timestamp return the receiver's clock (std.time.timestamp()), which makes /// timestamp validation a no-op for those types. This is acceptable because: /// /// - With Noise ON (production): AEAD prevents replay at the transport layer. /// - msg_id dedup (PeerMessageKey) catches duplicate request_id/query_id. /// - Sequenced types (topology_update, data_chunk, route_update) have sliding /// window protection via checkSequence(). /// - Non-DHT custom messages bypass this entirely — they use the wire envelope /// timestamp directly in handleNetworkMessageImpl(). pub fn getTimestamp(self: Message) i64 { return switch (self) { // DHT messages: wire-level timestamp from serialization .dht_find_node => |m| m.wire_timestamp, .dht_find_node_response => |m| m.wire_timestamp, .dht_store => |m| m.wire_timestamp, .dht_store_response => |m| m.wire_timestamp, .dht_find_value => |m| m.wire_timestamp, .dht_find_value_response => |m| m.wire_timestamp, // Discovery and key exchange: embedded sender timestamp .discovery_hello => |m| m.timestamp, .discovery_announce => |m| m.timestamp, .discovery_response => |m| m.timestamp, .key_exchange_init => |m| m.timestamp, .key_exchange_response => |m| m.timestamp, // RouteResponse has a signed timestamp .route_response => |m| m.timestamp, // All other types have no sender timestamp. Returning receiver's clock // makes validateTimestamp() a no-op. Replay defense for these types relies // on msg_id dedup, sequence windows, and Noise AEAD. else => std.time.timestamp(), }; } /// Get sequence number for replay protection pub fn getSequence(self: Message) u64 { return switch (self) { .ping => |msg| @as(u64, msg.sequence), .pong => |msg| @as(u64, msg.sequence), .topology_update => |msg| msg.sequence, .route_update => |msg| msg.sequence, .data_chunk => |msg| msg.sequence, else => 0, // 0 means no ordering required }; } /// Get source node ID for replay protection pub fn getSource(self: Message) NodeId { // Extract source from message or return zero (broadcast/unknown) // Most messages don't include source_id in payload, it's in the header _ = self; return [_]u8{0} ** 32; // Will be overridden by handler context } }; /// Message builder for creating messages pub const MessageBuilder = struct { allocator: std.mem.Allocator, pub fn init(allocator: std.mem.Allocator) MessageBuilder { return .{ .allocator = allocator }; } /// Create a new message with header pub fn createMessage(self: MessageBuilder, msg_type: protocol.MessageType, source: NodeId, dest: NodeId) !Message { _ = source; _ = dest; const id = self.generateMessageId(); return switch (msg_type) { .discovery_hello => .{ .discovery_hello = DiscoveryHello.init(protocol.PROTOCOL_VERSION, 0, NetworkAddress{ .ip = .{0} ** protocol.Network.ADDRESS_SIZE, .port = 0, }), }, .ping => .{ // CRIT-2 FIX: Explicitly use lower 32 bits which contain the random component // The message ID is u64 with timestamp in high bits and random in low bits. // Ping sequence only needs uniqueness, so we use the random portion. .ping = Ping.init(@as(u32, @intCast(id & 0xFFFFFFFF))), }, else => return error.UnsupportedMessageType, }; } /// Generate a unique message ID using cryptographically strong randomness /// /// CRY-M1 FIX: To reduce birthday paradox collision risk at 2^32 messages, /// we combine a high-resolution timestamp with cryptographic randomness. /// - Top 32 bits: timestamp-derived value (ensures temporal uniqueness) /// - Bottom 32 bits: cryptographic random (ensures uniqueness within same time) /// /// This provides O(2^64) collision resistance in practice since messages /// within the same microsecond still have 32 bits of randomness, and /// messages across time have different timestamps. pub fn generateMessageId(self: MessageBuilder) MessageId { _ = self; // Use full 64 bits of cryptographic randomness for message IDs // This provides maximum entropy and unpredictability for security var random_bytes: [8]u8 = undefined; std.crypto.random.bytes(&random_bytes); return std.mem.readInt(u64, &random_bytes, .little); } }; test "message types and structures" { // Test message header creation var source: NodeId = .{0} ** protocol.Network.NODE_ID_SIZE; source[0] = 1; var dest: NodeId = .{0} ** protocol.Network.NODE_ID_SIZE; dest[0] = 2; const header = MessageHeader.init(.ping, 123, source, dest); try std.testing.expectEqual(protocol.MessageType.ping, header.msg_type); try std.testing.expectEqual(@as(MessageId, 123), header.id); try std.testing.expect(header.source[0] == 1); try std.testing.expect(header.dest[0] == 2); // Test base message operations var base_msg = BaseMessage{ .header = header, .payload = &.{} }; try std.testing.expectEqual(protocol.MessageType.ping, base_msg.getType()); try std.testing.expect(!base_msg.isBroadcast()); base_msg.header.flags |= protocol.MessageFlags.BROADCAST; try std.testing.expect(base_msg.isBroadcast()); // Test TTL decrement try std.testing.expect(base_msg.decrementTTL()); try std.testing.expectEqual(@as(u8, protocol.Limits.MAX_HOPS - 1), base_msg.header.ttl); } test "message IDs are unique" { const builder = MessageBuilder.init(std.testing.allocator); var seen = std.AutoHashMap(MessageId, void).init(std.testing.allocator); defer seen.deinit(); // Generate 10000 IDs and verify uniqueness var i: usize = 0; while (i < 10000) : (i += 1) { const id = builder.generateMessageId(); try std.testing.expect(seen.get(id) == null); try seen.put(id, {}); } } test "message IDs use full entropy" { const builder = MessageBuilder.init(std.testing.allocator); // Generate some IDs and verify they use full 64-bit space var has_high_bit = false; var has_low_bit = false; // Generate 1000 IDs to check for statistical distribution var i: usize = 0; while (i < 1000) : (i += 1) { const id = builder.generateMessageId(); // Check if high 32 bits are used if ((id >> 32) != 0) { has_high_bit = true; } // Check if low 32 bits are used if ((id & 0xFFFFFFFF) != 0) { has_low_bit = true; } if (has_high_bit and has_low_bit) break; } try std.testing.expect(has_high_bit); try std.testing.expect(has_low_bit); } test "message IDs are non-predictable" { const builder = MessageBuilder.init(std.testing.allocator); // Generate two consecutive IDs const id1 = builder.generateMessageId(); const id2 = builder.generateMessageId(); // They should not be sequential try std.testing.expect(id2 != id1 + 1); try std.testing.expect(id2 != id1 - 1); // They should be different try std.testing.expect(id1 != id2); } test "BaseMessage.getSource" { const source_id = [_]u8{0x01} ** 32; const dest_id = [_]u8{0x02} ** 32; const header = MessageHeader.init(.ping, 1, source_id, dest_id); const msg = BaseMessage{ .header = header, .payload = "" }; const src = msg.getSource(); try std.testing.expectEqual(source_id, src); } test "DiscoveryHello.init" { const addr = NetworkAddress{ .ip = [_]u8{0} ** protocol.Network.ADDRESS_SIZE, .port = 8080 }; const hello = DiscoveryHello.init(1, 0x01, addr); try std.testing.expectEqual(@as(u16, 1), hello.version); try std.testing.expectEqual(@as(u32, 0x01), hello.capabilities); try std.testing.expectEqual(@as(u16, 8080), hello.address.port); } test "DiscoveryAnnounce.initWithTtl" { const addr = NetworkAddress{ .ip = [_]u8{0} ** protocol.Network.ADDRESS_SIZE, .port = 9000 }; const announce = DiscoveryAnnounce.initWithTtl(0x03, addr, 3); try std.testing.expectEqual(@as(u32, 0x03), announce.capabilities); try std.testing.expectEqual(@as(u8, 3), announce.ttl); try std.testing.expectEqual(@as(u16, 9000), announce.address.port); } test "TopologyUpdate.initFromChanges" { const changes = "test changes"; const update = TopologyUpdate.initFromChanges(42, changes); try std.testing.expectEqual(@as(u32, 42), update.sequence); try std.testing.expectEqualStrings("test changes", update.changes); } test "Pong.init" { const pong = Pong.init(123, 50); try std.testing.expectEqual(@as(u32, 123), pong.sequence); try std.testing.expectEqual(@as(u32, 50), pong.rtt); } test "Ping.init" { const ping = Ping.init(456); try std.testing.expectEqual(@as(u32, 456), ping.sequence); }