bidirectional ip reflection for listener address discovery

This commit is contained in:
2026-02-09 16:02:23 -03:00
parent 59e9e420be
commit 7b47ef155c
31 changed files with 3192 additions and 269 deletions

View File

@@ -71,6 +71,7 @@ pub fn main() !void {
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| {
@@ -93,6 +94,16 @@ pub fn main() !void {
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
@@ -108,6 +119,7 @@ pub fn main() !void {
\\ --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:
@@ -147,8 +159,8 @@ pub fn main() !void {
try p2p_node.start();
// Start listening for incoming connections
const listen_addr = p2p.Address.ipv4(.{ 127, 0, 0, 1 }, port);
// 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});
@@ -180,29 +192,50 @@ pub fn main() !void {
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].*});
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});
// 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});
};
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);
// 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});
}
}
@@ -214,6 +247,29 @@ pub fn main() !void {
// =========================================
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)
@@ -227,9 +283,47 @@ pub fn main() !void {
std.debug.print(" Computed target pubkey for '{s}'\n", .{target_name.?});
}
// Get our addresses for MWP
// Get our addresses for MWP - prefer explicit --public-ip, then observed address
var mwp_addrs: [1]mwp.Address = undefined;
mwp_addrs[0] = mwp.Address.initV4(.{ 127, 0, 0, 1 }, port + 1);
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: 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,
@@ -328,10 +422,11 @@ pub fn main() !void {
std.debug.print("\n[4/4] Publishing and listening...\n", .{});
std.debug.print(" (Press Ctrl+C to exit)\n\n", .{});
// Publish immediately on startup
// Publish immediately on startup - SAVE the publication for later use
std.debug.print(" Initial publish...\n", .{});
_ = mwp_node.publishFor(target, 300) catch |err| {
const our_publication = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
return;
};
std.debug.print(" Published!\n", .{});
@@ -343,15 +438,16 @@ pub fn main() !void {
const now = std.time.milliTimestamp();
// Publish every 30 seconds
if (now - last_publish >= 30000) {
// Check for peer every 2 seconds (don't re-publish to keep same nonce)
if (now - last_publish >= 2000) {
last_publish = now;
_ = mwp_node.publishFor(target, 300) catch |err| {
std.debug.print(" Error publishing: {}\n", .{err});
};
// Also try to find peer's publication
// 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],
@@ -360,6 +456,34 @@ pub fn main() !void {
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;
}
}
@@ -394,7 +518,16 @@ pub fn main() !void {
if (now - last_heartbeat >= 5000) {
last_heartbeat = now;
const dht_count = p2p_node.getDhtPeerCount();
std.debug.print(" [heartbeat] DHT peers: {d}\n", .{dht_count});
// 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