create Mutual Witness Protocol specs and implementation. mwp aims to be
a zero-infrastructure NAT traversal
This commit is contained in:
484
src/mwp/hole_punch.zig
Normal file
484
src/mwp/hole_punch.zig
Normal file
@@ -0,0 +1,484 @@
|
||||
//! Mutual Witness Protocol - Hole Punch Engine
|
||||
//!
|
||||
//! Handles the actual NAT traversal via simultaneous connection attempts.
|
||||
|
||||
const std = @import("std");
|
||||
const types = @import("types.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const os = std.os;
|
||||
|
||||
const Address = types.Address;
|
||||
const HolePunchPacket = types.HolePunchPacket;
|
||||
const RendezvousParams = types.RendezvousParams;
|
||||
const ConnectionResult = types.ConnectionResult;
|
||||
const ConnectionInfo = types.ConnectionInfo;
|
||||
const HolePunchError = types.HolePunchError;
|
||||
const Defaults = types.Defaults;
|
||||
|
||||
/// Socket wrapper for cross-platform UDP
|
||||
pub const UdpSocket = struct {
|
||||
fd: std.posix.socket_t,
|
||||
bound_address: ?Address,
|
||||
|
||||
pub fn init() !UdpSocket {
|
||||
const fd = try std.posix.socket(
|
||||
std.posix.AF.INET,
|
||||
std.posix.SOCK.DGRAM,
|
||||
0,
|
||||
);
|
||||
|
||||
// Set non-blocking (platform-independent approach)
|
||||
const flags = try std.posix.fcntl(fd, std.posix.F.GETFL, 0);
|
||||
const nonblock_bit = 1 << @bitOffsetOf(std.posix.O, "NONBLOCK");
|
||||
_ = try std.posix.fcntl(fd, std.posix.F.SETFL, flags | nonblock_bit);
|
||||
|
||||
// Allow address reuse
|
||||
try std.posix.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
|
||||
|
||||
return .{
|
||||
.fd = fd,
|
||||
.bound_address = null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *UdpSocket) void {
|
||||
std.posix.close(self.fd);
|
||||
}
|
||||
|
||||
pub fn bind(self: *UdpSocket, port: u16) !void {
|
||||
const addr = std.net.Address.initIp4(.{ 0, 0, 0, 0 }, port);
|
||||
try std.posix.bind(self.fd, &addr.any, addr.getOsSockLen());
|
||||
self.bound_address = Address.initV4(.{ 0, 0, 0, 0 }, port);
|
||||
}
|
||||
|
||||
pub fn sendTo(self: *UdpSocket, addr: Address, data: []const u8) !void {
|
||||
const sock_addr = addressToSockaddr(addr);
|
||||
_ = try std.posix.sendto(
|
||||
self.fd,
|
||||
data,
|
||||
0,
|
||||
&sock_addr.any,
|
||||
sock_addr.getOsSockLen(),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn recvFrom(self: *UdpSocket, buf: []u8) !struct { len: usize, addr: Address } {
|
||||
var src_addr: std.posix.sockaddr.storage = undefined;
|
||||
var addr_len: std.posix.socklen_t = @sizeOf(@TypeOf(src_addr));
|
||||
|
||||
const len = std.posix.recvfrom(
|
||||
self.fd,
|
||||
buf,
|
||||
0,
|
||||
@ptrCast(&src_addr),
|
||||
&addr_len,
|
||||
) catch |err| {
|
||||
if (err == error.WouldBlock) return error.WouldBlock;
|
||||
return err;
|
||||
};
|
||||
|
||||
const addr = sockaddrToAddress(&src_addr);
|
||||
return .{ .len = len, .addr = addr };
|
||||
}
|
||||
|
||||
fn addressToSockaddr(addr: Address) std.net.Address {
|
||||
return switch (addr.addr_type) {
|
||||
.ipv4 => std.net.Address.initIp4(addr.ip.v4, addr.port),
|
||||
.ipv6 => std.net.Address.initIp6(addr.ip.v6, addr.port, 0, 0),
|
||||
};
|
||||
}
|
||||
|
||||
fn sockaddrToAddress(sockaddr: *const std.posix.sockaddr.storage) Address {
|
||||
const family = sockaddr.family;
|
||||
if (family == std.posix.AF.INET) {
|
||||
const in_addr: *const std.posix.sockaddr.in = @ptrCast(sockaddr);
|
||||
const ip_bytes: [4]u8 = @bitCast(in_addr.addr);
|
||||
return Address.initV4(ip_bytes, std.mem.bigToNative(u16, in_addr.port));
|
||||
} else {
|
||||
const in6_addr: *const std.posix.sockaddr.in6 = @ptrCast(sockaddr);
|
||||
return Address.initV6(in6_addr.addr, std.mem.bigToNative(u16, in6_addr.port));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/// Hole punch engine
|
||||
pub const HolePunchEngine = struct {
|
||||
allocator: Allocator,
|
||||
our_keypair: KeyPair,
|
||||
stats: types.Stats,
|
||||
|
||||
/// Ed25519 key pair
|
||||
pub const KeyPair = struct {
|
||||
public: [32]u8,
|
||||
secret: [64]u8,
|
||||
|
||||
pub fn sign(self: KeyPair, message: [32]u8) [64]u8 {
|
||||
const secret_key = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch unreachable;
|
||||
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch unreachable;
|
||||
const key_pair = std.crypto.sign.Ed25519.KeyPair{
|
||||
.secret_key = secret_key,
|
||||
.public_key = public_key,
|
||||
};
|
||||
const sig = std.crypto.sign.Ed25519.KeyPair.sign(key_pair, &message, null) catch unreachable;
|
||||
return sig.toBytes();
|
||||
}
|
||||
};
|
||||
|
||||
/// Connection attempt context
|
||||
const AttemptContext = struct {
|
||||
socket: UdpSocket,
|
||||
target_address: Address,
|
||||
using_port_hint: bool,
|
||||
};
|
||||
|
||||
/// Initialize hole punch engine
|
||||
pub fn init(allocator: Allocator, keypair: KeyPair) HolePunchEngine {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.our_keypair = keypair,
|
||||
.stats = .{},
|
||||
};
|
||||
}
|
||||
|
||||
/// Attempt connection to peer
|
||||
pub fn attemptConnection(
|
||||
self: *HolePunchEngine,
|
||||
target_addresses: []const Address,
|
||||
params: RendezvousParams,
|
||||
options: types.ConnectOptions,
|
||||
) ConnectionResult {
|
||||
self.stats.attempts += 1;
|
||||
const start_time = std.time.milliTimestamp();
|
||||
|
||||
// Wait until rendezvous time
|
||||
const now = std.time.milliTimestamp();
|
||||
if (params.rendezvous_time > now) {
|
||||
const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms;
|
||||
|
||||
if (options.send_keepalives) {
|
||||
self.waitWithKeepalives(target_addresses, wait_ns) catch {};
|
||||
} else {
|
||||
std.Thread.sleep(wait_ns);
|
||||
}
|
||||
}
|
||||
|
||||
// Try with retries
|
||||
for (Defaults.retry_intervals) |delay| {
|
||||
if (delay > 0) {
|
||||
std.Thread.sleep(delay * std.time.ns_per_ms);
|
||||
}
|
||||
|
||||
const result = self.singleAttempt(target_addresses, params, options);
|
||||
|
||||
switch (result) {
|
||||
.success => |info| {
|
||||
self.stats.successes += 1;
|
||||
const elapsed = @as(u64, @intCast(std.time.milliTimestamp() - start_time));
|
||||
self.updateAvgTime(elapsed);
|
||||
return .{ .success = info };
|
||||
},
|
||||
.hole_punch_failed => continue, // Retry
|
||||
else => return result,
|
||||
}
|
||||
}
|
||||
|
||||
self.stats.failures += 1;
|
||||
return .{ .hole_punch_failed = .all_addresses_failed };
|
||||
}
|
||||
|
||||
/// Single connection attempt (no retries)
|
||||
fn singleAttempt(
|
||||
self: *HolePunchEngine,
|
||||
target_addresses: []const Address,
|
||||
params: RendezvousParams,
|
||||
options: types.ConnectOptions,
|
||||
) ConnectionResult {
|
||||
var contexts: std.ArrayList(AttemptContext) = .{};
|
||||
defer {
|
||||
for (contexts.items) |*ctx| {
|
||||
ctx.socket.deinit();
|
||||
}
|
||||
contexts.deinit(self.allocator);
|
||||
}
|
||||
|
||||
// Create sockets for all target addresses
|
||||
for (target_addresses) |addr| {
|
||||
// Direct attempt
|
||||
var socket = UdpSocket.init() catch continue;
|
||||
contexts.append(self.allocator, .{
|
||||
.socket = socket,
|
||||
.target_address = addr,
|
||||
.using_port_hint = false,
|
||||
}) catch {
|
||||
socket.deinit();
|
||||
continue;
|
||||
};
|
||||
|
||||
// Port hint attempt (if enabled)
|
||||
if (options.use_port_hints) {
|
||||
var hint_socket = UdpSocket.init() catch continue;
|
||||
hint_socket.bind(params.port_hint) catch {
|
||||
hint_socket.deinit();
|
||||
continue;
|
||||
};
|
||||
|
||||
const hint_addr = Address.initV4(
|
||||
if (addr.addr_type == .ipv4) addr.ip.v4 else .{ 0, 0, 0, 0 },
|
||||
params.port_hint,
|
||||
);
|
||||
|
||||
contexts.append(self.allocator, .{
|
||||
.socket = hint_socket,
|
||||
.target_address = hint_addr,
|
||||
.using_port_hint = true,
|
||||
}) catch {
|
||||
hint_socket.deinit();
|
||||
continue;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (contexts.items.len == 0) {
|
||||
return .{ .hole_punch_failed = .all_addresses_failed };
|
||||
}
|
||||
|
||||
// Create and send hole punch packets
|
||||
const packet = self.createHolePunchPacket(params);
|
||||
const packet_bytes = packet.serialize();
|
||||
|
||||
for (contexts.items) |*ctx| {
|
||||
ctx.socket.sendTo(ctx.target_address, &packet_bytes) catch continue;
|
||||
self.stats.hole_punch_sent += 1;
|
||||
}
|
||||
|
||||
// Wait for responses
|
||||
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(Defaults.hole_punch_timeout_ms));
|
||||
var recv_buf: [256]u8 = undefined;
|
||||
|
||||
while (std.time.milliTimestamp() < deadline) {
|
||||
for (contexts.items) |*ctx| {
|
||||
const result = ctx.socket.recvFrom(&recv_buf) catch |err| {
|
||||
if (err == error.WouldBlock) continue;
|
||||
continue;
|
||||
};
|
||||
|
||||
self.stats.hole_punch_received += 1;
|
||||
|
||||
// Parse response
|
||||
const response = HolePunchPacket.deserialize(recv_buf[0..result.len]) catch continue;
|
||||
|
||||
// Verify connection ID matches
|
||||
if (!std.mem.eql(u8, &response.connection_id, ¶ms.connection_id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verify signature
|
||||
if (!response.verify()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Success!
|
||||
const elapsed = @as(u64, @intCast(std.time.milliTimestamp() -
|
||||
(params.rendezvous_time - Defaults.rendezvous_buffer_ms)));
|
||||
|
||||
return .{
|
||||
.success = .{
|
||||
.peer_id = response.sender_id,
|
||||
.remote_address = result.addr,
|
||||
.local_address = ctx.socket.bound_address orelse
|
||||
Address.initV4(.{ 0, 0, 0, 0 }, 0),
|
||||
.connection_id = params.connection_id,
|
||||
.establishment_time_ms = elapsed,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Small sleep to avoid busy loop
|
||||
std.Thread.sleep(1 * std.time.ns_per_ms);
|
||||
}
|
||||
|
||||
return .{ .hole_punch_failed = .timeout };
|
||||
}
|
||||
|
||||
/// Create a hole punch packet
|
||||
fn createHolePunchPacket(self: *HolePunchEngine, params: RendezvousParams) HolePunchPacket {
|
||||
var packet = HolePunchPacket{
|
||||
.connection_id = params.connection_id,
|
||||
.sender_id = self.our_keypair.public,
|
||||
.timestamp = std.time.milliTimestamp(),
|
||||
.signature = undefined,
|
||||
};
|
||||
|
||||
const hash = packet.computeHash();
|
||||
packet.signature = self.our_keypair.sign(hash);
|
||||
|
||||
return packet;
|
||||
}
|
||||
|
||||
/// Wait with periodic keepalive packets to maintain NAT mappings
|
||||
fn waitWithKeepalives(
|
||||
_: *HolePunchEngine,
|
||||
target_addresses: []const Address,
|
||||
total_wait_ns: u64,
|
||||
) !void {
|
||||
const interval_ns = Defaults.keepalive_interval_ms * std.time.ns_per_ms;
|
||||
var remaining = total_wait_ns;
|
||||
|
||||
var socket = try UdpSocket.init();
|
||||
defer socket.deinit();
|
||||
|
||||
// Simple keepalive packet (just magic + timestamp)
|
||||
var keepalive: [12]u8 = undefined;
|
||||
@memcpy(keepalive[0..4], "MWPK"); // Keepalive magic
|
||||
|
||||
while (remaining > 0) {
|
||||
const sleep_time = @min(remaining, interval_ns);
|
||||
std.Thread.sleep(sleep_time);
|
||||
remaining -= sleep_time;
|
||||
|
||||
if (remaining > 0) {
|
||||
// Send keepalive to all addresses
|
||||
std.mem.writeInt(i64, keepalive[4..12], std.time.milliTimestamp(), .big);
|
||||
for (target_addresses) |addr| {
|
||||
socket.sendTo(addr, &keepalive) catch continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Update rolling average connection time
|
||||
fn updateAvgTime(self: *HolePunchEngine, new_time: u64) void {
|
||||
if (self.stats.successes == 1) {
|
||||
self.stats.avg_connection_time_ms = new_time;
|
||||
} else {
|
||||
// Exponential moving average
|
||||
self.stats.avg_connection_time_ms =
|
||||
(self.stats.avg_connection_time_ms * 7 + new_time) / 8;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get current statistics
|
||||
pub fn getStats(self: *HolePunchEngine) types.Stats {
|
||||
return self.stats;
|
||||
}
|
||||
|
||||
/// Reset statistics
|
||||
pub fn resetStats(self: *HolePunchEngine) void {
|
||||
self.stats = .{};
|
||||
}
|
||||
};
|
||||
|
||||
/// Listen for incoming hole punch attempts
|
||||
pub const HolePunchListener = struct {
|
||||
allocator: Allocator,
|
||||
socket: UdpSocket,
|
||||
our_keypair: HolePunchEngine.KeyPair,
|
||||
expected_connection_id: ?[16]u8,
|
||||
|
||||
pub fn init(
|
||||
allocator: Allocator,
|
||||
keypair: HolePunchEngine.KeyPair,
|
||||
listen_port: u16,
|
||||
) !HolePunchListener {
|
||||
var socket = try UdpSocket.init();
|
||||
try socket.bind(listen_port);
|
||||
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.socket = socket,
|
||||
.our_keypair = keypair,
|
||||
.expected_connection_id = null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *HolePunchListener) void {
|
||||
self.socket.deinit();
|
||||
}
|
||||
|
||||
/// Set expected connection ID (from rendezvous params)
|
||||
pub fn expectConnection(self: *HolePunchListener, connection_id: [16]u8) void {
|
||||
self.expected_connection_id = connection_id;
|
||||
}
|
||||
|
||||
/// Wait for incoming hole punch
|
||||
pub fn waitForPunch(self: *HolePunchListener, timeout_ms: u64) !struct {
|
||||
packet: HolePunchPacket,
|
||||
from: Address,
|
||||
} {
|
||||
var buf: [256]u8 = undefined;
|
||||
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
|
||||
|
||||
while (std.time.milliTimestamp() < deadline) {
|
||||
const result = self.socket.recvFrom(&buf) catch |err| {
|
||||
if (err == error.WouldBlock) {
|
||||
std.Thread.sleep(1 * std.time.ns_per_ms);
|
||||
continue;
|
||||
}
|
||||
return err;
|
||||
};
|
||||
|
||||
const packet = HolePunchPacket.deserialize(buf[0..result.len]) catch continue;
|
||||
|
||||
// Check connection ID if we're expecting a specific one
|
||||
if (self.expected_connection_id) |expected| {
|
||||
if (!std.mem.eql(u8, &packet.connection_id, &expected)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Verify signature
|
||||
if (!packet.verify()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return .{ .packet = packet, .from = result.addr };
|
||||
}
|
||||
|
||||
return error.Timeout;
|
||||
}
|
||||
|
||||
/// Send response to hole punch
|
||||
pub fn sendResponse(
|
||||
self: *HolePunchListener,
|
||||
to: Address,
|
||||
connection_id: [16]u8,
|
||||
) !void {
|
||||
var packet = HolePunchPacket{
|
||||
.connection_id = connection_id,
|
||||
.sender_id = self.our_keypair.public,
|
||||
.timestamp = std.time.milliTimestamp(),
|
||||
.signature = undefined,
|
||||
};
|
||||
|
||||
const hash = packet.computeHash();
|
||||
packet.signature = self.our_keypair.sign(hash);
|
||||
|
||||
const bytes = packet.serialize();
|
||||
try self.socket.sendTo(to, &bytes);
|
||||
}
|
||||
};
|
||||
|
||||
// Tests
|
||||
test "HolePunchPacket roundtrip" {
|
||||
var packet = HolePunchPacket{
|
||||
.connection_id = [_]u8{0xAB} ** 16,
|
||||
.sender_id = [_]u8{0xCD} ** 32,
|
||||
.timestamp = 1234567890123,
|
||||
.signature = [_]u8{0xEF} ** 64,
|
||||
};
|
||||
|
||||
const serialized = packet.serialize();
|
||||
const deserialized = try HolePunchPacket.deserialize(&serialized);
|
||||
|
||||
try std.testing.expect(std.mem.eql(u8, &packet.connection_id, &deserialized.connection_id));
|
||||
try std.testing.expect(std.mem.eql(u8, &packet.sender_id, &deserialized.sender_id));
|
||||
try std.testing.expectEqual(packet.timestamp, deserialized.timestamp);
|
||||
}
|
||||
|
||||
test "UdpSocket creation" {
|
||||
var socket = try UdpSocket.init();
|
||||
defer socket.deinit();
|
||||
|
||||
try socket.bind(0); // Bind to any available port
|
||||
try std.testing.expect(socket.bound_address != null);
|
||||
}
|
||||
347
src/mwp/meeting_point.zig
Normal file
347
src/mwp/meeting_point.zig
Normal file
@@ -0,0 +1,347 @@
|
||||
//! Mutual Witness Protocol - Meeting Point Logic
|
||||
//!
|
||||
//! Handles the DHT-based meeting point where peers find each other.
|
||||
|
||||
const std = @import("std");
|
||||
const types = @import("types.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const MeetingPublication = types.MeetingPublication;
|
||||
const Address = types.Address;
|
||||
const Defaults = types.Defaults;
|
||||
|
||||
/// DHT interface that MWP requires
|
||||
pub const DHTInterface = struct {
|
||||
ptr: *anyopaque,
|
||||
vtable: *const VTable,
|
||||
|
||||
pub const VTable = struct {
|
||||
/// Store value at key
|
||||
put: *const fn (ptr: *anyopaque, key: [32]u8, value: []const u8) anyerror!void,
|
||||
|
||||
/// Get all values at key
|
||||
getAll: *const fn (ptr: *anyopaque, key: [32]u8, allocator: Allocator) anyerror![][]u8,
|
||||
|
||||
/// Subscribe to changes at key (optional)
|
||||
subscribe: ?*const fn (ptr: *anyopaque, key: [32]u8, callback: *const fn ([]const u8) void) anyerror!void,
|
||||
};
|
||||
|
||||
pub fn put(self: DHTInterface, key: [32]u8, value: []const u8) !void {
|
||||
return self.vtable.put(self.ptr, key, value);
|
||||
}
|
||||
|
||||
pub fn getAll(self: DHTInterface, key: [32]u8, allocator: Allocator) ![][]u8 {
|
||||
return self.vtable.getAll(self.ptr, key, allocator);
|
||||
}
|
||||
|
||||
pub fn subscribe(self: DHTInterface, key: [32]u8, callback: *const fn ([]const u8) void) !void {
|
||||
if (self.vtable.subscribe) |sub| {
|
||||
return sub(self.ptr, key, callback);
|
||||
}
|
||||
return error.SubscribeNotSupported;
|
||||
}
|
||||
};
|
||||
|
||||
/// Meeting point manager
|
||||
pub const MeetingPoint = struct {
|
||||
allocator: Allocator,
|
||||
dht: DHTInterface,
|
||||
our_keypair: KeyPair,
|
||||
our_addresses: []const Address,
|
||||
next_sequence: u64,
|
||||
|
||||
/// Ed25519 key pair
|
||||
pub const KeyPair = struct {
|
||||
public: [32]u8,
|
||||
secret: [64]u8,
|
||||
|
||||
/// Sign a message
|
||||
pub fn sign(self: KeyPair, message: [32]u8) [64]u8 {
|
||||
const secret_key = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch unreachable;
|
||||
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch unreachable;
|
||||
const key_pair = std.crypto.sign.Ed25519.KeyPair{
|
||||
.secret_key = secret_key,
|
||||
.public_key = public_key,
|
||||
};
|
||||
const sig = std.crypto.sign.Ed25519.KeyPair.sign(key_pair, &message, null) catch unreachable;
|
||||
return sig.toBytes();
|
||||
}
|
||||
};
|
||||
|
||||
/// Initialize meeting point manager
|
||||
pub fn init(
|
||||
allocator: Allocator,
|
||||
dht: DHTInterface,
|
||||
keypair: KeyPair,
|
||||
addresses: []const Address,
|
||||
) MeetingPoint {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.dht = dht,
|
||||
.our_keypair = keypair,
|
||||
.our_addresses = addresses,
|
||||
.next_sequence = 1,
|
||||
};
|
||||
}
|
||||
|
||||
/// Compute the deterministic meeting key for two peers
|
||||
pub fn computeMeetingKey(our_pubkey: [32]u8, their_pubkey: [32]u8) [32]u8 {
|
||||
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
||||
|
||||
// Protocol identifier
|
||||
hasher.update("mwp-v1");
|
||||
|
||||
// Deterministic ordering of public keys
|
||||
if (std.mem.lessThan(u8, &our_pubkey, &their_pubkey)) {
|
||||
hasher.update(&our_pubkey);
|
||||
hasher.update(&their_pubkey);
|
||||
} else {
|
||||
hasher.update(&their_pubkey);
|
||||
hasher.update(&our_pubkey);
|
||||
}
|
||||
|
||||
var result: [32]u8 = undefined;
|
||||
hasher.final(&result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Create a new publication
|
||||
pub fn createPublication(self: *MeetingPoint, ttl: u32) MeetingPublication {
|
||||
var pub_data = MeetingPublication{
|
||||
.peer_id = self.our_keypair.public,
|
||||
.addresses = self.our_addresses,
|
||||
.nonce = undefined,
|
||||
.timestamp = std.time.milliTimestamp(),
|
||||
.ttl = ttl,
|
||||
.sequence = self.next_sequence,
|
||||
.signature = undefined,
|
||||
};
|
||||
|
||||
// Generate random nonce
|
||||
std.crypto.random.bytes(&pub_data.nonce);
|
||||
|
||||
// Sign
|
||||
const hash = pub_data.computeHash();
|
||||
pub_data.signature = self.our_keypair.sign(hash);
|
||||
|
||||
self.next_sequence += 1;
|
||||
|
||||
return pub_data;
|
||||
}
|
||||
|
||||
/// Publish to a meeting point
|
||||
pub fn publish(self: *MeetingPoint, their_pubkey: [32]u8, ttl: u32) !MeetingPublication {
|
||||
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
|
||||
const publication = self.createPublication(ttl);
|
||||
|
||||
const serialized = try publication.serialize(self.allocator);
|
||||
defer self.allocator.free(serialized);
|
||||
|
||||
try self.dht.put(meeting_key, serialized);
|
||||
|
||||
return publication;
|
||||
}
|
||||
|
||||
/// Wait for peer's publication at meeting point
|
||||
pub fn waitForPeer(
|
||||
self: *MeetingPoint,
|
||||
their_pubkey: [32]u8,
|
||||
timeout_ms: u64,
|
||||
) !struct { publication: MeetingPublication, seen_time: i64 } {
|
||||
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
|
||||
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
|
||||
|
||||
while (std.time.milliTimestamp() < deadline) {
|
||||
// Query DHT
|
||||
const entries = try self.dht.getAll(meeting_key, self.allocator);
|
||||
defer {
|
||||
for (entries) |entry| {
|
||||
self.allocator.free(entry);
|
||||
}
|
||||
self.allocator.free(entries);
|
||||
}
|
||||
|
||||
// Look for peer's publication
|
||||
for (entries) |entry| {
|
||||
var publication = MeetingPublication.deserialize(self.allocator, entry) catch continue;
|
||||
|
||||
// Is this from our target peer?
|
||||
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
|
||||
publication.deinit(self.allocator);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verify signature
|
||||
if (!publication.verify()) {
|
||||
publication.deinit(self.allocator);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check not expired
|
||||
if (publication.isExpired()) {
|
||||
publication.deinit(self.allocator);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Found valid publication
|
||||
return .{
|
||||
.publication = publication,
|
||||
.seen_time = std.time.milliTimestamp(),
|
||||
};
|
||||
}
|
||||
|
||||
// Poll interval
|
||||
std.Thread.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms);
|
||||
}
|
||||
|
||||
return error.Timeout;
|
||||
}
|
||||
|
||||
/// Find peer's publication (non-blocking)
|
||||
pub fn findPeer(
|
||||
self: *MeetingPoint,
|
||||
their_pubkey: [32]u8,
|
||||
) !?MeetingPublication {
|
||||
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
|
||||
|
||||
const entries = try self.dht.getAll(meeting_key, self.allocator);
|
||||
defer {
|
||||
for (entries) |entry| {
|
||||
self.allocator.free(entry);
|
||||
}
|
||||
self.allocator.free(entries);
|
||||
}
|
||||
|
||||
for (entries) |entry| {
|
||||
var publication = MeetingPublication.deserialize(self.allocator, entry) catch continue;
|
||||
|
||||
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
|
||||
publication.deinit(self.allocator);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!publication.verify()) {
|
||||
publication.deinit(self.allocator);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (publication.isExpired()) {
|
||||
publication.deinit(self.allocator);
|
||||
continue;
|
||||
}
|
||||
|
||||
return publication;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Update our addresses and republish
|
||||
pub fn updateAddresses(self: *MeetingPoint, new_addresses: []const Address) void {
|
||||
self.our_addresses = new_addresses;
|
||||
}
|
||||
};
|
||||
|
||||
/// Compute shared rendezvous parameters from two publications
|
||||
pub fn computeRendezvousParams(
|
||||
our_pub: MeetingPublication,
|
||||
their_pub: MeetingPublication,
|
||||
seen_time: i64,
|
||||
buffer_ms: i64,
|
||||
) types.RendezvousParams {
|
||||
// Combine nonces deterministically
|
||||
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
||||
|
||||
if (std.mem.lessThan(u8, &our_pub.nonce, &their_pub.nonce)) {
|
||||
hasher.update(&our_pub.nonce);
|
||||
hasher.update(&their_pub.nonce);
|
||||
} else {
|
||||
hasher.update(&their_pub.nonce);
|
||||
hasher.update(&our_pub.nonce);
|
||||
}
|
||||
|
||||
var shared_randomness: [32]u8 = undefined;
|
||||
hasher.final(&shared_randomness);
|
||||
|
||||
// Rendezvous time: relative to when we saw peer (robust to clock skew)
|
||||
const rendezvous_time = seen_time + buffer_ms;
|
||||
|
||||
// Port hint from shared randomness
|
||||
const port_offset = std.mem.readInt(u16, shared_randomness[0..2], .little);
|
||||
const port_hint = 49152 + (port_offset % 16384);
|
||||
|
||||
// Connection ID from shared randomness
|
||||
var connection_id: [16]u8 = undefined;
|
||||
@memcpy(&connection_id, shared_randomness[16..32]);
|
||||
|
||||
return .{
|
||||
.shared_randomness = shared_randomness,
|
||||
.rendezvous_time = rendezvous_time,
|
||||
.port_hint = port_hint,
|
||||
.connection_id = connection_id,
|
||||
};
|
||||
}
|
||||
|
||||
// Tests
|
||||
test "computeMeetingKey is deterministic" {
|
||||
const key_a = [_]u8{1} ** 32;
|
||||
const key_b = [_]u8{2} ** 32;
|
||||
|
||||
const result1 = MeetingPoint.computeMeetingKey(key_a, key_b);
|
||||
const result2 = MeetingPoint.computeMeetingKey(key_b, key_a);
|
||||
|
||||
// Order shouldn't matter
|
||||
try std.testing.expect(std.mem.eql(u8, &result1, &result2));
|
||||
}
|
||||
|
||||
test "computeMeetingKey is unique per pair" {
|
||||
const key_a = [_]u8{1} ** 32;
|
||||
const key_b = [_]u8{2} ** 32;
|
||||
const key_c = [_]u8{3} ** 32;
|
||||
|
||||
const result_ab = MeetingPoint.computeMeetingKey(key_a, key_b);
|
||||
const result_ac = MeetingPoint.computeMeetingKey(key_a, key_c);
|
||||
|
||||
try std.testing.expect(!std.mem.eql(u8, &result_ab, &result_ac));
|
||||
}
|
||||
|
||||
test "computeRendezvousParams produces same result for both peers" {
|
||||
// Simulate two peers with their publications
|
||||
var our_nonce: [32]u8 = undefined;
|
||||
var their_nonce: [32]u8 = undefined;
|
||||
std.crypto.random.bytes(&our_nonce);
|
||||
std.crypto.random.bytes(&their_nonce);
|
||||
|
||||
const our_pub = MeetingPublication{
|
||||
.peer_id = [_]u8{1} ** 32,
|
||||
.addresses = &[_]Address{},
|
||||
.nonce = our_nonce,
|
||||
.timestamp = 1000,
|
||||
.ttl = 300,
|
||||
.sequence = 1,
|
||||
.signature = [_]u8{0} ** 64,
|
||||
};
|
||||
|
||||
const their_pub = MeetingPublication{
|
||||
.peer_id = [_]u8{2} ** 32,
|
||||
.addresses = &[_]Address{},
|
||||
.nonce = their_nonce,
|
||||
.timestamp = 1050,
|
||||
.ttl = 300,
|
||||
.sequence = 1,
|
||||
.signature = [_]u8{0} ** 64,
|
||||
};
|
||||
|
||||
// Both peers compute with their own seen_time
|
||||
const our_params = computeRendezvousParams(our_pub, their_pub, 1100, 500);
|
||||
const their_params = computeRendezvousParams(their_pub, our_pub, 1100, 500);
|
||||
|
||||
// Shared randomness should be identical
|
||||
try std.testing.expect(std.mem.eql(u8, &our_params.shared_randomness, &their_params.shared_randomness));
|
||||
|
||||
// Port hint should be identical
|
||||
try std.testing.expectEqual(our_params.port_hint, their_params.port_hint);
|
||||
|
||||
// Connection ID should be identical
|
||||
try std.testing.expect(std.mem.eql(u8, &our_params.connection_id, &their_params.connection_id));
|
||||
}
|
||||
444
src/mwp/mutual_witness.zig
Normal file
444
src/mwp/mutual_witness.zig
Normal file
@@ -0,0 +1,444 @@
|
||||
//! Mutual Witness Protocol - Main Module
|
||||
//!
|
||||
//! 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) KeyPair {
|
||||
const sk = std.crypto.sign.Ed25519.SecretKey.fromBytes(secret) catch unreachable;
|
||||
const kp = std.crypto.sign.Ed25519.KeyPair.fromSecretKey(sk) catch unreachable;
|
||||
return .{
|
||||
.public = kp.public_key.toBytes(),
|
||||
.secret = secret,
|
||||
};
|
||||
}
|
||||
|
||||
/// Sign a 32-byte hash
|
||||
pub fn sign(self: KeyPair, hash: [32]u8) [64]u8 {
|
||||
const sk = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch unreachable;
|
||||
const pk = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch unreachable;
|
||||
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 unreachable;
|
||||
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));
|
||||
}
|
||||
37
src/mwp/mwp.zig
Normal file
37
src/mwp/mwp.zig
Normal file
@@ -0,0 +1,37 @@
|
||||
//! Mutual Witness Protocol (MWP)
|
||||
//!
|
||||
//! A novel NAT traversal protocol requiring zero external infrastructure.
|
||||
//!
|
||||
//! See `mutual_witness.zig` for main documentation.
|
||||
|
||||
pub const mutual_witness = @import("mutual_witness.zig");
|
||||
pub const types = @import("types.zig");
|
||||
pub const meeting_point = @import("meeting_point.zig");
|
||||
pub const hole_punch = @import("hole_punch.zig");
|
||||
pub const p2p_dht_adapter = @import("p2p_dht_adapter.zig");
|
||||
|
||||
// Re-export main types for convenience
|
||||
pub const MutualWitness = mutual_witness.MutualWitness;
|
||||
pub const KeyPair = mutual_witness.KeyPair;
|
||||
pub const MockDHT = mutual_witness.MockDHT;
|
||||
pub const Address = types.Address;
|
||||
pub const MeetingPublication = types.MeetingPublication;
|
||||
pub const RendezvousParams = types.RendezvousParams;
|
||||
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 DHTInterface = meeting_point.DHTInterface;
|
||||
pub const MeetingPoint = meeting_point.MeetingPoint;
|
||||
pub const HolePunchEngine = hole_punch.HolePunchEngine;
|
||||
pub const P2PDhtAdapter = p2p_dht_adapter.P2PDhtAdapter;
|
||||
pub const P2PMeetingPoint = p2p_dht_adapter.P2PMeetingPoint;
|
||||
|
||||
test {
|
||||
_ = @import("types.zig");
|
||||
_ = @import("meeting_point.zig");
|
||||
_ = @import("hole_punch.zig");
|
||||
_ = @import("mutual_witness.zig");
|
||||
_ = @import("p2p_dht_adapter.zig");
|
||||
}
|
||||
208
src/mwp/p2p_dht_adapter.zig
Normal file
208
src/mwp/p2p_dht_adapter.zig
Normal file
@@ -0,0 +1,208 @@
|
||||
//! P2P DHT Adapter for MWP
|
||||
//!
|
||||
//! Adapts zig-p2p's DHT to work with the Mutual Witness Protocol.
|
||||
//!
|
||||
//! Key insight: MWP's original design has both peers publish to the same
|
||||
//! meeting key, then uses getAll() to retrieve all publications. However,
|
||||
//! zig-p2p's DHT stores one value per key.
|
||||
//!
|
||||
//! Solution: We use peer-specific publication keys:
|
||||
//! - Alice publishes at: hash(meeting_key || alice_pubkey)
|
||||
//! - Bob publishes at: hash(meeting_key || bob_pubkey)
|
||||
//! - When looking up, we query the peer's specific key
|
||||
//!
|
||||
//! This adapter wraps the P2P DHT and handles this key transformation.
|
||||
|
||||
const std = @import("std");
|
||||
const types = @import("types.zig");
|
||||
const meeting_point = @import("meeting_point.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const DHTInterface = meeting_point.DHTInterface;
|
||||
|
||||
/// Adapter to use zig-p2p's P2P DHT with MWP
|
||||
pub const P2PDhtAdapter = struct {
|
||||
allocator: Allocator,
|
||||
|
||||
/// Opaque pointer to zig-p2p P2P instance
|
||||
/// This is *P2P from src/p2p/p2p.zig
|
||||
p2p: *anyopaque,
|
||||
|
||||
/// Function pointers to P2P DHT methods (to avoid import cycle)
|
||||
dht_store_fn: *const fn (p2p: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void,
|
||||
dht_find_value_fn: *const fn (p2p: *anyopaque, key: [32]u8) anyerror!?[]u8,
|
||||
|
||||
/// Our public key (for computing publication keys)
|
||||
our_pubkey: [32]u8,
|
||||
|
||||
/// The target peer's public key we're trying to meet
|
||||
/// Set before put/getAll operations
|
||||
target_pubkey: ?[32]u8,
|
||||
|
||||
/// Default TTL for publications (seconds)
|
||||
default_ttl: u32,
|
||||
|
||||
pub const Config = struct {
|
||||
allocator: Allocator,
|
||||
p2p: *anyopaque,
|
||||
dht_store_fn: *const fn (p2p: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void,
|
||||
dht_find_value_fn: *const fn (p2p: *anyopaque, key: [32]u8) anyerror!?[]u8,
|
||||
our_pubkey: [32]u8,
|
||||
default_ttl: u32 = 300, // 5 minutes
|
||||
};
|
||||
|
||||
pub fn init(config: Config) P2PDhtAdapter {
|
||||
return .{
|
||||
.allocator = config.allocator,
|
||||
.p2p = config.p2p,
|
||||
.dht_store_fn = config.dht_store_fn,
|
||||
.dht_find_value_fn = config.dht_find_value_fn,
|
||||
.our_pubkey = config.our_pubkey,
|
||||
.target_pubkey = null,
|
||||
.default_ttl = config.default_ttl,
|
||||
};
|
||||
}
|
||||
|
||||
/// Set the target peer for the next operations
|
||||
/// Must be called before put/getAll when using the interface
|
||||
pub fn setTarget(self: *P2PDhtAdapter, target_pubkey: [32]u8) void {
|
||||
self.target_pubkey = target_pubkey;
|
||||
}
|
||||
|
||||
/// Compute the publication key for a specific peer at a meeting point
|
||||
/// publication_key = hash("mwp-pub" || meeting_key || publisher_pubkey)
|
||||
fn computePublicationKey(meeting_key: [32]u8, publisher_pubkey: [32]u8) [32]u8 {
|
||||
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
||||
hasher.update("mwp-pub-v1");
|
||||
hasher.update(&meeting_key);
|
||||
hasher.update(&publisher_pubkey);
|
||||
var result: [32]u8 = undefined;
|
||||
hasher.final(&result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// DHTInterface.put implementation
|
||||
/// Publishes our data at our publication key (meeting_key + our_pubkey)
|
||||
fn put(ptr: *anyopaque, meeting_key: [32]u8, value: []const u8) anyerror!void {
|
||||
const self: *P2PDhtAdapter = @ptrCast(@alignCast(ptr));
|
||||
|
||||
// Compute our publication key
|
||||
const pub_key = computePublicationKey(meeting_key, self.our_pubkey);
|
||||
|
||||
// Store in DHT
|
||||
try self.dht_store_fn(self.p2p, pub_key, value, self.default_ttl);
|
||||
}
|
||||
|
||||
/// DHTInterface.getAll implementation
|
||||
/// Looks up the target peer's publication key (meeting_key + target_pubkey)
|
||||
fn getAll(ptr: *anyopaque, meeting_key: [32]u8, allocator: Allocator) anyerror![][]u8 {
|
||||
const self: *P2PDhtAdapter = @ptrCast(@alignCast(ptr));
|
||||
|
||||
const target = self.target_pubkey orelse return error.TargetNotSet;
|
||||
|
||||
// Compute target's publication key
|
||||
const pub_key = computePublicationKey(meeting_key, target);
|
||||
|
||||
// Query DHT
|
||||
const value = try self.dht_find_value_fn(self.p2p, pub_key);
|
||||
|
||||
if (value) |v| {
|
||||
// Return as single-element array (DHT returns one value per key)
|
||||
const result = try allocator.alloc([]u8, 1);
|
||||
result[0] = v;
|
||||
return result;
|
||||
}
|
||||
|
||||
// No value found
|
||||
return &[_][]u8{};
|
||||
}
|
||||
|
||||
/// Get the DHTInterface for use with MWP
|
||||
pub fn interface(self: *P2PDhtAdapter) DHTInterface {
|
||||
return .{
|
||||
.ptr = self,
|
||||
.vtable = &.{
|
||||
.put = put,
|
||||
.getAll = getAll,
|
||||
.subscribe = null, // Not implemented yet
|
||||
},
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/// Wrapper for MeetingPoint that handles the target peer setup
|
||||
pub const P2PMeetingPoint = struct {
|
||||
allocator: Allocator,
|
||||
adapter: *P2PDhtAdapter,
|
||||
meeting: meeting_point.MeetingPoint,
|
||||
|
||||
pub fn init(
|
||||
allocator: Allocator,
|
||||
adapter: *P2PDhtAdapter,
|
||||
keypair: meeting_point.MeetingPoint.KeyPair,
|
||||
addresses: []const types.Address,
|
||||
) P2PMeetingPoint {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.adapter = adapter,
|
||||
.meeting = meeting_point.MeetingPoint.init(
|
||||
allocator,
|
||||
adapter.interface(),
|
||||
keypair,
|
||||
addresses,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/// Publish our availability for a specific peer
|
||||
pub fn publish(self: *P2PMeetingPoint, their_pubkey: [32]u8, ttl: u32) !types.MeetingPublication {
|
||||
// Set target before publishing (for key computation)
|
||||
self.adapter.setTarget(their_pubkey);
|
||||
return self.meeting.publish(their_pubkey, ttl);
|
||||
}
|
||||
|
||||
/// Wait for a peer's publication
|
||||
pub fn waitForPeer(
|
||||
self: *P2PMeetingPoint,
|
||||
their_pubkey: [32]u8,
|
||||
timeout_ms: u64,
|
||||
) !struct { publication: types.MeetingPublication, seen_time: i64 } {
|
||||
// Set target before querying
|
||||
self.adapter.setTarget(their_pubkey);
|
||||
return self.meeting.waitForPeer(their_pubkey, timeout_ms);
|
||||
}
|
||||
|
||||
/// Find a peer's publication (non-blocking)
|
||||
pub fn findPeer(self: *P2PMeetingPoint, their_pubkey: [32]u8) !?types.MeetingPublication {
|
||||
self.adapter.setTarget(their_pubkey);
|
||||
return self.meeting.findPeer(their_pubkey);
|
||||
}
|
||||
|
||||
/// Compute meeting key (for debugging)
|
||||
pub fn computeMeetingKey(our_pubkey: [32]u8, their_pubkey: [32]u8) [32]u8 {
|
||||
return meeting_point.MeetingPoint.computeMeetingKey(our_pubkey, their_pubkey);
|
||||
}
|
||||
};
|
||||
|
||||
// Tests
|
||||
test "P2PDhtAdapter publication key is deterministic" {
|
||||
const meeting_key = [_]u8{0xAA} ** 32;
|
||||
const pubkey = [_]u8{0xBB} ** 32;
|
||||
|
||||
const key1 = P2PDhtAdapter.computePublicationKey(meeting_key, pubkey);
|
||||
const key2 = P2PDhtAdapter.computePublicationKey(meeting_key, pubkey);
|
||||
|
||||
try std.testing.expect(std.mem.eql(u8, &key1, &key2));
|
||||
}
|
||||
|
||||
test "P2PDhtAdapter publication key differs by publisher" {
|
||||
const meeting_key = [_]u8{0xAA} ** 32;
|
||||
const alice_pubkey = [_]u8{0xBB} ** 32;
|
||||
const bob_pubkey = [_]u8{0xCC} ** 32;
|
||||
|
||||
const alice_key = P2PDhtAdapter.computePublicationKey(meeting_key, alice_pubkey);
|
||||
const bob_key = P2PDhtAdapter.computePublicationKey(meeting_key, bob_pubkey);
|
||||
|
||||
// Different publishers = different publication keys
|
||||
try std.testing.expect(!std.mem.eql(u8, &alice_key, &bob_key));
|
||||
}
|
||||
608
src/mwp/types.zig
Normal file
608
src/mwp/types.zig
Normal file
@@ -0,0 +1,608 @@
|
||||
//! Mutual Witness Protocol - Type Definitions
|
||||
//!
|
||||
//! Core data structures for the MWP protocol.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
/// Protocol version
|
||||
pub const PROTOCOL_VERSION: u8 = 0x01;
|
||||
|
||||
/// Magic bytes for hole punch packets
|
||||
pub const HOLE_PUNCH_MAGIC = [4]u8{ 'M', 'W', 'P', '1' };
|
||||
|
||||
/// Default parameters
|
||||
pub const Defaults = struct {
|
||||
/// Time to live for publications (seconds)
|
||||
pub const publication_ttl: u32 = 300; // 5 minutes
|
||||
|
||||
/// Buffer time after seeing peer's publication (milliseconds)
|
||||
pub const rendezvous_buffer_ms: i64 = 500;
|
||||
|
||||
/// Timeout waiting for peer's publication (milliseconds)
|
||||
pub const discovery_timeout_ms: u64 = 30_000; // 30 seconds
|
||||
|
||||
/// Timeout for hole punch attempts (milliseconds)
|
||||
pub const hole_punch_timeout_ms: u64 = 2_000;
|
||||
|
||||
/// Number of retry attempts
|
||||
pub const max_retries: u32 = 4;
|
||||
|
||||
/// Retry intervals (milliseconds)
|
||||
pub const retry_intervals = [_]u64{ 0, 500, 1000, 2000 };
|
||||
|
||||
/// DHT poll interval (milliseconds)
|
||||
pub const dht_poll_interval_ms: u64 = 100;
|
||||
|
||||
/// Keepalive interval during wait (milliseconds)
|
||||
pub const keepalive_interval_ms: u64 = 10_000;
|
||||
};
|
||||
|
||||
/// Compute BLAKE2b-256 hash
|
||||
pub fn blake2b256(data: []const u8) [32]u8 {
|
||||
var out: [32]u8 = undefined;
|
||||
std.crypto.hash.blake2.Blake2b256.hash(data, &out, .{});
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Network address (IPv4 or IPv6)
|
||||
pub const Address = struct {
|
||||
/// Address type
|
||||
pub const Type = enum(u8) {
|
||||
ipv4 = 4,
|
||||
ipv6 = 6,
|
||||
};
|
||||
|
||||
addr_type: Type,
|
||||
ip: union {
|
||||
v4: [4]u8,
|
||||
v6: [16]u8,
|
||||
},
|
||||
port: u16,
|
||||
|
||||
/// Create IPv4 address
|
||||
pub fn initV4(ip: [4]u8, port: u16) Address {
|
||||
return .{
|
||||
.addr_type = .ipv4,
|
||||
.ip = .{ .v4 = ip },
|
||||
.port = port,
|
||||
};
|
||||
}
|
||||
|
||||
/// Create IPv6 address
|
||||
pub fn initV6(ip: [16]u8, port: u16) Address {
|
||||
return .{
|
||||
.addr_type = .ipv6,
|
||||
.ip = .{ .v6 = ip },
|
||||
.port = port,
|
||||
};
|
||||
}
|
||||
|
||||
/// Check equality
|
||||
pub fn eql(self: Address, other: Address) bool {
|
||||
if (self.addr_type != other.addr_type) return false;
|
||||
if (self.port != other.port) return false;
|
||||
|
||||
return switch (self.addr_type) {
|
||||
.ipv4 => std.mem.eql(u8, &self.ip.v4, &other.ip.v4),
|
||||
.ipv6 => std.mem.eql(u8, &self.ip.v6, &other.ip.v6),
|
||||
};
|
||||
}
|
||||
|
||||
/// Serialize to bytes
|
||||
pub fn serialize(self: Address, buf: []u8) !usize {
|
||||
var idx: usize = 0;
|
||||
|
||||
buf[idx] = @intFromEnum(self.addr_type);
|
||||
idx += 1;
|
||||
|
||||
switch (self.addr_type) {
|
||||
.ipv4 => {
|
||||
@memcpy(buf[idx..][0..4], &self.ip.v4);
|
||||
idx += 4;
|
||||
},
|
||||
.ipv6 => {
|
||||
@memcpy(buf[idx..][0..16], &self.ip.v6);
|
||||
idx += 16;
|
||||
},
|
||||
}
|
||||
|
||||
std.mem.writeInt(u16, buf[idx..][0..2], self.port, .big);
|
||||
idx += 2;
|
||||
|
||||
return idx;
|
||||
}
|
||||
|
||||
/// Deserialize from bytes
|
||||
pub fn deserialize(buf: []const u8) !struct { addr: Address, consumed: usize } {
|
||||
if (buf.len < 3) return error.BufferTooSmall;
|
||||
|
||||
var idx: usize = 0;
|
||||
|
||||
const addr_type = std.meta.intToEnum(Type, buf[idx]) catch return error.InvalidAddressType;
|
||||
idx += 1;
|
||||
|
||||
var addr: Address = undefined;
|
||||
addr.addr_type = addr_type;
|
||||
|
||||
switch (addr_type) {
|
||||
.ipv4 => {
|
||||
if (buf.len < idx + 6) return error.BufferTooSmall;
|
||||
var v4: [4]u8 = undefined;
|
||||
@memcpy(&v4, buf[idx..][0..4]);
|
||||
addr.ip = .{ .v4 = v4 };
|
||||
idx += 4;
|
||||
},
|
||||
.ipv6 => {
|
||||
if (buf.len < idx + 18) return error.BufferTooSmall;
|
||||
var v6: [16]u8 = undefined;
|
||||
@memcpy(&v6, buf[idx..][0..16]);
|
||||
addr.ip = .{ .v6 = v6 };
|
||||
idx += 16;
|
||||
},
|
||||
}
|
||||
|
||||
addr.port = std.mem.readInt(u16, buf[idx..][0..2], .big);
|
||||
idx += 2;
|
||||
|
||||
return .{ .addr = addr, .consumed = idx };
|
||||
}
|
||||
|
||||
/// Get wire size
|
||||
pub fn wireSize(self: Address) usize {
|
||||
return 1 + (if (self.addr_type == .ipv4) @as(usize, 4) else @as(usize, 16)) + 2;
|
||||
}
|
||||
};
|
||||
|
||||
/// Publication that peers post to the DHT meeting point
|
||||
pub const MeetingPublication = struct {
|
||||
/// Peer's public key (Ed25519)
|
||||
peer_id: [32]u8,
|
||||
|
||||
/// Connection addresses (multiple for fallback)
|
||||
addresses: []const Address,
|
||||
|
||||
/// Random nonce for mutual witness
|
||||
nonce: [32]u8,
|
||||
|
||||
/// Timestamp (milliseconds since Unix epoch)
|
||||
timestamp: i64,
|
||||
|
||||
/// Time-to-live (seconds)
|
||||
ttl: u32,
|
||||
|
||||
/// Sequence number (monotonically increasing)
|
||||
sequence: u64,
|
||||
|
||||
/// Ed25519 signature over all above fields
|
||||
signature: [64]u8,
|
||||
|
||||
/// Check if publication is expired
|
||||
pub fn isExpired(self: MeetingPublication) bool {
|
||||
const now_ms = std.time.milliTimestamp();
|
||||
const expiry_ms = self.timestamp + (@as(i64, self.ttl) * 1000);
|
||||
return now_ms > expiry_ms;
|
||||
}
|
||||
|
||||
/// Compute hash of publication (for signing)
|
||||
pub fn computeHash(self: MeetingPublication) [32]u8 {
|
||||
var buf: [1024]u8 = undefined;
|
||||
var idx: usize = 0;
|
||||
|
||||
// Version
|
||||
buf[idx] = PROTOCOL_VERSION;
|
||||
idx += 1;
|
||||
|
||||
// Peer ID
|
||||
@memcpy(buf[idx..][0..32], &self.peer_id);
|
||||
idx += 32;
|
||||
|
||||
// Address count
|
||||
buf[idx] = @intCast(self.addresses.len);
|
||||
idx += 1;
|
||||
|
||||
// Addresses (simplified - just count for hash)
|
||||
for (self.addresses) |addr| {
|
||||
const size = addr.serialize(buf[idx..]) catch 0;
|
||||
idx += size;
|
||||
}
|
||||
|
||||
// Nonce
|
||||
@memcpy(buf[idx..][0..32], &self.nonce);
|
||||
idx += 32;
|
||||
|
||||
// Timestamp
|
||||
std.mem.writeInt(i64, buf[idx..][0..8], self.timestamp, .big);
|
||||
idx += 8;
|
||||
|
||||
// TTL
|
||||
std.mem.writeInt(u32, buf[idx..][0..4], self.ttl, .big);
|
||||
idx += 4;
|
||||
|
||||
// Sequence
|
||||
std.mem.writeInt(u64, buf[idx..][0..8], self.sequence, .big);
|
||||
idx += 8;
|
||||
|
||||
return blake2b256(buf[0..idx]);
|
||||
}
|
||||
|
||||
/// Verify signature
|
||||
pub fn verify(self: MeetingPublication) bool {
|
||||
const hash = self.computeHash();
|
||||
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.peer_id) catch return false;
|
||||
const sig = std.crypto.sign.Ed25519.Signature.fromBytes(self.signature);
|
||||
sig.verify(&hash, public_key) catch return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Serialize to bytes
|
||||
pub fn serialize(self: MeetingPublication, allocator: Allocator) ![]u8 {
|
||||
// Calculate size
|
||||
var size: usize = 1; // version
|
||||
size += 32; // peer_id
|
||||
size += 1; // address count
|
||||
for (self.addresses) |addr| {
|
||||
size += addr.wireSize();
|
||||
}
|
||||
size += 32; // nonce
|
||||
size += 8; // timestamp
|
||||
size += 4; // ttl
|
||||
size += 8; // sequence
|
||||
size += 64; // signature
|
||||
|
||||
const buf = try allocator.alloc(u8, size);
|
||||
var idx: usize = 0;
|
||||
|
||||
// Version
|
||||
buf[idx] = PROTOCOL_VERSION;
|
||||
idx += 1;
|
||||
|
||||
// Peer ID
|
||||
@memcpy(buf[idx..][0..32], &self.peer_id);
|
||||
idx += 32;
|
||||
|
||||
// Addresses
|
||||
buf[idx] = @intCast(self.addresses.len);
|
||||
idx += 1;
|
||||
for (self.addresses) |addr| {
|
||||
idx += try addr.serialize(buf[idx..]);
|
||||
}
|
||||
|
||||
// Nonce
|
||||
@memcpy(buf[idx..][0..32], &self.nonce);
|
||||
idx += 32;
|
||||
|
||||
// Timestamp
|
||||
std.mem.writeInt(i64, buf[idx..][0..8], self.timestamp, .big);
|
||||
idx += 8;
|
||||
|
||||
// TTL
|
||||
std.mem.writeInt(u32, buf[idx..][0..4], self.ttl, .big);
|
||||
idx += 4;
|
||||
|
||||
// Sequence
|
||||
std.mem.writeInt(u64, buf[idx..][0..8], self.sequence, .big);
|
||||
idx += 8;
|
||||
|
||||
// Signature
|
||||
@memcpy(buf[idx..][0..64], &self.signature);
|
||||
idx += 64;
|
||||
|
||||
return buf[0..idx];
|
||||
}
|
||||
|
||||
/// Deserialize from bytes
|
||||
pub fn deserialize(allocator: Allocator, buf: []const u8) !MeetingPublication {
|
||||
if (buf.len < 1 + 32 + 1 + 32 + 8 + 4 + 8 + 64) {
|
||||
return error.BufferTooSmall;
|
||||
}
|
||||
|
||||
var idx: usize = 0;
|
||||
|
||||
// Version
|
||||
const version = buf[idx];
|
||||
if (version != PROTOCOL_VERSION) return error.UnsupportedVersion;
|
||||
idx += 1;
|
||||
|
||||
// Peer ID
|
||||
var peer_id: [32]u8 = undefined;
|
||||
@memcpy(&peer_id, buf[idx..][0..32]);
|
||||
idx += 32;
|
||||
|
||||
// Addresses
|
||||
const addr_count = buf[idx];
|
||||
idx += 1;
|
||||
|
||||
const addresses = try allocator.alloc(Address, addr_count);
|
||||
for (0..addr_count) |i| {
|
||||
const result = try Address.deserialize(buf[idx..]);
|
||||
addresses[i] = result.addr;
|
||||
idx += result.consumed;
|
||||
}
|
||||
|
||||
// Nonce
|
||||
var nonce: [32]u8 = undefined;
|
||||
@memcpy(&nonce, buf[idx..][0..32]);
|
||||
idx += 32;
|
||||
|
||||
// Timestamp
|
||||
const timestamp = std.mem.readInt(i64, buf[idx..][0..8], .big);
|
||||
idx += 8;
|
||||
|
||||
// TTL
|
||||
const ttl = std.mem.readInt(u32, buf[idx..][0..4], .big);
|
||||
idx += 4;
|
||||
|
||||
// Sequence
|
||||
const sequence = std.mem.readInt(u64, buf[idx..][0..8], .big);
|
||||
idx += 8;
|
||||
|
||||
// Signature
|
||||
var signature: [64]u8 = undefined;
|
||||
@memcpy(&signature, buf[idx..][0..64]);
|
||||
idx += 64;
|
||||
|
||||
return MeetingPublication{
|
||||
.peer_id = peer_id,
|
||||
.addresses = addresses,
|
||||
.nonce = nonce,
|
||||
.timestamp = timestamp,
|
||||
.ttl = ttl,
|
||||
.sequence = sequence,
|
||||
.signature = signature,
|
||||
};
|
||||
}
|
||||
|
||||
/// Free allocated memory
|
||||
pub fn deinit(self: *MeetingPublication, allocator: Allocator) void {
|
||||
allocator.free(self.addresses);
|
||||
}
|
||||
};
|
||||
|
||||
/// Computed rendezvous parameters (derived by both peers independently)
|
||||
pub const RendezvousParams = struct {
|
||||
/// Shared randomness from both nonces
|
||||
shared_randomness: [32]u8,
|
||||
|
||||
/// Time to attempt connection (milliseconds since epoch)
|
||||
rendezvous_time: i64,
|
||||
|
||||
/// Suggested port to try
|
||||
port_hint: u16,
|
||||
|
||||
/// Unique connection ID for this attempt
|
||||
connection_id: [16]u8,
|
||||
};
|
||||
|
||||
/// Hole punch packet sent during connection attempt
|
||||
pub const HolePunchPacket = struct {
|
||||
/// Magic bytes for identification
|
||||
magic: [4]u8 = HOLE_PUNCH_MAGIC,
|
||||
|
||||
/// Connection ID from rendezvous params
|
||||
connection_id: [16]u8,
|
||||
|
||||
/// Sender's public key
|
||||
sender_id: [32]u8,
|
||||
|
||||
/// Timestamp of send
|
||||
timestamp: i64,
|
||||
|
||||
/// Signature over above fields
|
||||
signature: [64]u8,
|
||||
|
||||
/// Serialize to bytes
|
||||
pub fn serialize(self: HolePunchPacket) [124]u8 {
|
||||
var buf: [124]u8 = undefined;
|
||||
var idx: usize = 0;
|
||||
|
||||
@memcpy(buf[idx..][0..4], &self.magic);
|
||||
idx += 4;
|
||||
|
||||
@memcpy(buf[idx..][0..16], &self.connection_id);
|
||||
idx += 16;
|
||||
|
||||
@memcpy(buf[idx..][0..32], &self.sender_id);
|
||||
idx += 32;
|
||||
|
||||
std.mem.writeInt(i64, buf[idx..][0..8], self.timestamp, .big);
|
||||
idx += 8;
|
||||
|
||||
@memcpy(buf[idx..][0..64], &self.signature);
|
||||
idx += 64;
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
/// Deserialize from bytes
|
||||
pub fn deserialize(buf: []const u8) !HolePunchPacket {
|
||||
if (buf.len < 124) return error.BufferTooSmall;
|
||||
|
||||
var pkt: HolePunchPacket = undefined;
|
||||
var idx: usize = 0;
|
||||
|
||||
@memcpy(&pkt.magic, buf[idx..][0..4]);
|
||||
if (!std.mem.eql(u8, &pkt.magic, &HOLE_PUNCH_MAGIC)) {
|
||||
return error.InvalidMagic;
|
||||
}
|
||||
idx += 4;
|
||||
|
||||
@memcpy(&pkt.connection_id, buf[idx..][0..16]);
|
||||
idx += 16;
|
||||
|
||||
@memcpy(&pkt.sender_id, buf[idx..][0..32]);
|
||||
idx += 32;
|
||||
|
||||
pkt.timestamp = std.mem.readInt(i64, buf[idx..][0..8], .big);
|
||||
idx += 8;
|
||||
|
||||
@memcpy(&pkt.signature, buf[idx..][0..64]);
|
||||
idx += 64;
|
||||
|
||||
return pkt;
|
||||
}
|
||||
|
||||
/// Compute hash for signing
|
||||
pub fn computeHash(self: HolePunchPacket) [32]u8 {
|
||||
var buf: [60]u8 = undefined;
|
||||
@memcpy(buf[0..4], &self.magic);
|
||||
@memcpy(buf[4..20], &self.connection_id);
|
||||
@memcpy(buf[20..52], &self.sender_id);
|
||||
std.mem.writeInt(i64, buf[52..60], self.timestamp, .big);
|
||||
return blake2b256(&buf);
|
||||
}
|
||||
|
||||
/// Verify signature
|
||||
pub fn verify(self: HolePunchPacket) bool {
|
||||
const hash = self.computeHash();
|
||||
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.sender_id) catch return false;
|
||||
const sig = std.crypto.sign.Ed25519.Signature.fromBytes(self.signature);
|
||||
sig.verify(&hash, public_key) catch return false;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
/// Result of a connection attempt
|
||||
pub const ConnectionResult = union(enum) {
|
||||
/// Connection succeeded
|
||||
success: ConnectionInfo,
|
||||
|
||||
/// Peer not found in DHT
|
||||
peer_not_found,
|
||||
|
||||
/// Timeout waiting for peer
|
||||
timeout,
|
||||
|
||||
/// Hole punch failed
|
||||
hole_punch_failed: HolePunchError,
|
||||
|
||||
/// Other error
|
||||
other_error: anyerror,
|
||||
};
|
||||
|
||||
/// Information about established connection
|
||||
pub const ConnectionInfo = struct {
|
||||
/// Remote peer's public key
|
||||
peer_id: [32]u8,
|
||||
|
||||
/// Remote address we connected to
|
||||
remote_address: Address,
|
||||
|
||||
/// Local address we connected from
|
||||
local_address: Address,
|
||||
|
||||
/// Connection ID used
|
||||
connection_id: [16]u8,
|
||||
|
||||
/// Time taken to establish (milliseconds)
|
||||
establishment_time_ms: u64,
|
||||
};
|
||||
|
||||
/// Hole punch specific errors
|
||||
pub const HolePunchError = enum {
|
||||
/// All addresses unreachable
|
||||
all_addresses_failed,
|
||||
|
||||
/// NAT traversal failed
|
||||
nat_traversal_failed,
|
||||
|
||||
/// Timeout during attempt
|
||||
timeout,
|
||||
|
||||
/// Invalid response received
|
||||
invalid_response,
|
||||
|
||||
/// Signature verification failed
|
||||
signature_failed,
|
||||
};
|
||||
|
||||
/// Options for connection attempts
|
||||
pub const ConnectOptions = struct {
|
||||
/// Timeout for entire operation (milliseconds)
|
||||
timeout_ms: u64 = Defaults.discovery_timeout_ms,
|
||||
|
||||
/// Number of retries
|
||||
max_retries: u32 = Defaults.max_retries,
|
||||
|
||||
/// TTL for our publication
|
||||
publication_ttl: u32 = Defaults.publication_ttl,
|
||||
|
||||
/// Buffer after seeing peer (milliseconds)
|
||||
rendezvous_buffer_ms: i64 = Defaults.rendezvous_buffer_ms,
|
||||
|
||||
/// Whether to try port hints
|
||||
use_port_hints: bool = true,
|
||||
|
||||
/// Whether to send keepalives during wait
|
||||
send_keepalives: bool = true,
|
||||
};
|
||||
|
||||
/// Statistics about MWP operations
|
||||
pub const Stats = struct {
|
||||
/// Total connection attempts
|
||||
attempts: u64 = 0,
|
||||
|
||||
/// Successful connections
|
||||
successes: u64 = 0,
|
||||
|
||||
/// Failed connections
|
||||
failures: u64 = 0,
|
||||
|
||||
/// Average connection time (milliseconds)
|
||||
avg_connection_time_ms: u64 = 0,
|
||||
|
||||
/// Publications created
|
||||
publications_created: u64 = 0,
|
||||
|
||||
/// Publications received
|
||||
publications_received: u64 = 0,
|
||||
|
||||
/// Hole punch packets sent
|
||||
hole_punch_sent: u64 = 0,
|
||||
|
||||
/// Hole punch packets received
|
||||
hole_punch_received: u64 = 0,
|
||||
};
|
||||
|
||||
// Tests
|
||||
test "Address serialization roundtrip" {
|
||||
const addr = Address.initV4(.{ 192, 168, 1, 1 }, 8080);
|
||||
var buf: [19]u8 = undefined;
|
||||
const size = try addr.serialize(&buf);
|
||||
|
||||
const result = try Address.deserialize(buf[0..size]);
|
||||
try std.testing.expect(addr.eql(result.addr));
|
||||
}
|
||||
|
||||
test "Address IPv6 serialization" {
|
||||
const ip: [16]u8 = .{ 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
|
||||
const addr = Address.initV6(ip, 443);
|
||||
var buf: [19]u8 = undefined;
|
||||
const size = try addr.serialize(&buf);
|
||||
|
||||
const result = try Address.deserialize(buf[0..size]);
|
||||
try std.testing.expect(addr.eql(result.addr));
|
||||
try std.testing.expectEqual(@as(usize, 19), size);
|
||||
}
|
||||
|
||||
test "HolePunchPacket serialization" {
|
||||
var pkt = HolePunchPacket{
|
||||
.connection_id = [_]u8{1} ** 16,
|
||||
.sender_id = [_]u8{2} ** 32,
|
||||
.timestamp = 1234567890,
|
||||
.signature = [_]u8{3} ** 64,
|
||||
};
|
||||
|
||||
const serialized = pkt.serialize();
|
||||
const deserialized = try HolePunchPacket.deserialize(&serialized);
|
||||
|
||||
try std.testing.expect(std.mem.eql(u8, &pkt.connection_id, &deserialized.connection_id));
|
||||
try std.testing.expect(std.mem.eql(u8, &pkt.sender_id, &deserialized.sender_id));
|
||||
try std.testing.expectEqual(pkt.timestamp, deserialized.timestamp);
|
||||
}
|
||||
|
||||
test "blake2b256 hash" {
|
||||
const data = "hello world";
|
||||
const hash = blake2b256(data);
|
||||
try std.testing.expectEqual(@as(usize, 32), hash.len);
|
||||
}
|
||||
Reference in New Issue
Block a user