create Mutual Witness Protocol specs and implementation. mwp aims to be
a zero-infrastructure NAT traversal
This commit is contained in:
401
src/mwp_integration.zig
Normal file
401
src/mwp_integration.zig
Normal file
@@ -0,0 +1,401 @@
|
||||
//! MWP (Mutual Witness Protocol) Integration for zig-p2p
|
||||
//!
|
||||
//! This module provides seamless integration between MWP and zig-p2p's DHT,
|
||||
//! enabling NAT traversal and peer discovery without external infrastructure.
|
||||
//!
|
||||
//! ## Quick Start
|
||||
//!
|
||||
//! ```zig
|
||||
//! const mwp = @import("mwp");
|
||||
//!
|
||||
//! // Create MWP instance attached to P2P node
|
||||
//! var mwp_instance = try mwp.MWP.init(allocator, p2p, .{});
|
||||
//! defer mwp_instance.deinit();
|
||||
//!
|
||||
//! // Connect to a peer by their public key
|
||||
//! const result = try mwp_instance.connect(target_pubkey, .{ .timeout_ms = 30_000 });
|
||||
//! switch (result) {
|
||||
//! .success => |info| std.debug.print("Connected to peer\n", .{}),
|
||||
//! .timeout => std.debug.print("Peer not found\n", .{}),
|
||||
//! else => {},
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
// Import zig-p2p P2P module
|
||||
const p2p_mod = @import("p2p");
|
||||
const P2P = p2p_mod.P2P;
|
||||
|
||||
// Import MWP core library types
|
||||
const mwp_lib = @import("mwp_lib");
|
||||
pub const types = mwp_lib.types;
|
||||
|
||||
// Re-export types for user convenience
|
||||
pub const Address = types.Address;
|
||||
pub const MeetingPublication = types.MeetingPublication;
|
||||
pub const ConnectionResult = types.ConnectionResult;
|
||||
pub const ConnectionInfo = types.ConnectionInfo;
|
||||
pub const HolePunchError = types.HolePunchError;
|
||||
pub const ConnectOptions = types.ConnectOptions;
|
||||
pub const RendezvousParams = types.RendezvousParams;
|
||||
pub const HolePunchPacket = types.HolePunchPacket;
|
||||
pub const Stats = types.Stats;
|
||||
pub const Defaults = types.Defaults;
|
||||
|
||||
// Re-export KeyPair from mutual_witness
|
||||
pub const KeyPair = mwp_lib.KeyPair;
|
||||
|
||||
/// Main MWP integration with zig-p2p
|
||||
pub const MWP = struct {
|
||||
allocator: Allocator,
|
||||
p2p: *P2P,
|
||||
keypair: KeyPair,
|
||||
our_addresses: []const Address,
|
||||
next_sequence: u64,
|
||||
default_ttl: u32,
|
||||
|
||||
pub const InitOptions = struct {
|
||||
/// Override MWP identity (default: generate new)
|
||||
keypair: ?KeyPair = null,
|
||||
/// Our reachable addresses for hole punch
|
||||
addresses: ?[]const Address = null,
|
||||
/// Default TTL for publications
|
||||
default_ttl: u32 = Defaults.publication_ttl,
|
||||
};
|
||||
|
||||
/// Initialize MWP with a zig-p2p node
|
||||
pub fn init(allocator: Allocator, p2p: *P2P, options: InitOptions) !*MWP {
|
||||
const self = try allocator.create(MWP);
|
||||
|
||||
// Generate or use provided keypair
|
||||
const keypair = options.keypair orelse KeyPair.generate();
|
||||
|
||||
// Use provided addresses or detect from P2P
|
||||
const addresses = if (options.addresses) |addrs|
|
||||
try allocator.dupe(Address, addrs)
|
||||
else blk: {
|
||||
// Try to get our address from P2P config
|
||||
// For now, default to localhost
|
||||
const default_addrs = try allocator.alloc(Address, 1);
|
||||
default_addrs[0] = Address.initV4(.{ 127, 0, 0, 1 }, 9000);
|
||||
break :blk default_addrs;
|
||||
};
|
||||
|
||||
self.* = .{
|
||||
.allocator = allocator,
|
||||
.p2p = p2p,
|
||||
.keypair = keypair,
|
||||
.our_addresses = addresses,
|
||||
.next_sequence = 1,
|
||||
.default_ttl = options.default_ttl,
|
||||
};
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *MWP) void {
|
||||
self.allocator.free(self.our_addresses);
|
||||
self.allocator.destroy(self);
|
||||
}
|
||||
|
||||
/// Get our MWP public key
|
||||
pub fn getPublicKey(self: *MWP) [32]u8 {
|
||||
return self.keypair.public;
|
||||
}
|
||||
|
||||
/// Compute the meeting key for a peer pair
|
||||
pub fn computeMeetingKey(our_pubkey: [32]u8, their_pubkey: [32]u8) [32]u8 {
|
||||
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
||||
hasher.update("mwp-v1");
|
||||
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;
|
||||
}
|
||||
|
||||
/// Compute publication key (meeting_key + publisher)
|
||||
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;
|
||||
}
|
||||
|
||||
/// Create a publication for a target peer
|
||||
fn createPublication(self: *MWP, ttl: u32) MeetingPublication {
|
||||
var pub_data = MeetingPublication{
|
||||
.peer_id = self.keypair.public,
|
||||
.addresses = self.our_addresses,
|
||||
.nonce = undefined,
|
||||
.timestamp = std.time.milliTimestamp(),
|
||||
.ttl = ttl,
|
||||
.sequence = self.next_sequence,
|
||||
.signature = undefined,
|
||||
};
|
||||
|
||||
std.crypto.random.bytes(&pub_data.nonce);
|
||||
const hash = pub_data.computeHash();
|
||||
pub_data.signature = self.keypair.sign(hash);
|
||||
|
||||
self.next_sequence += 1;
|
||||
return pub_data;
|
||||
}
|
||||
|
||||
/// Publish our availability for a specific peer
|
||||
pub fn publishFor(self: *MWP, their_pubkey: [32]u8, ttl: u32) !MeetingPublication {
|
||||
const meeting_key = computeMeetingKey(self.keypair.public, their_pubkey);
|
||||
const pub_key = computePublicationKey(meeting_key, self.keypair.public);
|
||||
|
||||
const publication = self.createPublication(ttl);
|
||||
const serialized = try publication.serialize(self.allocator);
|
||||
defer self.allocator.free(serialized);
|
||||
|
||||
// Store in zig-p2p DHT
|
||||
try self.p2p.dhtStore(pub_key, serialized, ttl);
|
||||
|
||||
return publication;
|
||||
}
|
||||
|
||||
/// Find a peer's publication (non-blocking)
|
||||
pub fn findPeer(self: *MWP, their_pubkey: [32]u8) !?MeetingPublication {
|
||||
const meeting_key = computeMeetingKey(self.keypair.public, their_pubkey);
|
||||
const pub_key = computePublicationKey(meeting_key, their_pubkey);
|
||||
|
||||
// Query zig-p2p DHT
|
||||
const value = try self.p2p.dhtFindValue(pub_key);
|
||||
if (value) |v| {
|
||||
defer self.allocator.free(v);
|
||||
|
||||
var publication = MeetingPublication.deserialize(self.allocator, v) catch return null;
|
||||
|
||||
// Verify it's from the right peer
|
||||
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
|
||||
publication.deinit(self.allocator);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Verify signature
|
||||
if (!publication.verify()) {
|
||||
publication.deinit(self.allocator);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check expiry
|
||||
if (publication.isExpired()) {
|
||||
publication.deinit(self.allocator);
|
||||
return null;
|
||||
}
|
||||
|
||||
return publication;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Wait for peer's publication (blocking with timeout)
|
||||
pub fn waitForPeer(self: *MWP, their_pubkey: [32]u8, timeout_ms: u64) !MeetingPublication {
|
||||
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
|
||||
|
||||
while (std.time.milliTimestamp() < deadline) {
|
||||
if (try self.findPeer(their_pubkey)) |publication| {
|
||||
return publication;
|
||||
}
|
||||
std.Thread.sleep(100 * std.time.ns_per_ms);
|
||||
}
|
||||
|
||||
return error.Timeout;
|
||||
}
|
||||
|
||||
/// Connect to a peer using MWP
|
||||
///
|
||||
/// This is the main entry point:
|
||||
/// 1. Publishes our availability to DHT
|
||||
/// 2. Waits for peer's publication
|
||||
/// 3. Computes rendezvous parameters
|
||||
/// 4. Attempts simultaneous hole punch
|
||||
pub fn connect(self: *MWP, target_pubkey: [32]u8, options: ConnectOptions) ConnectionResult {
|
||||
// Step 1: Publish our availability
|
||||
const our_publication = self.publishFor(target_pubkey, options.publication_ttl) catch |err| {
|
||||
return .{ .other_error = err };
|
||||
};
|
||||
|
||||
// Step 2: Wait for peer
|
||||
const peer_publication = self.waitForPeer(target_pubkey, options.timeout_ms) catch |err| {
|
||||
return switch (err) {
|
||||
error.Timeout => .timeout,
|
||||
else => .{ .other_error = err },
|
||||
};
|
||||
};
|
||||
defer {
|
||||
var pub_copy = peer_publication;
|
||||
pub_copy.deinit(self.allocator);
|
||||
}
|
||||
|
||||
// Step 3: Compute rendezvous params
|
||||
const params = computeRendezvousParamsFromPubs(our_publication, peer_publication, options.rendezvous_buffer_ms);
|
||||
|
||||
// Step 4: Attempt hole punch
|
||||
return self.attemptHolePunch(peer_publication.addresses, params, options);
|
||||
}
|
||||
|
||||
fn computeRendezvousParamsFromPubs(our_pub: MeetingPublication, their_pub: MeetingPublication, buffer_ms: i64) RendezvousParams {
|
||||
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);
|
||||
|
||||
const rendezvous_time = std.time.milliTimestamp() + buffer_ms;
|
||||
const port_offset = std.mem.readInt(u16, shared_randomness[0..2], .little);
|
||||
const port_hint = 49152 + (port_offset % 16384);
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
fn attemptHolePunch(
|
||||
self: *MWP,
|
||||
target_addresses: []const Address,
|
||||
params: RendezvousParams,
|
||||
options: ConnectOptions,
|
||||
) ConnectionResult {
|
||||
_ = options;
|
||||
|
||||
// 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;
|
||||
std.Thread.sleep(wait_ns);
|
||||
}
|
||||
|
||||
// Create UDP socket
|
||||
const fd = std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0) catch {
|
||||
return .{ .hole_punch_failed = .all_addresses_failed };
|
||||
};
|
||||
defer std.posix.close(fd);
|
||||
|
||||
// Set non-blocking
|
||||
const flags = std.posix.fcntl(fd, std.posix.F.GETFL, 0) catch {
|
||||
return .{ .hole_punch_failed = .all_addresses_failed };
|
||||
};
|
||||
const nonblock_bit = 1 << @bitOffsetOf(std.posix.O, "NONBLOCK");
|
||||
_ = std.posix.fcntl(fd, std.posix.F.SETFL, flags | nonblock_bit) catch {
|
||||
return .{ .hole_punch_failed = .all_addresses_failed };
|
||||
};
|
||||
|
||||
// Create and sign hole punch packet
|
||||
var pkt = HolePunchPacket{
|
||||
.connection_id = params.connection_id,
|
||||
.sender_id = self.keypair.public,
|
||||
.timestamp = std.time.milliTimestamp(),
|
||||
.signature = undefined,
|
||||
};
|
||||
const hash = pkt.computeHash();
|
||||
pkt.signature = self.keypair.sign(hash);
|
||||
const packet = pkt.serialize();
|
||||
|
||||
// Send to all target addresses
|
||||
for (target_addresses) |addr| {
|
||||
if (addr.addr_type == .ipv4) {
|
||||
const sock_addr = std.net.Address.initIp4(addr.ip.v4, addr.port);
|
||||
_ = std.posix.sendto(fd, &packet, 0, &sock_addr.any, sock_addr.getOsSockLen()) catch continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for response
|
||||
const deadline = std.time.milliTimestamp() + 2000; // 2 second timeout
|
||||
var recv_buf: [256]u8 = undefined;
|
||||
|
||||
while (std.time.milliTimestamp() < deadline) {
|
||||
var src_addr: std.posix.sockaddr.storage = undefined;
|
||||
var addr_len: std.posix.socklen_t = @sizeOf(@TypeOf(src_addr));
|
||||
|
||||
const len = std.posix.recvfrom(fd, &recv_buf, 0, @ptrCast(&src_addr), &addr_len) catch |err| {
|
||||
if (err == error.WouldBlock) {
|
||||
std.Thread.sleep(1 * std.time.ns_per_ms);
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
|
||||
if (len < 124) continue;
|
||||
|
||||
// Deserialize and verify packet
|
||||
const recv_pkt = HolePunchPacket.deserialize(&recv_buf) catch continue;
|
||||
|
||||
// Verify connection ID
|
||||
if (!std.mem.eql(u8, &recv_pkt.connection_id, ¶ms.connection_id)) continue;
|
||||
|
||||
// Verify signature
|
||||
if (!recv_pkt.verify()) continue;
|
||||
|
||||
// Extract remote address
|
||||
const family = src_addr.family;
|
||||
var remote_address: Address = undefined;
|
||||
if (family == std.posix.AF.INET) {
|
||||
const in_addr: *const std.posix.sockaddr.in = @ptrCast(&src_addr);
|
||||
const ip_bytes: [4]u8 = @bitCast(in_addr.addr);
|
||||
remote_address = Address.initV4(ip_bytes, std.mem.bigToNative(u16, in_addr.port));
|
||||
} else {
|
||||
continue; // Only handle IPv4 for now
|
||||
}
|
||||
|
||||
return .{
|
||||
.success = .{
|
||||
.peer_id = recv_pkt.sender_id,
|
||||
.remote_address = remote_address,
|
||||
.local_address = Address.initV4(.{ 0, 0, 0, 0 }, 0),
|
||||
.connection_id = params.connection_id,
|
||||
.establishment_time_ms = @as(u64, @intCast(std.time.milliTimestamp() - params.rendezvous_time + 500)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return .{ .hole_punch_failed = .timeout };
|
||||
}
|
||||
};
|
||||
|
||||
// Tests
|
||||
test "MWP meeting key is symmetric" {
|
||||
const alice = [_]u8{1} ** 32;
|
||||
const bob = [_]u8{2} ** 32;
|
||||
|
||||
const key1 = MWP.computeMeetingKey(alice, bob);
|
||||
const key2 = MWP.computeMeetingKey(bob, alice);
|
||||
|
||||
try std.testing.expect(std.mem.eql(u8, &key1, &key2));
|
||||
}
|
||||
|
||||
test "KeyPair generation and signing" {
|
||||
const kp = KeyPair.generate();
|
||||
const hash = [_]u8{0xAB} ** 32;
|
||||
const sig = kp.sign(hash);
|
||||
|
||||
// Verify signature
|
||||
const pk = std.crypto.sign.Ed25519.PublicKey.fromBytes(kp.public) catch unreachable;
|
||||
const signature = std.crypto.sign.Ed25519.Signature.fromBytes(sig);
|
||||
try signature.verify(&hash, pk);
|
||||
}
|
||||
Reference in New Issue
Block a user