published IP, resend packets every 500ms instead of single-shot, fix Docker iptables-legacy chains so miniupnpd port mapping fully works without warnings
482 lines
18 KiB
Zig
482 lines
18 KiB
Zig
//! MWP (Mutual Witness Protocol) — Production P2P-integrated API
|
|
//!
|
|
//! This is the production entry point for MWP, wired directly to `*P2P` for
|
|
//! DHT storage, peer discovery, and hole punching. Use this module in real
|
|
//! applications.
|
|
//!
|
|
//! For the standalone core (with `DHTInterface` abstraction for unit testing
|
|
//! with `MockDHT`), see `src/mwp/mutual_witness.zig`.
|
|
//!
|
|
//! 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) {
|
|
// CRITICAL: Must call p2p.update() to process incoming network messages
|
|
// Without this, DHT responses are never received
|
|
self.p2p.update() catch |err| {
|
|
std.log.warn("MWP: p2p.update() failed: {}", .{err});
|
|
};
|
|
|
|
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);
|
|
}
|
|
|
|
/// Connect using an existing publication (for listeners who already published)
|
|
/// Use this when you've already published and found the peer's publication.
|
|
pub fn connectWithPublication(
|
|
self: *MWP,
|
|
our_publication: MeetingPublication,
|
|
peer_publication: MeetingPublication,
|
|
options: ConnectOptions,
|
|
) ConnectionResult {
|
|
// Compute rendezvous params from both publications
|
|
const params = computeRendezvousParamsFromPubs(our_publication, peer_publication, options.rendezvous_buffer_ms);
|
|
|
|
// 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);
|
|
|
|
// CRITICAL: Rendezvous time must be the same for both peers
|
|
// Use the later publication timestamp plus buffer, so both peers agree
|
|
const later_timestamp = @max(our_pub.timestamp, their_pub.timestamp);
|
|
const rendezvous_time = later_timestamp + 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);
|
|
|
|
// Enable address reuse so we can bind even if the port was recently used
|
|
const enable: c_int = 1;
|
|
_ = std.posix.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.REUSEADDR, std.mem.asBytes(&enable)) catch {};
|
|
|
|
// Bind to 0.0.0.0:port so we receive on all interfaces.
|
|
// The published address tells peers where to send; we bind wildcard to receive.
|
|
if (self.our_addresses.len > 0) {
|
|
const our_addr = self.our_addresses[0];
|
|
if (our_addr.addr_type == .ipv4) {
|
|
const bind_addr = std.net.Address.initIp4(.{ 0, 0, 0, 0 }, our_addr.port);
|
|
std.posix.bind(fd, &bind_addr.any, bind_addr.getOsSockLen()) catch |err| {
|
|
std.log.warn("MWP: Failed to bind to published address: {}", .{err});
|
|
// Continue anyway - might work with ephemeral port in some cases
|
|
};
|
|
}
|
|
}
|
|
|
|
// 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-and-receive loop: resend periodically to handle timing jitter.
|
|
// Both peers send at the rendezvous time, but if one peer's packet arrives
|
|
// before the other's socket is bound, it's lost. Resending every 500ms
|
|
// ensures the peer will eventually receive our packet.
|
|
const deadline = std.time.milliTimestamp() + 30000; // 30 second timeout
|
|
var recv_buf: [256]u8 = undefined;
|
|
var last_send: i64 = 0;
|
|
|
|
while (std.time.milliTimestamp() < deadline) {
|
|
// Send (or resend) to all target addresses every 500ms
|
|
const loop_now = std.time.milliTimestamp();
|
|
if (loop_now - last_send >= 500) {
|
|
last_send = loop_now;
|
|
for (target_addresses) |addr| {
|
|
if (addr.addr_type == .ipv4) {
|
|
const sock_addr = std.net.Address.initIp4(addr.ip.v4, addr.port);
|
|
const sent = std.posix.sendto(fd, &packet, 0, &sock_addr.any, sock_addr.getOsSockLen()) catch |err| {
|
|
std.log.warn("MWP: sendto failed: {}", .{err});
|
|
continue;
|
|
};
|
|
std.log.info("MWP: Sent {d} bytes to {d}.{d}.{d}.{d}:{d}", .{
|
|
sent, addr.ip.v4[0], addr.ip.v4[1], addr.ip.v4[2], addr.ip.v4[3], addr.port,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
std.log.warn("MWP: recvfrom error: {}", .{err});
|
|
continue;
|
|
};
|
|
|
|
std.log.info("MWP: Received {d} bytes", .{len});
|
|
|
|
if (len < 124) {
|
|
std.log.warn("MWP: Packet too small: {d} bytes (need 124)", .{len});
|
|
continue;
|
|
}
|
|
|
|
// Deserialize and verify packet
|
|
const recv_pkt = HolePunchPacket.deserialize(&recv_buf) catch |err| {
|
|
std.log.warn("MWP: Failed to deserialize packet: {}", .{err});
|
|
continue;
|
|
};
|
|
|
|
// Verify connection ID
|
|
if (!std.mem.eql(u8, &recv_pkt.connection_id, ¶ms.connection_id)) {
|
|
std.log.warn("MWP: Connection ID mismatch", .{});
|
|
continue;
|
|
}
|
|
|
|
// Verify signature
|
|
if (!recv_pkt.verify()) {
|
|
std.log.warn("MWP: Signature verification failed", .{});
|
|
continue;
|
|
}
|
|
|
|
std.log.info("MWP: Packet verified successfully!", .{});
|
|
|
|
// 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);
|
|
}
|