create Mutual Witness Protocol specs and implementation. mwp aims to be

a zero-infrastructure NAT traversal
This commit is contained in:
2026-02-07 18:01:12 -03:00
parent 2b7ab5f570
commit abb398d363
22 changed files with 4656 additions and 51 deletions

404
examples/mwp_demo.zig Normal file
View File

@@ -0,0 +1,404 @@
//! MWP (Mutual Witness Protocol) Demo
//!
//! Demonstrates NAT traversal and peer discovery using MWP with zig-p2p's DHT.
//!
//! Usage:
//! # Terminal 1 (Alice - starts network):
//! zig-out/bin/mwp-demo --name alice --port 9000
//!
//! # Terminal 2 (Bob - joins and connects to Alice):
//! zig-out/bin/mwp-demo --name bob --port 9010 \
//! --bootstrap 127.0.0.1:9000 --peer <alice_mwp_pubkey>
//!
//! How it works:
//! 1. Both peers join the same P2P/DHT network
//! 2. Each publishes their MWP availability to the DHT
//! 3. MWP coordinates simultaneous hole punch attempts
//! 4. Direct connection established without central servers!
const std = @import("std");
const p2p = @import("p2p");
const mwp = @import("mwp");
const Allocator = std.mem.Allocator;
const P2P = p2p.P2P;
/// Generate deterministic keypair from seed (for testing)
fn deterministicKeypair(seed: []const u8) mwp.KeyPair {
var seed_hash: [32]u8 = undefined;
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
hasher.update("mwp-test-keypair-v1");
hasher.update(seed);
hasher.final(&seed_hash);
// Use seed to generate Ed25519 keypair
const kp = std.crypto.sign.Ed25519.KeyPair.generateDeterministic(seed_hash) catch unreachable;
return .{
.public = kp.public_key.toBytes(),
.secret = kp.secret_key.toBytes(),
};
}
fn formatHex(bytes: []const u8, buf: []u8) []u8 {
const charset = "0123456789abcdef";
for (bytes, 0..) |b, i| {
buf[i * 2] = charset[b >> 4];
buf[i * 2 + 1] = charset[b & 0x0f];
}
return buf[0 .. bytes.len * 2];
}
fn parseHex(hex: []const u8, out: []u8) !void {
if (hex.len != out.len * 2) return error.InvalidLength;
for (0..out.len) |i| {
out[i] = std.fmt.parseInt(u8, hex[i * 2 ..][0..2], 16) catch return error.InvalidHex;
}
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Parse arguments
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
var name: []const u8 = "peer";
var port: u16 = 9000;
var bootstrap_addr: ?[]const u8 = null;
var target_pubkey: ?[32]u8 = null;
var bootstrap_dht_id: ?[32]u8 = null; // DHT node ID is 32 bytes
var deterministic_keys: bool = false;
var target_name: ?[]const u8 = null; // For deterministic key lookup
_ = args.next(); // Skip program name
while (args.next()) |arg| {
if (std.mem.eql(u8, arg, "--name")) {
name = args.next() orelse return error.MissingArg;
} else if (std.mem.eql(u8, arg, "--port")) {
const port_str = args.next() orelse return error.MissingArg;
port = try std.fmt.parseInt(u16, port_str, 10);
} else if (std.mem.eql(u8, arg, "--bootstrap")) {
bootstrap_addr = args.next() orelse return error.MissingArg;
} else if (std.mem.eql(u8, arg, "--peer")) {
const hex = args.next() orelse return error.MissingArg;
target_pubkey = [_]u8{0} ** 32;
try parseHex(hex, &target_pubkey.?);
} else if (std.mem.eql(u8, arg, "--dht-id")) {
const hex = args.next() orelse return error.MissingArg;
bootstrap_dht_id = [_]u8{0} ** 32;
try parseHex(hex, &bootstrap_dht_id.?);
} else if (std.mem.eql(u8, arg, "--deterministic")) {
deterministic_keys = true;
} else if (std.mem.eql(u8, arg, "--connect-to")) {
target_name = args.next() orelse return error.MissingArg;
} else if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
std.debug.print(
\\MWP Demo - Mutual Witness Protocol for NAT Traversal
\\
\\Usage:
\\ mwp-demo [options]
\\
\\Options:
\\ --name <name> Peer name (default: peer)
\\ --port <port> P2P listen port (default: 9000)
\\ --bootstrap <addr> Bootstrap node address (e.g., 127.0.0.1:9000)
\\ --dht-id <id> Bootstrap node's DHT node ID (64 hex chars)
\\ --peer <pubkey> Target peer's MWP public key (64 hex chars)
\\ --deterministic Use deterministic keys based on --name (for testing)
\\ --connect-to <name> With --deterministic, auto-compute target's pubkey
\\ --help, -h Show this help
\\
\\Examples:
\\ # Deterministic keys (easiest for testing):
\\ Terminal 1: mwp-demo --name alice --port 18100 --deterministic --connect-to bob
\\ Terminal 2: mwp-demo --name bob --port 18200 --deterministic --connect-to alice \
\\ --bootstrap 127.0.0.1:18100 --dht-id <alice_dht_id>
\\
\\ # Manual keys:
\\ Terminal 1: mwp-demo --name alice --port 9000
\\ Terminal 2: mwp-demo --name bob --port 9010 --bootstrap 127.0.0.1:9000 \
\\ --dht-id <alice_dht_id> --peer <alice_mwp_key>
\\
, .{});
return;
}
}
std.debug.print("\n", .{});
std.debug.print("╔════════════════════════════════════════════════════╗\n", .{});
std.debug.print("║ MWP - Mutual Witness Protocol Demo ║\n", .{});
std.debug.print("║ Zero-Infrastructure NAT Traversal ║\n", .{});
std.debug.print("╚════════════════════════════════════════════════════╝\n", .{});
std.debug.print("\n", .{});
// =========================================
// Step 1: Initialize P2P Network
// =========================================
std.debug.print("[1/4] Initializing P2P network...\n", .{});
var config = p2p.P2PConfig{};
config.network.listen_port = port;
config.network.enable_noise_encryption = true; // Enable for DHT ID exchange
var p2p_node = try P2P.init(allocator, config);
defer p2p_node.deinit();
try p2p_node.start();
// Start listening for incoming connections
const listen_addr = p2p.Address.ipv4(.{ 127, 0, 0, 1 }, port);
try p2p_node.startListening(listen_addr);
std.debug.print(" P2P node listening on port {d}\n", .{port});
// Get our local DHT ID
const local_dht_id = p2p_node.getDhtLocalId() orelse {
std.debug.print(" ERROR: No DHT ID available\n", .{});
return error.DhtNotInitialized;
};
var dht_id_hex: [64]u8 = undefined;
_ = formatHex(&local_dht_id, &dht_id_hex);
std.debug.print(" DHT Node ID: {s}\n", .{dht_id_hex});
// Bootstrap if address provided
if (bootstrap_addr) |addr| {
std.debug.print(" Connecting to bootstrap node: {s}\n", .{addr});
// Parse bootstrap address
var parts = std.mem.splitScalar(u8, addr, ':');
const host = parts.next() orelse return error.InvalidBootstrap;
const port_str = parts.next() orelse return error.InvalidBootstrap;
const boot_port = try std.fmt.parseInt(u16, port_str, 10);
// Parse IP
var ip_parts = std.mem.splitScalar(u8, host, '.');
var ip: [4]u8 = undefined;
for (0..4) |i| {
const octet = ip_parts.next() orelse return error.InvalidIP;
ip[i] = try std.fmt.parseInt(u8, octet, 10);
}
const boot_addr = p2p.Address.ipv4(ip, boot_port);
const connection_peer_id = p2p_node.connectToPeer(boot_addr) catch |err| {
std.debug.print(" Warning: Bootstrap connection failed: {}\n", .{err});
return err;
};
std.debug.print(" Connected! Peer ID: {x}\n", .{connection_peer_id.bytes[0..4].*});
// Register DHT node ID mapping if provided
if (bootstrap_dht_id) |remote_dht_id| {
std.debug.print(" Registering DHT peer mapping...\n", .{});
try p2p_node.registerDhtNodeId(remote_dht_id, connection_peer_id);
p2p_node.dhtAddPeer(remote_dht_id, boot_addr) catch |err| {
std.debug.print(" Warning: Failed to add DHT peer: {}\n", .{err});
};
std.debug.print(" DHT peer registered!\n", .{});
} else {
std.debug.print(" Note: No --dht-id provided, DHT peer not registered\n", .{});
}
// Process messages to establish DHT
std.debug.print(" Processing DHT messages...\n", .{});
for (0..20) |_| {
try p2p_node.update();
std.Thread.sleep(50 * std.time.ns_per_ms);
}
}
const dht_peers = p2p_node.getDhtPeerCount();
std.debug.print(" DHT peer count: {d}\n", .{dht_peers});
// =========================================
// Step 2: Initialize MWP
// =========================================
std.debug.print("\n[2/4] Initializing MWP...\n", .{});
// Compute our keypair (deterministic or random)
const our_keypair = if (deterministic_keys)
deterministicKeypair(name)
else
null;
// If using deterministic keys with --connect-to, compute target's pubkey
if (deterministic_keys and target_name != null) {
const target_kp = deterministicKeypair(target_name.?);
target_pubkey = target_kp.public;
std.debug.print(" Computed target pubkey for '{s}'\n", .{target_name.?});
}
// Get our addresses for MWP
var mwp_addrs: [1]mwp.Address = undefined;
mwp_addrs[0] = mwp.Address.initV4(.{ 127, 0, 0, 1 }, port + 1);
var mwp_node = try mwp.MWP.init(allocator, &p2p_node, .{
.keypair = our_keypair,
.addresses = &mwp_addrs,
.default_ttl = 300,
});
defer mwp_node.deinit();
const our_pubkey = mwp_node.getPublicKey();
var pubkey_hex: [64]u8 = undefined;
_ = formatHex(&our_pubkey, &pubkey_hex);
std.debug.print(" Name: {s}\n", .{name});
std.debug.print(" MWP Public Key:\n", .{});
std.debug.print(" {s}\n", .{pubkey_hex});
// =========================================
// Step 3: Publish or Connect
// =========================================
// If we have both target AND bootstrap: initiate connection
// If we have target but no bootstrap: wait and publish for target
// If we have no target: just wait
if (target_pubkey != null and bootstrap_addr != null) {
// Initiator mode: connect to target
const target = target_pubkey.?;
std.debug.print("\n[3/4] Connecting to peer...\n", .{});
var target_hex: [64]u8 = undefined;
_ = formatHex(&target, &target_hex);
std.debug.print(" Target: {s}\n", .{target_hex});
// Compute meeting key for debugging
const meeting_key = mwp.MWP.computeMeetingKey(our_pubkey, target);
var meeting_hex: [64]u8 = undefined;
_ = formatHex(&meeting_key, &meeting_hex);
std.debug.print(" Meeting key: {s}\n", .{meeting_hex});
// Publish our availability
std.debug.print("\n Publishing availability to DHT...\n", .{});
_ = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
return;
};
std.debug.print(" Published!\n", .{});
// Try to connect
std.debug.print("\n Attempting connection (30s timeout)...\n", .{});
const result = mwp_node.connect(target, .{
.timeout_ms = 30_000,
});
std.debug.print("\n[4/4] Result:\n", .{});
switch (result) {
.success => |info| {
std.debug.print(" ✓ CONNECTION ESTABLISHED!\n", .{});
std.debug.print(" Remote: {d}.{d}.{d}.{d}:{d}\n", .{
info.remote_address.ip.v4[0],
info.remote_address.ip.v4[1],
info.remote_address.ip.v4[2],
info.remote_address.ip.v4[3],
info.remote_address.port,
});
std.debug.print(" Time: {d}ms\n", .{info.establishment_time_ms});
},
.peer_not_found => {
std.debug.print(" ✗ Peer not found in DHT\n", .{});
std.debug.print(" Make sure the peer is online and has published.\n", .{});
},
.timeout => {
std.debug.print(" ✗ Timeout waiting for peer\n", .{});
std.debug.print(" The peer may not be online or reachable.\n", .{});
},
.hole_punch_failed => |err| {
std.debug.print(" ✗ Hole punch failed: {s}\n", .{@tagName(err)});
},
.other_error => |err| {
std.debug.print(" ✗ Error: {s}\n", .{@errorName(err)});
},
}
} else if (target_pubkey) |target| {
// Listener mode with known target: publish and wait for connection
std.debug.print("\n[3/4] Publishing and waiting for peer...\n", .{});
var target_hex: [64]u8 = undefined;
_ = formatHex(&target, &target_hex);
std.debug.print(" Expected peer: {s}\n", .{target_hex});
const meeting_key = mwp.MWP.computeMeetingKey(our_pubkey, target);
var meeting_hex: [64]u8 = undefined;
_ = formatHex(&meeting_key, &meeting_hex);
std.debug.print(" Meeting key: {s}\n", .{meeting_hex});
std.debug.print("\n Other peer should use:\n", .{});
std.debug.print(" --bootstrap 127.0.0.1:{d} --dht-id {s} --connect-to {s}\n", .{ port, dht_id_hex, name });
std.debug.print("\n[4/4] Publishing and listening...\n", .{});
std.debug.print(" (Press Ctrl+C to exit)\n\n", .{});
// Publish immediately on startup
std.debug.print(" Initial publish...\n", .{});
_ = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
};
std.debug.print(" Published!\n", .{});
var last_publish: i64 = std.time.milliTimestamp();
var last_heartbeat: i64 = std.time.milliTimestamp();
while (true) {
try p2p_node.update();
const now = std.time.milliTimestamp();
// Publish every 30 seconds
if (now - last_publish >= 30000) {
last_publish = now;
_ = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
};
// Also try to find peer's publication
if (mwp_node.findPeer(target) catch null) |pub_data| {
std.debug.print("\n ✓ FOUND PEER PUBLICATION!\n", .{});
std.debug.print(" Peer is at {d}.{d}.{d}.{d}:{d}\n", .{
pub_data.addresses[0].ip.v4[0],
pub_data.addresses[0].ip.v4[1],
pub_data.addresses[0].ip.v4[2],
pub_data.addresses[0].ip.v4[3],
pub_data.addresses[0].port,
});
break;
}
}
// Heartbeat every 5 seconds
if (now - last_heartbeat >= 5000) {
last_heartbeat = now;
const dht_count = p2p_node.getDhtPeerCount();
std.debug.print(" [heartbeat] DHT peers: {d}\n", .{dht_count});
}
std.Thread.sleep(10 * std.time.ns_per_ms);
}
} else {
std.debug.print("\n[3/4] Waiting for connections...\n", .{});
std.debug.print("\n Share your MWP public key with peers:\n", .{});
std.debug.print(" {s}\n", .{pubkey_hex});
std.debug.print("\n Other peers can connect with:\n", .{});
std.debug.print(" --bootstrap 127.0.0.1:{d} --dht-id {s} --peer {s}\n", .{ port, dht_id_hex, pubkey_hex });
std.debug.print("\n[4/4] Listening...\n", .{});
std.debug.print(" (Press Ctrl+C to exit)\n\n", .{});
// Main loop: process P2P events and print heartbeat
var last_heartbeat: i64 = std.time.milliTimestamp();
while (true) {
// Process incoming connections and messages
try p2p_node.update();
// Heartbeat every 5 seconds
const now = std.time.milliTimestamp();
if (now - last_heartbeat >= 5000) {
last_heartbeat = now;
const dht_count = p2p_node.getDhtPeerCount();
std.debug.print(" [heartbeat] DHT peers: {d}\n", .{dht_count});
}
// Sleep briefly to avoid busy loop
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
}