Files
zigp2p/examples/mwp_demo.zig

556 lines
25 KiB
Zig

//! 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
var public_ip: ?[4]u8 = null; // Explicit public IP for NAT environments
_ = 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, "--public-ip")) {
// Parse IP address (e.g., "10.201.0.20")
const ip_str = args.next() orelse return error.MissingArg;
var ip_parts = std.mem.splitScalar(u8, ip_str, '.');
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);
}
public_ip = ip;
} 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
\\ --public-ip <ip> Public IP address (for NAT/Docker, e.g., 10.201.0.20)
\\ --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 (0.0.0.0 to accept from all interfaces)
const listen_addr = p2p.Address.ipv4(.{ 0, 0, 0, 0 }, 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);
if (p2p_node.connectToPeer(boot_addr)) |connection_peer_id| {
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", .{});
}
// Trigger a DHT lookup to test IP Reflection
std.debug.print(" Sending DHT FIND_VALUE to trigger IP Reflection...\n", .{});
const test_key: [32]u8 = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ++ [_]u8{0} ** 28;
_ = p2p_node.dhtFindValue(test_key) catch |err| {
std.debug.print(" DHT lookup result: {} (expected if key not found)\n", .{err});
};
// Process messages to receive the response
std.debug.print(" Processing DHT response...\n", .{});
for (0..30) |_| {
try p2p_node.update();
std.Thread.sleep(50 * std.time.ns_per_ms);
}
// Check for IP Reflection results (Bundled STUN)
if (p2p_node.getObservedPublicAddress()) |observed| {
std.debug.print("\n ┌─────────────────────────────────────────┐\n", .{});
std.debug.print(" │ IP REFLECTION (Bundled STUN) SUCCESS! │\n", .{});
std.debug.print(" └─────────────────────────────────────────┘\n", .{});
switch (observed.ip) {
.v4 => |obs_ip| std.debug.print(" Discovered public address: {d}.{d}.{d}.{d}:{d}\n", .{ obs_ip[0], obs_ip[1], obs_ip[2], obs_ip[3], observed.port }),
.v6 => std.debug.print(" Discovered public IPv6 address (port {d})\n", .{observed.port}),
}
std.debug.print(" (Learned from DHT peer without any STUN server!)\n\n", .{});
} else {
std.debug.print(" No observed address yet (IP Reflection pending)\n", .{});
}
} else |err| {
std.debug.print(" Warning: Bootstrap connection failed: {} (will accept incoming connections)\n", .{err});
}
}
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", .{});
// In listener mode (target but no bootstrap), wait for incoming peer connection
// to learn our address via IP Reflection
// Check both target_pubkey (from --peer) and target_name (from --connect-to)
if ((target_pubkey != null or target_name != null) and bootstrap_addr == null) {
std.debug.print(" Listener mode: waiting for incoming peer connection...\n", .{});
const wait_start = std.time.milliTimestamp();
while (std.time.milliTimestamp() - wait_start < 30000) {
try p2p_node.update();
// Check if we got any observed addresses (from processing incoming DHT messages)
const all_obs = p2p_node.getAllObservedAddresses(allocator) catch &[_]p2p.ObservedAddress{};
defer if (all_obs.len > 0) allocator.free(all_obs);
if (all_obs.len > 0) {
std.debug.print(" Got observed address from peer!\n", .{});
break;
}
std.Thread.sleep(100 * std.time.ns_per_ms);
}
}
// 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 - prefer explicit --public-ip, then observed address
var mwp_addrs: [1]mwp.Address = undefined;
var found_addr = false;
// First priority: explicit --public-ip option (for NAT/Docker)
if (public_ip) |ip| {
mwp_addrs[0] = mwp.Address.initV4(ip, port + 1);
std.debug.print(" Using explicit public IP: {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], port + 1 });
found_addr = true;
}
// Second priority: NAT-PMP (automatic port mapping)
if (!found_addr) {
if (p2p_node.tryNatPmpDiscovery(@intCast(port + 1), 3600)) |external_ip| {
mwp_addrs[0] = mwp.Address.initV4(external_ip, port + 1);
std.debug.print(" Using NAT-PMP: {d}.{d}.{d}.{d}:{d}\n", .{ external_ip[0], external_ip[1], external_ip[2], external_ip[3], port + 1 });
found_addr = true;
}
}
// Third priority: UPnP IGD (automatic port mapping for most consumer routers)
if (!found_addr) {
if (p2p_node.tryUpnpDiscovery(@intCast(port + 1), 3600)) |external_ip| {
mwp_addrs[0] = mwp.Address.initV4(external_ip, port + 1);
std.debug.print(" Using UPnP IGD: {d}.{d}.{d}.{d}:{d}\n", .{ external_ip[0], external_ip[1], external_ip[2], external_ip[3], port + 1 });
found_addr = true;
}
}
// Fourth priority: consensus address from IP Reflection (multi-source)
if (!found_addr) {
const consensus = p2p_node.getConsensusAddress();
if (consensus.address) |observed| {
switch (observed.ip) {
.v4 => |ip| {
// Skip loopback
if (ip[0] != 127) {
mwp_addrs[0] = mwp.Address.initV4(ip, port + 1);
const confidence_str = switch (consensus.confidence) {
.none => "none",
.single_source => "single source (unverified)",
.consensus => "VERIFIED (multi-source consensus)",
.conflict => "CONFLICT (using majority)",
};
std.debug.print(" Using IP from IP Reflection: {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], port + 1 });
std.debug.print(" Confidence: {s} ({d}/{d} observers)\n", .{ confidence_str, consensus.observer_count, consensus.total_observers });
found_addr = true;
}
},
.v6 => {},
}
}
}
// Final fallback to localhost
if (!found_addr) {
std.debug.print(" No observed IP, using localhost (127.0.0.1:{d})\n", .{port + 1});
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 - SAVE the publication for later use
std.debug.print(" Initial publish...\n", .{});
const our_publication = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
return;
};
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();
// Check for peer every 2 seconds (don't re-publish to keep same nonce)
if (now - last_publish >= 2000) {
last_publish = now;
// Try to find peer's publication and connect
if (mwp_node.findPeer(target) catch null) |pub_data| {
defer {
var pd = pub_data;
pd.deinit(allocator);
}
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,
});
std.debug.print(" Initiating hole punch...\n", .{});
// Use connectWithPublication to use our EXISTING publication
const result = mwp_node.connectWithPublication(our_publication, pub_data, .{
.timeout_ms = 10_000,
});
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,
});
},
.hole_punch_failed => |err| {
std.debug.print(" ✗ Hole punch failed: {s}\n", .{@tagName(err)});
},
.timeout => {
std.debug.print(" ✗ Connection timeout\n", .{});
},
else => {
std.debug.print(" ✗ Connection failed\n", .{});
},
}
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();
// Show IP Reflection status (Bundled STUN)
if (p2p_node.getObservedPublicAddress()) |observed| {
switch (observed.ip) {
.v4 => |obs_ip| std.debug.print(" [heartbeat] DHT peers: {d}, Public IP: {d}.{d}.{d}.{d}:{d}\n", .{ dht_count, obs_ip[0], obs_ip[1], obs_ip[2], obs_ip[3], observed.port }),
.v6 => std.debug.print(" [heartbeat] DHT peers: {d}, Public IPv6 (port {d})\n", .{ dht_count, observed.port }),
}
} else {
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);
}
}
}