add bootstrap node, MWP peer discovery, and DNS resolution

This commit is contained in:
2026-02-19 17:45:32 -03:00
parent 6b8067ce9b
commit 3150b3be5a
4 changed files with 742 additions and 9 deletions

363
examples/bootstrap_node.zig Normal file
View File

@@ -0,0 +1,363 @@
//! Headless Bootstrap / MWP Peer Node
//!
//! Can act as a DHT bootstrap relay OR as a peer that discovers and connects
//! via MWP hole punching. No TUI — just stdout logging.
//!
//! Bootstrap mode:
//! bootstrap-node --port 19000
//!
//! Peer mode (connects via MWP):
//! bootstrap-node --port 19001 --name alice --bootstrap VPS:19000 --mwp-connect bob
const std = @import("std");
const p2p_lib = @import("p2p");
const core = @import("core");
const network = @import("network");
const mwp_mod = @import("mwp");
const P2P = p2p_lib.P2P;
const P2PConfig = p2p_lib.P2PConfig;
const coreAddress = core.Address;
const APP_ID_DHT_EXCHANGE: u8 = 0x30;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
var port: u16 = 19000;
var bootstrap_addr: ?[]const u8 = null;
var name: []const u8 = "bootstrap";
var mwp_target_name: ?[]const u8 = null;
var i: usize = 1;
while (i < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--port") and i + 1 < args.len) {
i += 1;
port = std.fmt.parseInt(u16, args[i], 10) catch {
std.debug.print("Invalid port\n", .{});
return;
};
} else if (std.mem.eql(u8, args[i], "--bootstrap") and i + 1 < args.len) {
i += 1;
bootstrap_addr = args[i];
} else if (std.mem.eql(u8, args[i], "--name") and i + 1 < args.len) {
i += 1;
name = args[i];
} else if (std.mem.eql(u8, args[i], "--mwp-connect") and i + 1 < args.len) {
i += 1;
mwp_target_name = args[i];
} else if (std.mem.eql(u8, args[i], "--help") or std.mem.eql(u8, args[i], "-h")) {
std.debug.print(
\\Bootstrap / MWP Peer Node — Headless DHT/MWP for zig-p2p
\\
\\Usage: bootstrap-node [OPTIONS]
\\
\\Options:
\\ --port PORT Listen port (default: 19000)
\\ --name NAME Peer name for MWP keypair (default: bootstrap)
\\ --bootstrap HOST:PORT Connect to bootstrap node
\\ --mwp-connect NAME Target peer name for MWP discovery
\\
, .{});
return;
}
}
// P2P init
var config = P2PConfig.default();
config.network.listen_port = 0; // UDP on ephemeral port
config.network.enable_noise_encryption = true;
var p2p = try P2P.init(allocator, config);
defer p2p.deinit();
try p2p.start();
const listen_addr = coreAddress.ipv4(.{ 0, 0, 0, 0 }, port);
try p2p.startListening(listen_addr);
std.debug.print("bootstrap listening on :{d} (name={s})\n", .{ port, name });
// Connect to another bootstrap if specified
if (bootstrap_addr) |addr| {
if (parseHostPort(addr)) |hp| {
const boot_addr = coreAddress.ipv4(hp.host, hp.port);
std.debug.print("connecting to {s}...\n", .{addr});
if (p2p.connectToPeer(boot_addr)) |cpid| {
if (p2p.getDhtLocalId()) |our_id| {
_ = p2p.sendMessage(cpid, APP_ID_DHT_EXCHANGE, &our_id) catch {};
}
// Wait for DHT exchange
var got_it = false;
for (0..60) |_| {
p2p.update() catch {};
while (p2p.getNextEvent()) |ev| {
var event = ev;
defer event.deinit();
switch (event.data) {
.message_received => |msg| {
if (msg.message_type == APP_ID_DHT_EXCHANGE and msg.data.len == 32) {
var remote_id: [32]u8 = undefined;
@memcpy(&remote_id, msg.data[0..32]);
p2p.registerDhtNodeId(remote_id, msg.source) catch {};
p2p.dhtAddPeer(remote_id, boot_addr) catch {};
got_it = true;
}
},
else => {},
}
}
if (got_it) break;
std.Thread.sleep(50 * std.time.ns_per_ms);
}
// Trigger IP Reflection via DHT lookup
if (got_it) {
std.debug.print("connected + DHT exchange OK, triggering IP reflection\n", .{});
const dummy_key: [32]u8 = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ++ [_]u8{0} ** 28;
_ = p2p.dhtFindValue(dummy_key) catch {};
for (0..30) |_| {
p2p.update() catch {};
std.Thread.sleep(50 * std.time.ns_per_ms);
}
} else {
std.debug.print("connected but no DHT exchange\n", .{});
}
} else |err| {
std.debug.print("connection failed: {}\n", .{err});
}
}
}
// Initialize MWP if --mwp-connect is set
var mwp_node: ?*mwp_mod.MWP = null;
var mwp_target_pubkey: ?[32]u8 = null;
const mwp_port: u16 = if (port > 0) port + 1 else 9001;
var mwp_addrs: [1]mwp_mod.Address = .{mwp_mod.Address.initV4(.{ 127, 0, 0, 1 }, mwp_port)};
defer if (mwp_node) |m| m.deinit();
if (mwp_target_name != null or bootstrap_addr != null) {
const keypair = deterministicKeypair(name);
if (mwp_target_name) |target_name| {
const target_kp = deterministicKeypair(target_name);
mwp_target_pubkey = target_kp.public;
}
// Try to get observed public address from IP Reflection
if (p2p.getObservedPublicAddress()) |observed| {
switch (observed.ip) {
.v4 => |ip| {
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
std.debug.print("MWP: Using IP Reflection address {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], mwp_port });
},
.v6 => {},
}
} else {
std.debug.print("MWP: No public address yet, using 127.0.0.1:{d}\n", .{mwp_port});
}
mwp_node = mwp_mod.MWP.init(allocator, &p2p, .{
.keypair = keypair,
.addresses = &mwp_addrs,
}) catch |err| blk: {
std.debug.print("MWP init failed: {s}\n", .{@errorName(err)});
break :blk null;
};
if (mwp_node != null) {
var pk_hex: [64]u8 = undefined;
_ = formatHex(&keypair.public, &pk_hex);
std.debug.print("MWP initialized, pubkey: {s}\n", .{pk_hex});
}
}
// MWP state machine
const MwpState = enum { idle, published, searching, done };
var mwp_state: MwpState = .idle;
var mwp_publication: ?mwp_mod.MeetingPublication = null;
var mwp_last_search: i64 = 0;
var peer_count: usize = 0;
// Main loop
while (true) {
p2p.update() catch {};
while (p2p.getNextEvent()) |ev| {
var event = ev;
defer event.deinit();
switch (event.data) {
.peer_connected => |pc| {
peer_count += 1;
if (p2p.getDhtLocalId()) |our_id| {
_ = p2p.sendMessage(pc.peer_id, APP_ID_DHT_EXCHANGE, &our_id) catch {};
}
std.debug.print("[+] peer connected (total: {d})\n", .{peer_count});
},
.connection_established => |ce| {
peer_count += 1;
if (p2p.getDhtLocalId()) |our_id| {
_ = p2p.sendMessage(ce.peer_id, APP_ID_DHT_EXCHANGE, &our_id) catch {};
}
std.debug.print("[+] peer connected outbound (total: {d})\n", .{peer_count});
},
.message_received => |msg| {
if (msg.message_type == APP_ID_DHT_EXCHANGE and msg.data.len == 32) {
var remote_id: [32]u8 = undefined;
@memcpy(&remote_id, msg.data[0..32]);
p2p.registerDhtNodeId(remote_id, msg.source) catch {};
std.debug.print("[dht] registered peer\n", .{});
}
},
.peer_disconnected => |pd| {
if (peer_count > 0) peer_count -= 1;
std.debug.print("[-] peer disconnected: {s} (total: {d})\n", .{ pd.reason, peer_count });
},
else => {},
}
}
// MWP peer discovery state machine
if (mwp_node) |m| {
if (mwp_target_pubkey) |target_pk| {
const now = std.time.milliTimestamp();
switch (mwp_state) {
.idle => {
// Update MWP address from IP Reflection before publishing
if (p2p.getObservedPublicAddress()) |observed| {
switch (observed.ip) {
.v4 => |ip| {
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
std.debug.print("MWP: Updated address to {d}.{d}.{d}.{d}:{d}\n", .{ ip[0], ip[1], ip[2], ip[3], mwp_port });
},
.v6 => {},
}
}
// Publish our availability
if (m.publishFor(target_pk, 300)) |pub_data| {
mwp_publication = pub_data;
mwp_state = .published;
std.debug.print("MWP: Published availability, searching for peer...\n", .{});
} else |err| {
std.debug.print("MWP: Failed to publish: {s}\n", .{@errorName(err)});
}
},
.published, .searching => {
mwp_state = .searching;
if (now - mwp_last_search >= 2000) {
mwp_last_search = now;
if (m.findPeer(target_pk) catch null) |peer_pub| {
std.debug.print("MWP: Found peer! Attempting hole punch...\n", .{});
const result = m.connectWithPublication(
mwp_publication.?,
peer_pub,
.{ .timeout_ms = 10_000 },
);
var pub_copy = peer_pub;
pub_copy.deinit(allocator);
switch (result) {
.success => |info| {
const remote = coreAddress.ipv4(
info.remote_address.ip.v4,
info.remote_address.port,
);
std.debug.print("MWP: Hole punch OK! Connecting to {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,
});
p2p.startNonBlockingConnect(remote) catch {};
mwp_state = .done;
},
.timeout => {
std.debug.print("MWP: Hole punch timeout, retrying...\n", .{});
if (m.publishFor(target_pk, 300)) |new_pub| {
mwp_publication = new_pub;
mwp_state = .published;
} else |_| {}
},
.hole_punch_failed => |err| {
std.debug.print("MWP: Hole punch failed: {s}\n", .{@tagName(err)});
},
.peer_not_found => {
std.debug.print("MWP: Peer not found\n", .{});
},
.other_error => |err| {
std.debug.print("MWP: Error: {s}\n", .{@errorName(err)});
},
}
}
}
},
.done => {},
}
}
}
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
fn deterministicKeypair(seed: []const u8) mwp_mod.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);
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, idx| {
buf[idx * 2] = charset[b >> 4];
buf[idx * 2 + 1] = charset[b & 0x0f];
}
return buf[0 .. bytes.len * 2];
}
fn parseHostPort(s: []const u8) ?struct { host: [4]u8, port: u16 } {
const colon_idx = std.mem.lastIndexOfScalar(u8, s, ':') orelse return null;
const host_str = s[0..colon_idx];
const port_str = s[colon_idx + 1 ..];
const port = std.fmt.parseInt(u16, port_str, 10) catch return null;
// Try IPv4 dotted notation first
var parts: [4]u8 = undefined;
var iter = std.mem.splitScalar(u8, host_str, '.');
var idx: usize = 0;
var is_ip = true;
while (iter.next()) |part| {
if (idx >= 4) { is_ip = false; break; }
parts[idx] = std.fmt.parseInt(u8, part, 10) catch { is_ip = false; break; };
idx += 1;
}
if (is_ip and idx == 4) return .{ .host = parts, .port = port };
// Fall back to DNS resolution
var gpa_alloc = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_alloc.deinit();
const list = std.net.getAddressList(gpa_alloc.allocator(), host_str, port) catch return null;
defer list.deinit();
for (list.addrs) |addr| {
if (addr.any.family == std.posix.AF.INET) {
const bytes = @as(*const [4]u8, @ptrCast(&addr.in.sa.addr));
return .{ .host = bytes.*, .port = port };
}
}
return null;
}