//! DHT-based WebRTC Signaling //! //! Exchanges WebRTC SDP offers/answers and ICE candidates via the DHT, //! eliminating the need for a separate signaling server. //! //! Pattern: Both peers derive the same base signaling key from their public keys //! (order-independent). Each peer stores its messages at a key derived from //! the base key + their own pubkey, and reads the other peer's messages from //! the base key + the other's pubkey. This prevents collisions. //! //! Flow (Alice → Bob): //! 1. Alice computes signaling_key = computeSignalingKey(alice_pk, bob_pk) //! 2. Alice stores her offer at SHA-256(signaling_key || alice_pk || "offer") //! 3. Bob polls for Alice's offer at the same key //! 4. Bob stores his answer at SHA-256(signaling_key || bob_pk || "answer") //! 5. Alice polls for Bob's answer at the same key //! 6. ICE candidates exchanged similarly with versioned keys const std = @import("std"); const platform_time = @import("time.zig"); const Allocator = std.mem.Allocator; const signaling = @import("webrtc_signaling.zig"); pub const SignalingMessage = signaling.SignalingMessage; pub const MessageType = signaling.MessageType; pub const computeSignalingKey = signaling.computeSignalingKey; /// DHT interface — caller provides store/find functions. /// Avoids circular dependency with the p2p module. pub const DHTOps = struct { context: *anyopaque, storeFn: *const fn (ctx: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void, findFn: *const fn (ctx: *anyopaque, key: [32]u8) anyerror!?[]u8, }; /// Default TTL for signaling messages (60 seconds — connection should complete faster). pub const DEFAULT_SIGNALING_TTL: u32 = 60; /// Default timeout for waiting for a signaling response (30 seconds). pub const DEFAULT_WAIT_TIMEOUT_MS: u64 = 30_000; /// Default poll interval when waiting for signaling messages. pub const DEFAULT_POLL_INTERVAL_MS: u64 = 200; /// Derive a directional signaling DHT key for a specific message type. /// key = SHA-256(signaling_key || publisher_pubkey || label) /// This ensures the offerer and answerer store at different keys. pub fn deriveSignalingSubkey(signaling_key: [32]u8, publisher_pubkey: [32]u8, label: []const u8) [32]u8 { var hasher = std.crypto.hash.sha2.Sha256.init(.{}); hasher.update(&signaling_key); hasher.update(&publisher_pubkey); hasher.update(label); return hasher.finalResult(); } /// Derive a versioned ICE candidate DHT key from a base ICE key + version number. pub fn deriveIceVersionKey(base_ice_key: [32]u8, version: u32) [32]u8 { var hasher = std.crypto.hash.sha2.Sha256.init(.{}); hasher.update(&base_ice_key); var version_bytes: [4]u8 = undefined; std.mem.writeInt(u32, &version_bytes, version, .little); hasher.update(&version_bytes); return hasher.finalResult(); } /// WebRTC DHT Signaling session — manages SDP/ICE exchange for one connection. pub const SignalingSession = struct { allocator: Allocator, dht: DHTOps, our_pubkey: [32]u8, their_pubkey: [32]u8, /// Pre-computed base signaling key (order-independent). signaling_key: [32]u8, /// TTL for DHT store operations. ttl: u32, /// Next version to store when using trickle ICE (storeCandidateBatch). ice_send_version: u32 = 0, /// Next version to read when using trickle ICE (findNextCandidateBatch). ice_recv_version: u32 = 0, pub fn init( allocator: Allocator, dht: DHTOps, our_pubkey: [32]u8, their_pubkey: [32]u8, ) SignalingSession { return .{ .allocator = allocator, .dht = dht, .our_pubkey = our_pubkey, .their_pubkey = their_pubkey, .signaling_key = computeSignalingKey(our_pubkey, their_pubkey), .ttl = DEFAULT_SIGNALING_TTL, }; } // ========================================================================= // Store operations (publish our signaling data) // ========================================================================= /// Store our SDP offer in the DHT. pub fn storeOffer(self: *SignalingSession, sdp_payload: []const u8) !void { const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "offer"); const msg = SignalingMessage{ .msg_type = .offer, .from_pubkey = self.our_pubkey, .timestamp_ms = platform_time.milliTimestamp(), .payload = sdp_payload, .signature = [_]u8{0} ** 64, // TODO: sign with Ed25519 }; const wire = try msg.serialize(self.allocator); defer self.allocator.free(wire); try self.dht.storeFn(self.dht.context, key, wire, self.ttl); } /// Store our SDP answer in the DHT. pub fn storeAnswer(self: *SignalingSession, sdp_payload: []const u8) !void { const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "answer"); const msg = SignalingMessage{ .msg_type = .answer, .from_pubkey = self.our_pubkey, .timestamp_ms = platform_time.milliTimestamp(), .payload = sdp_payload, .signature = [_]u8{0} ** 64, // TODO: sign with Ed25519 }; const wire = try msg.serialize(self.allocator); defer self.allocator.free(wire); try self.dht.storeFn(self.dht.context, key, wire, self.ttl); } /// Store our ICE candidates in the DHT (batched as one message). pub fn storeCandidates(self: *SignalingSession, candidates_payload: []const u8) !void { const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "ice"); const msg = SignalingMessage{ .msg_type = .ice_candidate, .from_pubkey = self.our_pubkey, .timestamp_ms = platform_time.milliTimestamp(), .payload = candidates_payload, .signature = [_]u8{0} ** 64, }; const wire = try msg.serialize(self.allocator); defer self.allocator.free(wire); try self.dht.storeFn(self.dht.context, key, wire, self.ttl); } /// Store a batch of ICE candidates at a versioned key (trickle ICE). /// Each call increments the version, so candidates are stored at /// ice-0, ice-1, etc. The peer reads them in order via findNextCandidateBatch. pub fn storeCandidateBatch(self: *SignalingSession, candidates_payload: []const u8) !void { const base_key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "ice"); const versioned_key = deriveIceVersionKey(base_key, self.ice_send_version); const msg = SignalingMessage{ .msg_type = .ice_candidate, .from_pubkey = self.our_pubkey, .timestamp_ms = platform_time.milliTimestamp(), .payload = candidates_payload, .signature = [_]u8{0} ** 64, }; const wire = try msg.serialize(self.allocator); defer self.allocator.free(wire); try self.dht.storeFn(self.dht.context, versioned_key, wire, self.ttl); self.ice_send_version += 1; } // ========================================================================= // Find operations (retrieve peer's signaling data) // ========================================================================= /// Find the peer's SDP offer in the DHT (non-blocking). /// Returns the deserialized SignalingMessage or null if not found. /// Caller does NOT own the payload — it borrows from the returned wire data. pub fn findOffer(self: *SignalingSession) !?SignalingMessage { const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "offer"); return self.findMessage(key); } /// Find the peer's SDP answer in the DHT (non-blocking). pub fn findAnswer(self: *SignalingSession) !?SignalingMessage { const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "answer"); return self.findMessage(key); } /// Find the peer's ICE candidates in the DHT (non-blocking). pub fn findCandidates(self: *SignalingSession) !?SignalingMessage { const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice"); return self.findMessage(key); } /// Find the next batch of trickle ICE candidates from the peer (non-blocking). /// Returns the next unseen batch, or null if no new batch is available. /// Automatically advances the receive version on success. pub fn findNextCandidateBatch(self: *SignalingSession) !?SignalingMessage { const base_key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice"); const versioned_key = deriveIceVersionKey(base_key, self.ice_recv_version); const result = try self.findMessage(versioned_key); if (result != null) { self.ice_recv_version += 1; } return result; } /// Drain all available trickle ICE candidate batches from the peer (non-blocking). /// Returns all unseen batches as a slice. Caller owns the returned slice. /// Advances the receive version past all returned batches. pub fn drainCandidateBatches(self: *SignalingSession) ![]SignalingMessage { var batches: std.ArrayList(SignalingMessage) = .{}; errdefer batches.deinit(self.allocator); while (try self.findNextCandidateBatch()) |msg| { try batches.append(self.allocator, msg); } return batches.toOwnedSlice(self.allocator); } fn findMessage(self: *SignalingSession, key: [32]u8) !?SignalingMessage { const value = self.dht.findFn(self.dht.context, key) catch return null; if (value) |v| { defer self.allocator.free(v); return SignalingMessage.deserialize(v) catch null; } return null; } // ========================================================================= // Blocking wait operations (poll-based) // ========================================================================= /// Wait for the peer's SDP offer (blocking with timeout). /// Polls the DHT at regular intervals. MUST call p2p.update() externally /// if the DHT requires it for network I/O. pub fn waitForOffer(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "offer"); return self.waitForMessage(key, timeout_ms); } /// Wait for the peer's SDP answer (blocking with timeout). pub fn waitForAnswer(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "answer"); return self.waitForMessage(key, timeout_ms); } /// Wait for the peer's ICE candidates (blocking with timeout). pub fn waitForCandidates(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice"); return self.waitForMessage(key, timeout_ms); } /// Wait for the next trickle ICE candidate batch (blocking with timeout). /// Returns the next unseen batch, or null on timeout. pub fn waitForNextCandidateBatch(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { var elapsed: u64 = 0; while (elapsed < timeout_ms) { if (try self.findNextCandidateBatch()) |msg| { return msg; } platform_time.sleep(DEFAULT_POLL_INTERVAL_MS * std.time.ns_per_ms); elapsed += DEFAULT_POLL_INTERVAL_MS; } return null; } fn waitForMessage(self: *SignalingSession, key: [32]u8, timeout_ms: u64) !?SignalingMessage { var elapsed: u64 = 0; while (elapsed < timeout_ms) { if (try self.findMessage(key)) |msg| { return msg; } platform_time.sleep(DEFAULT_POLL_INTERVAL_MS * std.time.ns_per_ms); elapsed += DEFAULT_POLL_INTERVAL_MS; } return null; } }; // ============================================================================ // Tests // ============================================================================ test "deriveSignalingSubkey: different labels produce different keys" { const base = [_]u8{0xAA} ** 32; const pubkey = [_]u8{0xBB} ** 32; const offer_key = deriveSignalingSubkey(base, pubkey, "offer"); const answer_key = deriveSignalingSubkey(base, pubkey, "answer"); const ice_key = deriveSignalingSubkey(base, pubkey, "ice"); try std.testing.expect(!std.mem.eql(u8, &offer_key, &answer_key)); try std.testing.expect(!std.mem.eql(u8, &offer_key, &ice_key)); try std.testing.expect(!std.mem.eql(u8, &answer_key, &ice_key)); } test "deriveSignalingSubkey: different pubkeys produce different keys" { const base = [_]u8{0xAA} ** 32; const alice_pk = [_]u8{0x01} ** 32; const bob_pk = [_]u8{0x02} ** 32; const alice_offer = deriveSignalingSubkey(base, alice_pk, "offer"); const bob_offer = deriveSignalingSubkey(base, bob_pk, "offer"); try std.testing.expect(!std.mem.eql(u8, &alice_offer, &bob_offer)); } test "SignalingSession: store and find with mock DHT" { const allocator = std.testing.allocator; // Simple in-memory DHT mock const MockDHT = struct { store: std.AutoHashMap([32]u8, []u8), allocator: Allocator, fn init(alloc: Allocator) @This() { return .{ .store = std.AutoHashMap([32]u8, []u8).init(alloc), .allocator = alloc, }; } fn deinit(self: *@This()) void { var iter = self.store.valueIterator(); while (iter.next()) |v| { self.allocator.free(v.*); } self.store.deinit(); } fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { const self: *@This() = @ptrCast(@alignCast(ctx)); // Replace existing value if any if (self.store.fetchRemove(key)) |kv| { self.allocator.free(kv.value); } const copy = try self.allocator.dupe(u8, value); try self.store.put(key, copy); } fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.get(key)) |v| { return try self.allocator.dupe(u8, v); } return null; } fn ops(self: *@This()) DHTOps { return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn, }; } }; var mock = MockDHT.init(allocator); defer mock.deinit(); const alice_pk = [_]u8{0x01} ** 32; const bob_pk = [_]u8{0x02} ** 32; // Alice's session var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); // Bob's session var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); // Verify both compute the same signaling key try std.testing.expectEqualSlices(u8, &alice.signaling_key, &bob.signaling_key); // Alice stores her offer try alice.storeOffer("v=0\r\no=alice SDP"); // Bob finds Alice's offer const offer = try bob.findOffer(); try std.testing.expect(offer != null); try std.testing.expectEqual(MessageType.offer, offer.?.msg_type); try std.testing.expectEqualSlices(u8, &alice_pk, &offer.?.from_pubkey); // Bob stores his answer try bob.storeAnswer("v=0\r\no=bob SDP answer"); // Alice finds Bob's answer const answer = try alice.findAnswer(); try std.testing.expect(answer != null); try std.testing.expectEqual(MessageType.answer, answer.?.msg_type); try std.testing.expectEqualSlices(u8, &bob_pk, &answer.?.from_pubkey); // Alice stores her ICE candidates try alice.storeCandidates("candidate:1 1 UDP 2130706431 127.0.0.1 12345 typ host"); // Bob finds Alice's candidates const ice = try bob.findCandidates(); try std.testing.expect(ice != null); try std.testing.expectEqual(MessageType.ice_candidate, ice.?.msg_type); // Verify Alice can't find an offer from Bob (Bob never stored one) const wrong = try alice.findOffer(); // alice.findOffer() looks for bob's offer, but Bob only stored an answer try std.testing.expect(wrong == null); } test "SignalingSession: findOffer returns null when DHT empty" { const allocator = std.testing.allocator; const EmptyDHT = struct { fn storeFn(_: *anyopaque, _: [32]u8, _: []const u8, _: u32) anyerror!void {} fn findFn(_: *anyopaque, _: [32]u8) anyerror!?[]u8 { return null; } }; var dummy: u8 = 0; var session = SignalingSession.init(allocator, .{ .context = @ptrCast(&dummy), .storeFn = EmptyDHT.storeFn, .findFn = EmptyDHT.findFn, }, [_]u8{0x01} ** 32, [_]u8{0x02} ** 32); const result = try session.findOffer(); try std.testing.expect(result == null); } test "deriveIceVersionKey: different versions produce different keys" { const base = [_]u8{0xCC} ** 32; const key0 = deriveIceVersionKey(base, 0); const key1 = deriveIceVersionKey(base, 1); const key2 = deriveIceVersionKey(base, 2); try std.testing.expect(!std.mem.eql(u8, &key0, &key1)); try std.testing.expect(!std.mem.eql(u8, &key0, &key2)); try std.testing.expect(!std.mem.eql(u8, &key1, &key2)); } test "trickle ICE: store and find versioned candidate batches" { const allocator = std.testing.allocator; const MockDHT = struct { store: std.AutoHashMap([32]u8, []u8), alloc: Allocator, fn init(alloc: Allocator) @This() { return .{ .store = std.AutoHashMap([32]u8, []u8).init(alloc), .alloc = alloc, }; } fn deinit(self: *@This()) void { var iter = self.store.valueIterator(); while (iter.next()) |v| self.alloc.free(v.*); self.store.deinit(); } fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value); const copy = try self.alloc.dupe(u8, value); try self.store.put(key, copy); } fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v); return null; } fn ops(self: *@This()) DHTOps { return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn }; } }; var mock = MockDHT.init(allocator); defer mock.deinit(); const alice_pk = [_]u8{0x01} ** 32; const bob_pk = [_]u8{0x02} ** 32; var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); // Alice stores 3 batches of trickle ICE candidates try alice.storeCandidateBatch("candidate:1 1 UDP 2130706431 192.168.1.1 10000 typ host"); try alice.storeCandidateBatch("candidate:2 1 UDP 1694498815 10.0.0.1 10001 typ srflx"); try alice.storeCandidateBatch("candidate:3 1 UDP 16777215 1.2.3.4 10002 typ relay"); // Verify Alice's send version advanced try std.testing.expectEqual(@as(u32, 3), alice.ice_send_version); // Bob hasn't read any yet try std.testing.expectEqual(@as(u32, 0), bob.ice_recv_version); // Bob reads batch 0 const batch0 = try bob.findNextCandidateBatch(); try std.testing.expect(batch0 != null); try std.testing.expectEqual(MessageType.ice_candidate, batch0.?.msg_type); try std.testing.expectEqual(@as(u32, 1), bob.ice_recv_version); // Bob reads batch 1 const batch1 = try bob.findNextCandidateBatch(); try std.testing.expect(batch1 != null); try std.testing.expectEqual(@as(u32, 2), bob.ice_recv_version); // Bob reads batch 2 const batch2 = try bob.findNextCandidateBatch(); try std.testing.expect(batch2 != null); try std.testing.expectEqual(@as(u32, 3), bob.ice_recv_version); // No more batches const batch3 = try bob.findNextCandidateBatch(); try std.testing.expect(batch3 == null); // Version should NOT advance on null try std.testing.expectEqual(@as(u32, 3), bob.ice_recv_version); } test "trickle ICE: drainCandidateBatches returns all unseen" { const allocator = std.testing.allocator; const MockDHT = struct { store: std.AutoHashMap([32]u8, []u8), alloc: Allocator, fn init(alloc: Allocator) @This() { return .{ .store = std.AutoHashMap([32]u8, []u8).init(alloc), .alloc = alloc, }; } fn deinit(self: *@This()) void { var iter = self.store.valueIterator(); while (iter.next()) |v| self.alloc.free(v.*); self.store.deinit(); } fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value); const copy = try self.alloc.dupe(u8, value); try self.store.put(key, copy); } fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v); return null; } fn ops(self: *@This()) DHTOps { return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn }; } }; var mock = MockDHT.init(allocator); defer mock.deinit(); const alice_pk = [_]u8{0x01} ** 32; const bob_pk = [_]u8{0x02} ** 32; var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); // Alice stores 4 batches try alice.storeCandidateBatch("candidate:host"); try alice.storeCandidateBatch("candidate:srflx"); try alice.storeCandidateBatch("candidate:relay"); try alice.storeCandidateBatch("candidate:prflx"); // Bob drains all at once const batches = try bob.drainCandidateBatches(); defer allocator.free(batches); try std.testing.expectEqual(@as(usize, 4), batches.len); try std.testing.expectEqual(@as(u32, 4), bob.ice_recv_version); // Drain again — should be empty const empty = try bob.drainCandidateBatches(); defer allocator.free(empty); try std.testing.expectEqual(@as(usize, 0), empty.len); } test "trickle ICE: bidirectional exchange" { const allocator = std.testing.allocator; const MockDHT = struct { store: std.AutoHashMap([32]u8, []u8), alloc: Allocator, fn init(alloc: Allocator) @This() { return .{ .store = std.AutoHashMap([32]u8, []u8).init(alloc), .alloc = alloc, }; } fn deinit(self: *@This()) void { var iter = self.store.valueIterator(); while (iter.next()) |v| self.alloc.free(v.*); self.store.deinit(); } fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value); const copy = try self.alloc.dupe(u8, value); try self.store.put(key, copy); } fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { const self: *@This() = @ptrCast(@alignCast(ctx)); if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v); return null; } fn ops(self: *@This()) DHTOps { return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn }; } }; var mock = MockDHT.init(allocator); defer mock.deinit(); const alice_pk = [_]u8{0x01} ** 32; const bob_pk = [_]u8{0x02} ** 32; var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); // Both sides trickle candidates independently try alice.storeCandidateBatch("alice-candidate:host"); try bob.storeCandidateBatch("bob-candidate:host"); try alice.storeCandidateBatch("alice-candidate:srflx"); try bob.storeCandidateBatch("bob-candidate:srflx"); // Alice reads Bob's candidates const alice_batches = try alice.drainCandidateBatches(); defer allocator.free(alice_batches); try std.testing.expectEqual(@as(usize, 2), alice_batches.len); // Verify they came from Bob for (alice_batches) |batch| { try std.testing.expectEqualSlices(u8, &bob_pk, &batch.from_pubkey); } // Bob reads Alice's candidates const bob_batches = try bob.drainCandidateBatches(); defer allocator.free(bob_batches); try std.testing.expectEqual(@as(usize, 2), bob_batches.len); // Verify they came from Alice for (bob_batches) |batch| { try std.testing.expectEqualSlices(u8, &alice_pk, &batch.from_pubkey); } // Both versions advanced independently try std.testing.expectEqual(@as(u32, 2), alice.ice_send_version); try std.testing.expectEqual(@as(u32, 2), alice.ice_recv_version); try std.testing.expectEqual(@as(u32, 2), bob.ice_send_version); try std.testing.expectEqual(@as(u32, 2), bob.ice_recv_version); }