refactor MWP: platform abstractions

This commit is contained in:
2026-02-19 11:36:27 -03:00
parent 7b120731a6
commit 3da00503a2
4 changed files with 73 additions and 42 deletions

View File

@@ -3,9 +3,13 @@
//! Handles the actual NAT traversal via simultaneous connection attempts.
const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const platform = @import("platform");
const platform_time = platform.time;
const types = @import("types.zig");
const Allocator = std.mem.Allocator;
const os = std.os;
const os = if (!is_wasm) std.os else struct {};
const Address = types.Address;
const HolePunchPacket = types.HolePunchPacket;
@@ -16,7 +20,24 @@ const HolePunchError = types.HolePunchError;
const Defaults = types.Defaults;
/// Socket wrapper for cross-platform UDP
pub const UdpSocket = struct {
pub const UdpSocket = if (is_wasm) struct {
fd: u32 = 0,
bound_address: ?Address = null,
pub fn init() !UdpSocket {
return error.OperationNotSupported;
}
pub fn deinit(_: *UdpSocket) void {}
pub fn bind(_: *UdpSocket, _: u16) !void {
return error.OperationNotSupported;
}
pub fn sendTo(_: *UdpSocket, _: Address, _: []const u8) !void {
return error.OperationNotSupported;
}
pub fn recvFrom(_: *UdpSocket, _: []u8) !struct { len: usize, addr: Address } {
return error.OperationNotSupported;
}
} else struct {
fd: std.posix.socket_t,
bound_address: ?Address,
@@ -148,24 +169,24 @@ pub const HolePunchEngine = struct {
options: types.ConnectOptions,
) ConnectionResult {
self.stats.attempts += 1;
const start_time = std.time.milliTimestamp();
const start_time = platform_time.milliTimestamp();
// Wait until rendezvous time
const now = std.time.milliTimestamp();
const now = platform_time.milliTimestamp();
if (params.rendezvous_time > now) {
const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms;
if (options.send_keepalives) {
self.waitWithKeepalives(target_addresses, wait_ns) catch {};
} else {
std.Thread.sleep(wait_ns);
platform.time.sleep(wait_ns);
}
}
// Try with retries
for (Defaults.retry_intervals) |delay| {
if (delay > 0) {
std.Thread.sleep(delay * std.time.ns_per_ms);
platform.time.sleep(delay * std.time.ns_per_ms);
}
const result = self.singleAttempt(target_addresses, params, options);
@@ -173,7 +194,7 @@ pub const HolePunchEngine = struct {
switch (result) {
.success => |info| {
self.stats.successes += 1;
const elapsed = @as(u64, @intCast(std.time.milliTimestamp() - start_time));
const elapsed = @as(u64, @intCast(platform_time.milliTimestamp() - start_time));
self.updateAvgTime(elapsed);
return .{ .success = info };
},
@@ -254,10 +275,10 @@ pub const HolePunchEngine = struct {
}
// Wait for responses
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(Defaults.hole_punch_timeout_ms));
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(Defaults.hole_punch_timeout_ms));
var recv_buf: [256]u8 = undefined;
while (std.time.milliTimestamp() < deadline) {
while (platform_time.milliTimestamp() < deadline) {
for (contexts.items) |*ctx| {
const result = ctx.socket.recvFrom(&recv_buf) catch |err| {
if (err == error.WouldBlock) continue;
@@ -280,7 +301,7 @@ pub const HolePunchEngine = struct {
}
// Success!
const elapsed = @as(u64, @intCast(std.time.milliTimestamp() -
const elapsed = @as(u64, @intCast(platform_time.milliTimestamp() -
(params.rendezvous_time - Defaults.rendezvous_buffer_ms)));
return .{
@@ -296,7 +317,7 @@ pub const HolePunchEngine = struct {
}
// Small sleep to avoid busy loop
std.Thread.sleep(1 * std.time.ns_per_ms);
platform.time.sleep(1 * std.time.ns_per_ms);
}
return .{ .hole_punch_failed = .timeout };
@@ -307,7 +328,7 @@ pub const HolePunchEngine = struct {
var packet = HolePunchPacket{
.connection_id = params.connection_id,
.sender_id = self.our_keypair.public,
.timestamp = std.time.milliTimestamp(),
.timestamp = platform_time.milliTimestamp(),
.signature = undefined,
};
@@ -335,12 +356,12 @@ pub const HolePunchEngine = struct {
while (remaining > 0) {
const sleep_time = @min(remaining, interval_ns);
std.Thread.sleep(sleep_time);
platform.time.sleep(sleep_time);
remaining -= sleep_time;
if (remaining > 0) {
// Send keepalive to all addresses
std.mem.writeInt(i64, keepalive[4..12], std.time.milliTimestamp(), .big);
std.mem.writeInt(i64, keepalive[4..12], platform_time.milliTimestamp(), .big);
for (target_addresses) |addr| {
socket.sendTo(addr, &keepalive) catch continue;
}
@@ -408,12 +429,12 @@ pub const HolePunchListener = struct {
from: Address,
} {
var buf: [256]u8 = undefined;
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) {
while (platform_time.milliTimestamp() < deadline) {
const result = self.socket.recvFrom(&buf) catch |err| {
if (err == error.WouldBlock) {
std.Thread.sleep(1 * std.time.ns_per_ms);
platform.time.sleep(1 * std.time.ns_per_ms);
continue;
}
return err;
@@ -448,7 +469,7 @@ pub const HolePunchListener = struct {
var packet = HolePunchPacket{
.connection_id = connection_id,
.sender_id = self.our_keypair.public,
.timestamp = std.time.milliTimestamp(),
.timestamp = platform_time.milliTimestamp(),
.signature = undefined,
};

View File

@@ -3,6 +3,9 @@
//! Handles the DHT-based meeting point where peers find each other.
const std = @import("std");
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
const types = @import("types.zig");
const Allocator = std.mem.Allocator;
@@ -111,14 +114,14 @@ pub const MeetingPoint = struct {
.peer_id = self.our_keypair.public,
.addresses = self.our_addresses,
.nonce = undefined,
.timestamp = std.time.milliTimestamp(),
.timestamp = platform_time.milliTimestamp(),
.ttl = ttl,
.sequence = self.next_sequence,
.signature = undefined,
};
// Generate random nonce
std.crypto.random.bytes(&pub_data.nonce);
platform_random.bytes(&pub_data.nonce);
// Sign
const hash = pub_data.computeHash();
@@ -149,9 +152,9 @@ pub const MeetingPoint = struct {
timeout_ms: u64,
) !struct { publication: MeetingPublication, seen_time: i64 } {
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) {
while (platform_time.milliTimestamp() < deadline) {
// Query DHT
const entries = try self.dht.getAll(meeting_key, self.allocator);
defer {
@@ -186,12 +189,12 @@ pub const MeetingPoint = struct {
// Found valid publication
return .{
.publication = publication,
.seen_time = std.time.milliTimestamp(),
.seen_time = platform_time.milliTimestamp(),
};
}
// Poll interval
std.Thread.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms);
platform.time.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms);
}
return error.Timeout;
@@ -309,8 +312,8 @@ test "computeRendezvousParams produces same result for both peers" {
// Simulate two peers with their publications
var our_nonce: [32]u8 = undefined;
var their_nonce: [32]u8 = undefined;
std.crypto.random.bytes(&our_nonce);
std.crypto.random.bytes(&their_nonce);
platform_random.bytes(&our_nonce);
platform_random.bytes(&their_nonce);
const our_pub = MeetingPublication{
.peer_id = [_]u8{1} ** 32,

View File

@@ -4,6 +4,7 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
/// Protocol version
pub const PROTOCOL_VERSION: u8 = 0x01;
@@ -183,7 +184,7 @@ pub const MeetingPublication = struct {
/// Check if publication is expired
pub fn isExpired(self: MeetingPublication) bool {
const now_ms = std.time.milliTimestamp();
const now_ms = platform_time.milliTimestamp();
const expiry_ms = self.timestamp + (@as(i64, self.ttl) * 1000);
return now_ms > expiry_ms;
}

View File

@@ -29,7 +29,12 @@
//! ```
const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const Allocator = std.mem.Allocator;
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
// Import zig-p2p P2P module
const p2p_mod = @import("p2p");
@@ -150,13 +155,13 @@ pub const MWP = struct {
.peer_id = self.keypair.public,
.addresses = self.our_addresses,
.nonce = undefined,
.timestamp = std.time.milliTimestamp(),
.timestamp = platform_time.milliTimestamp(),
.ttl = ttl,
.sequence = self.next_sequence,
.signature = undefined,
};
std.crypto.random.bytes(&pub_data.nonce);
platform_random.bytes(&pub_data.nonce);
const hash = pub_data.computeHash();
pub_data.signature = try self.keypair.sign(hash);
@@ -211,7 +216,7 @@ pub const MWP = struct {
// SECURITY: Reject publications with far-future timestamps
// A malicious peer could use this to delay rendezvous arbitrarily
const now_ms = std.time.milliTimestamp();
const now_ms = platform_time.milliTimestamp();
if (publication.timestamp > now_ms + MAX_TIMESTAMP_SKEW_MS) {
std.log.warn("MWP: Rejecting publication with far-future timestamp (skew: {}ms)", .{
publication.timestamp - now_ms,
@@ -228,9 +233,9 @@ pub const MWP = struct {
/// 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));
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) {
while (platform_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| {
@@ -240,7 +245,7 @@ pub const MWP = struct {
if (try self.findPeer(their_pubkey)) |publication| {
return publication;
}
std.Thread.sleep(100 * std.time.ns_per_ms);
platform.time.sleep(100 * std.time.ns_per_ms);
}
return error.Timeout;
@@ -287,7 +292,7 @@ pub const MWP = struct {
options: ConnectOptions,
) ConnectionResult {
// SECURITY: Reject peer publications with far-future timestamps
const now_ms = std.time.milliTimestamp();
const now_ms = platform_time.milliTimestamp();
if (peer_publication.timestamp > now_ms + MAX_TIMESTAMP_SKEW_MS) {
std.log.warn("MWP: Peer publication has far-future timestamp (skew: {}ms), rejecting", .{
peer_publication.timestamp - now_ms,
@@ -339,13 +344,14 @@ pub const MWP = struct {
params: RendezvousParams,
options: ConnectOptions,
) ConnectionResult {
if (is_wasm) return .{ .hole_punch_failed = .all_addresses_failed };
_ = options;
// Wait until rendezvous time
const now = std.time.milliTimestamp();
const now = platform_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);
platform.time.sleep(wait_ns);
}
// Create UDP socket
@@ -384,7 +390,7 @@ pub const MWP = struct {
var pkt = HolePunchPacket{
.connection_id = params.connection_id,
.sender_id = self.keypair.public,
.timestamp = std.time.milliTimestamp(),
.timestamp = platform_time.milliTimestamp(),
.signature = undefined,
};
const hash = pkt.computeHash();
@@ -397,13 +403,13 @@ pub const MWP = struct {
// 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
const deadline = platform_time.milliTimestamp() + 30000; // 30 second timeout
var recv_buf: [256]u8 = undefined;
var last_send: i64 = 0;
while (std.time.milliTimestamp() < deadline) {
while (platform_time.milliTimestamp() < deadline) {
// Send (or resend) to all target addresses every 500ms
const loop_now = std.time.milliTimestamp();
const loop_now = platform_time.milliTimestamp();
if (loop_now - last_send >= 500) {
last_send = loop_now;
for (target_addresses) |addr| {
@@ -425,7 +431,7 @@ pub const MWP = struct {
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);
platform.time.sleep(1 * std.time.ns_per_ms);
continue;
}
std.log.warn("MWP: recvfrom error: {}", .{err});
@@ -476,7 +482,7 @@ pub const MWP = struct {
.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)),
.establishment_time_ms = @as(u64, @intCast(platform_time.milliTimestamp() - params.rendezvous_time + 500)),
},
};
}