//! Mutual Witness Protocol — Standalone Core //! //! This is the testable standalone implementation of MWP, using a `DHTInterface` //! abstraction so it can run with `MockDHT` in unit tests. For the production //! API wired to `*P2P`, see `src/mwp_integration.zig`. //! //! A novel NAT traversal and peer discovery protocol that requires //! zero external infrastructure beyond a DHT. //! //! ## Overview //! //! The Mutual Witness Protocol (MWP) enables two peers to establish a direct //! P2P connection when they know each other's public keys, using only a DHT //! for coordination. //! //! ## Key Features //! //! - No STUN servers required //! - No relay/signaling servers required //! - No beacon chain or external timing source //! - Only requires DHT (already present in most P2P networks) //! //! ## How It Works //! //! 1. Both peers compute the same deterministic "meeting key" from their public keys //! 2. Both publish their connection info to the DHT at this key //! 3. Each peer discovers the other's publication //! 4. Both compute identical rendezvous parameters from their combined data //! 5. Both attempt simultaneous connection at the computed time //! //! ## Example //! //! ```zig //! const mwp = @import("mwp"); //! //! // Initialize //! var witness = mwp.MutualWitness.init(allocator, dht, keypair, our_addresses); //! //! // Connect to a peer by their public key //! const result = witness.connect(target_pubkey, .{}); //! //! switch (result) { //! .success => |info| { //! std.debug.print("Connected to {x} at {}:{}\n", .{ //! info.peer_id, //! info.remote_address.ip.v4, //! info.remote_address.port, //! }); //! }, //! .peer_not_found => std.debug.print("Peer not found\n", .{}), //! .timeout => std.debug.print("Timeout\n", .{}), //! else => std.debug.print("Connection failed\n", .{}), //! } //! ``` const std = @import("std"); const Allocator = std.mem.Allocator; pub const types = @import("types.zig"); pub const meeting_point = @import("meeting_point.zig"); pub const hole_punch = @import("hole_punch.zig"); // Re-export common types pub const Address = types.Address; pub const MeetingPublication = types.MeetingPublication; pub const RendezvousParams = types.RendezvousParams; pub const HolePunchPacket = types.HolePunchPacket; pub const ConnectionResult = types.ConnectionResult; pub const ConnectionInfo = types.ConnectionInfo; pub const ConnectOptions = types.ConnectOptions; pub const Stats = types.Stats; pub const Defaults = types.Defaults; pub const MeetingPoint = meeting_point.MeetingPoint; pub const DHTInterface = meeting_point.DHTInterface; pub const HolePunchEngine = hole_punch.HolePunchEngine; pub const HolePunchListener = hole_punch.HolePunchListener; /// Ed25519 key pair for identity and signing pub const KeyPair = struct { public: [32]u8, secret: [64]u8, /// Generate a new random key pair pub fn generate() KeyPair { const kp = std.crypto.sign.Ed25519.KeyPair.generate(); return .{ .public = kp.public_key.toBytes(), .secret = kp.secret_key.toBytes(), }; } /// Create from existing secret key bytes pub fn fromSecretKey(secret: [64]u8) error{InvalidKeyData}!KeyPair { const sk = std.crypto.sign.Ed25519.SecretKey.fromBytes(secret) catch return error.InvalidKeyData; const kp = std.crypto.sign.Ed25519.KeyPair.fromSecretKey(sk) catch return error.InvalidKeyData; return .{ .public = kp.public_key.toBytes(), .secret = secret, }; } /// Sign a 32-byte hash pub fn sign(self: KeyPair, hash: [32]u8) error{InvalidKeyData}![64]u8 { const sk = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch return error.InvalidKeyData; const pk = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch return error.InvalidKeyData; const kp = std.crypto.sign.Ed25519.KeyPair{ .secret_key = sk, .public_key = pk, }; const sig = std.crypto.sign.Ed25519.KeyPair.sign(kp, &hash, null) catch return error.InvalidKeyData; return sig.toBytes(); } }; /// Main Mutual Witness Protocol handler pub const MutualWitness = struct { allocator: Allocator, meeting: MeetingPoint, hole_punch_engine: HolePunchEngine, keypair: KeyPair, our_addresses: []const Address, stats: Stats, /// Initialize the Mutual Witness Protocol handler pub fn init( allocator: Allocator, dht: DHTInterface, keypair: KeyPair, addresses: []const Address, ) MutualWitness { const mp_keypair = MeetingPoint.KeyPair{ .public = keypair.public, .secret = keypair.secret, }; const hp_keypair = HolePunchEngine.KeyPair{ .public = keypair.public, .secret = keypair.secret, }; return .{ .allocator = allocator, .meeting = MeetingPoint.init(allocator, dht, mp_keypair, addresses), .hole_punch_engine = HolePunchEngine.init(allocator, hp_keypair), .keypair = keypair, .our_addresses = addresses, .stats = .{}, }; } /// Connect to a peer by their public key /// /// This is the main entry point for establishing connections via MWP. /// The function will: /// 1. Publish our connection info to the DHT meeting point /// 2. Wait for the peer's publication /// 3. Compute shared rendezvous parameters /// 4. Attempt simultaneous hole punch /// /// Returns a ConnectionResult indicating success or failure. pub fn connect( self: *MutualWitness, target_pubkey: [32]u8, options: ConnectOptions, ) ConnectionResult { self.stats.attempts += 1; // Step 1: Publish our meeting info const our_publication = self.meeting.publish( target_pubkey, options.publication_ttl, ) catch |err| { return .{ .other_error = err }; }; self.stats.publications_created += 1; // Step 2: Wait for peer's publication const peer_result = self.meeting.waitForPeer( target_pubkey, options.timeout_ms, ) catch |err| { return switch (err) { error.Timeout => .timeout, else => .{ .other_error = err }, }; }; self.stats.publications_received += 1; defer { var pub_copy = peer_result.publication; pub_copy.deinit(self.allocator); } // Step 3: Compute rendezvous parameters const params = meeting_point.computeRendezvousParams( our_publication, peer_result.publication, peer_result.seen_time, options.rendezvous_buffer_ms, ); // Step 4: Attempt connection const result = self.hole_punch_engine.attemptConnection( peer_result.publication.addresses, params, options, ); // Update stats switch (result) { .success => self.stats.successes += 1, else => self.stats.failures += 1, } return result; } /// Check if a peer is available at the meeting point (non-blocking) pub fn findPeer(self: *MutualWitness, target_pubkey: [32]u8) !?MeetingPublication { return self.meeting.findPeer(target_pubkey); } /// Publish availability for a specific peer to find us pub fn publishFor(self: *MutualWitness, target_pubkey: [32]u8, ttl: u32) !MeetingPublication { const pub_data = try self.meeting.publish(target_pubkey, ttl); self.stats.publications_created += 1; return pub_data; } /// Update our addresses (e.g., after NAT remapping) pub fn updateAddresses(self: *MutualWitness, new_addresses: []const Address) void { self.our_addresses = new_addresses; self.meeting.updateAddresses(new_addresses); } /// Get our public key pub fn getPublicKey(self: *MutualWitness) [32]u8 { return self.keypair.public; } /// Get statistics pub fn getStats(self: *MutualWitness) Stats { return self.stats; } /// Reset statistics pub fn resetStats(self: *MutualWitness) void { self.stats = .{}; self.hole_punch_engine.resetStats(); } /// Compute meeting key for a peer (useful for debugging) pub fn computeMeetingKey(self: *MutualWitness, target_pubkey: [32]u8) [32]u8 { return MeetingPoint.computeMeetingKey(self.keypair.public, target_pubkey); } }; /// Helper to create a mock DHT for testing pub const MockDHT = struct { allocator: Allocator, storage: std.AutoHashMap([32]u8, std.ArrayList([]u8)), pub fn init(allocator: Allocator) MockDHT { return .{ .allocator = allocator, .storage = std.AutoHashMap([32]u8, std.ArrayList([]u8)).init(allocator), }; } pub fn deinit(self: *MockDHT) void { var it = self.storage.valueIterator(); while (it.next()) |list| { for (list.items) |item| { self.allocator.free(item); } var list_copy = list.*; list_copy.deinit(self.allocator); } self.storage.deinit(); } pub fn put(ptr: *anyopaque, key: [32]u8, value: []const u8) !void { const self: *MockDHT = @ptrCast(@alignCast(ptr)); const entry = self.storage.getOrPut(key) catch return error.OutOfMemory; if (!entry.found_existing) { entry.value_ptr.* = .{}; } const copy = self.allocator.dupe(u8, value) catch return error.OutOfMemory; entry.value_ptr.append(self.allocator, copy) catch { self.allocator.free(copy); return error.OutOfMemory; }; } pub fn getAll(ptr: *anyopaque, key: [32]u8, allocator: Allocator) ![][]u8 { const self: *MockDHT = @ptrCast(@alignCast(ptr)); const list = self.storage.get(key) orelse return &[_][]u8{}; var result = try allocator.alloc([]u8, list.items.len); for (list.items, 0..) |item, i| { result[i] = try allocator.dupe(u8, item); } return result; } pub fn interface(self: *MockDHT) DHTInterface { return .{ .ptr = self, .vtable = &.{ .put = put, .getAll = getAll, .subscribe = null, }, }; } }; // Tests test "MutualWitness basic flow" { const allocator = std.testing.allocator; // Create mock DHT var dht = MockDHT.init(allocator); defer dht.deinit(); // Create two peers const alice_keypair = KeyPair.generate(); const bob_keypair = KeyPair.generate(); const alice_addr = Address.initV4(.{ 192, 168, 1, 1 }, 9000); const bob_addr = Address.initV4(.{ 192, 168, 1, 2 }, 9001); var alice = MutualWitness.init( allocator, dht.interface(), alice_keypair, &[_]Address{alice_addr}, ); var bob = MutualWitness.init( allocator, dht.interface(), bob_keypair, &[_]Address{bob_addr}, ); // Both compute same meeting key const alice_key = alice.computeMeetingKey(bob_keypair.public); const bob_key = bob.computeMeetingKey(alice_keypair.public); try std.testing.expect(std.mem.eql(u8, &alice_key, &bob_key)); // Alice publishes for Bob const alice_pub = try alice.publishFor(bob_keypair.public, 300); try std.testing.expect(alice_pub.verify()); // Bob can find Alice const found = try bob.findPeer(alice_keypair.public); try std.testing.expect(found != null); if (found) |f| { try std.testing.expect(std.mem.eql(u8, &f.peer_id, &alice_keypair.public)); var f_copy = f; f_copy.deinit(allocator); } } test "Meeting key is symmetric" { const alice = [_]u8{1} ** 32; const bob = [_]u8{2} ** 32; const key1 = MeetingPoint.computeMeetingKey(alice, bob); const key2 = MeetingPoint.computeMeetingKey(bob, alice); try std.testing.expect(std.mem.eql(u8, &key1, &key2)); } test "Publication signature verification" { const allocator = std.testing.allocator; var dht = MockDHT.init(allocator); defer dht.deinit(); const keypair = KeyPair.generate(); const addr = Address.initV4(.{ 127, 0, 0, 1 }, 8080); var witness = MutualWitness.init( allocator, dht.interface(), keypair, &[_]Address{addr}, ); const target = [_]u8{0xAB} ** 32; const pub_data = try witness.publishFor(target, 300); // Verify signature try std.testing.expect(pub_data.verify()); // Tamper with data - signature should fail var tampered = pub_data; tampered.timestamp += 1; try std.testing.expect(!tampered.verify()); } test "Rendezvous params are deterministic" { // Two publications const nonce_a = [_]u8{1} ** 32; const nonce_b = [_]u8{2} ** 32; const pub_a = MeetingPublication{ .peer_id = [_]u8{0xAA} ** 32, .addresses = &[_]Address{}, .nonce = nonce_a, .timestamp = 1000, .ttl = 300, .sequence = 1, .signature = [_]u8{0} ** 64, }; const pub_b = MeetingPublication{ .peer_id = [_]u8{0xBB} ** 32, .addresses = &[_]Address{}, .nonce = nonce_b, .timestamp = 1050, .ttl = 300, .sequence = 1, .signature = [_]u8{0} ** 64, }; // Both peers compute params (with same seen_time for test) const params_a = meeting_point.computeRendezvousParams(pub_a, pub_b, 1100, 500); const params_b = meeting_point.computeRendezvousParams(pub_b, pub_a, 1100, 500); // Should produce identical shared randomness try std.testing.expect(std.mem.eql(u8, ¶ms_a.shared_randomness, ¶ms_b.shared_randomness)); // Should produce identical port hints try std.testing.expectEqual(params_a.port_hint, params_b.port_hint); // Should produce identical connection IDs try std.testing.expect(std.mem.eql(u8, ¶ms_a.connection_id, ¶ms_b.connection_id)); }