bidirectional ip reflection for listener address discovery
This commit is contained in:
377
src/p2p/p2p.zig
377
src/p2p/p2p.zig
@@ -98,6 +98,67 @@ pub const UserContext = events.UserContext;
|
||||
pub const P2PStats = stats.P2PStats;
|
||||
pub const CircuitBreaker = circuit_breaker.CircuitBreaker;
|
||||
|
||||
/// Observed address from DHT response (Bundled STUN / IP Reflection)
|
||||
pub const ObservedAddress = struct {
|
||||
/// The observed IP address (IPv4 or IPv6)
|
||||
ip: union(enum) {
|
||||
v4: [4]u8,
|
||||
v6: [16]u8,
|
||||
},
|
||||
/// The observed port
|
||||
port: u16,
|
||||
/// Timestamp when this was observed
|
||||
timestamp: i64,
|
||||
/// Which peer observed this address
|
||||
observer_id: [32]u8,
|
||||
|
||||
/// Create from raw DHT response bytes
|
||||
pub fn fromDhtResponse(addr_bytes: [18]u8, addr_len: u8, observer: [32]u8) ?ObservedAddress {
|
||||
if (addr_len == 0) return null;
|
||||
|
||||
var result: ObservedAddress = undefined;
|
||||
result.timestamp = std.time.milliTimestamp();
|
||||
result.observer_id = observer;
|
||||
|
||||
if (addr_len == 6) {
|
||||
// IPv4: 4 bytes IP + 2 bytes port
|
||||
result.ip = .{ .v4 = addr_bytes[0..4].* };
|
||||
result.port = std.mem.readInt(u16, addr_bytes[4..6], .big);
|
||||
} else if (addr_len == 18) {
|
||||
// IPv6: 16 bytes IP + 2 bytes port
|
||||
result.ip = .{ .v6 = addr_bytes[0..16].* };
|
||||
result.port = std.mem.readInt(u16, addr_bytes[16..18], .big);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Check if this is a valid public address (not localhost/private)
|
||||
pub fn isPublic(self: ObservedAddress) bool {
|
||||
switch (self.ip) {
|
||||
.v4 => |ip| {
|
||||
// Skip localhost (127.x.x.x)
|
||||
if (ip[0] == 127) return false;
|
||||
// Skip private ranges
|
||||
if (ip[0] == 10) return false; // 10.0.0.0/8
|
||||
if (ip[0] == 172 and ip[1] >= 16 and ip[1] <= 31) return false; // 172.16.0.0/12
|
||||
if (ip[0] == 192 and ip[1] == 168) return false; // 192.168.0.0/16
|
||||
if (ip[0] == 0) return false; // 0.0.0.0
|
||||
return true;
|
||||
},
|
||||
.v6 => |ip| {
|
||||
// Skip loopback (::1)
|
||||
if (std.mem.eql(u8, &ip, &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 })) return false;
|
||||
// Skip link-local (fe80::/10)
|
||||
if (ip[0] == 0xfe and (ip[1] & 0xc0) == 0x80) return false;
|
||||
return true;
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Implementation modules
|
||||
const lifecycle = @import("lifecycle.zig");
|
||||
const connection = @import("connection.zig");
|
||||
@@ -144,6 +205,17 @@ pub fn sendDhtMessageCallback(peer_id: [32]u8, msg: protocol.message.Message, co
|
||||
return dht_module.sendDhtMessageImpl(p2p, peer_id, msg);
|
||||
}
|
||||
|
||||
/// Callback to record observed addresses from DHT responses (IP Reflection / Bundled STUN).
|
||||
/// Called by DHT response handlers when they receive our public IP from peers.
|
||||
pub fn addObservedAddressCallback(observed_addr: [18]u8, observed_addr_len: u8, observer_id: [32]u8, context: ?*anyopaque) void {
|
||||
const p2p: *P2P = @ptrCast(@alignCast(context orelse {
|
||||
std.log.err("addObservedAddressCallback: null context", .{});
|
||||
return;
|
||||
}));
|
||||
|
||||
p2p.addObservedAddress(observed_addr, observed_addr_len, observer_id);
|
||||
}
|
||||
|
||||
/// Callback to handle data responses during file downloads.
|
||||
///
|
||||
/// This function processes incoming DataResponse messages and writes
|
||||
@@ -307,6 +379,11 @@ pub const P2P = struct {
|
||||
dht_node_to_peer: std.AutoHashMap([32]u8, PeerId),
|
||||
/// Mutex for dht_node_to_peer map
|
||||
dht_node_to_peer_mutex: Mutex,
|
||||
/// Observed public addresses from DHT responses (Bundled STUN / IP Reflection)
|
||||
/// Stores our public IP:port as seen by DHT peers
|
||||
observed_addresses: std.ArrayList(ObservedAddress),
|
||||
/// Mutex for observed_addresses
|
||||
observed_addresses_mutex: Mutex,
|
||||
/// Statistics
|
||||
stats: P2PStats,
|
||||
/// Internal flags (THREAD SAFETY: atomic for lock-free access from multiple threads)
|
||||
@@ -383,6 +460,8 @@ pub const P2P = struct {
|
||||
.connection_backoff = null,
|
||||
.dht_node_to_peer = std.AutoHashMap([32]u8, PeerId).init(allocator),
|
||||
.dht_node_to_peer_mutex = Mutex{},
|
||||
.observed_addresses = .{},
|
||||
.observed_addresses_mutex = Mutex{},
|
||||
.stats = P2PStats{
|
||||
.state = .Uninitialized,
|
||||
.uptime_seconds = 0,
|
||||
@@ -614,6 +693,7 @@ pub const P2P = struct {
|
||||
p2p.allocator.destroy(rt);
|
||||
}
|
||||
p2p.dht_node_to_peer.deinit();
|
||||
p2p.observed_addresses.deinit(p2p.allocator);
|
||||
|
||||
// Clean up network components
|
||||
if (p2p.network_bridge) |bridge| {
|
||||
@@ -829,6 +909,30 @@ pub const P2P = struct {
|
||||
return messaging.emitEventImpl(p2p, event);
|
||||
}
|
||||
|
||||
/// Process network I/O and internal state updates.
|
||||
///
|
||||
/// **CRITICAL**: This function MUST be called periodically in your application's
|
||||
/// main loop. Without calling update(), the library will not:
|
||||
/// - Receive incoming messages
|
||||
/// - Accept new connections
|
||||
/// - Process DHT queries/responses
|
||||
/// - Handle file transfers
|
||||
///
|
||||
/// This poll-based design enables WASM compatibility and single-threaded operation.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```zig
|
||||
/// while (running) {
|
||||
/// try p2p.update(); // Process all pending I/O
|
||||
/// // ... your application logic ...
|
||||
/// std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Recommended Call Frequency
|
||||
/// - 10-100ms intervals for most applications
|
||||
/// - More frequent for lower latency requirements
|
||||
/// - Less frequent is OK for idle applications (but responses will be delayed)
|
||||
pub fn update(p2p: *P2P) Error!void {
|
||||
return messaging.updateImpl(p2p);
|
||||
}
|
||||
@@ -881,6 +985,47 @@ pub const P2P = struct {
|
||||
return dht_ops.getDhtPeerCountImpl(p2p);
|
||||
}
|
||||
|
||||
/// Get the number of active connections (connected peers)
|
||||
pub fn getActiveConnectionCount(p2p: *P2P) u32 {
|
||||
return p2p.stats.active_connections.load(.monotonic);
|
||||
}
|
||||
|
||||
/// Get the number of DHT node ID mappings (peers we can route DHT messages to)
|
||||
pub fn getDhtMappingCount(p2p: *P2P) usize {
|
||||
p2p.dht_node_to_peer_mutex.lock();
|
||||
defer p2p.dht_node_to_peer_mutex.unlock();
|
||||
return p2p.dht_node_to_peer.count();
|
||||
}
|
||||
|
||||
/// Add all currently mapped DHT peers to the routing table.
|
||||
/// This is useful when you want to be able to query peers that have connected to you
|
||||
/// but haven't been explicitly added to your routing table via dhtAddPeer.
|
||||
pub fn addMappedPeersToRoutingTable(p2p: *P2P) !usize {
|
||||
var added: usize = 0;
|
||||
|
||||
// Collect node IDs and their connection peer IDs
|
||||
p2p.dht_node_to_peer_mutex.lock();
|
||||
defer p2p.dht_node_to_peer_mutex.unlock();
|
||||
|
||||
var iter = p2p.dht_node_to_peer.iterator();
|
||||
while (iter.next()) |entry| {
|
||||
const node_id = entry.key_ptr.*;
|
||||
const connection_peer_id = entry.value_ptr.*;
|
||||
|
||||
// Get the socket for this connection peer
|
||||
const socket = p2p.getPeerSocket(connection_peer_id) orelse continue;
|
||||
|
||||
// Get the peer's address from the socket (already in our Address type)
|
||||
const address = socket.getPeerAddress() catch continue;
|
||||
|
||||
// Add to routing table
|
||||
p2p.dhtAddPeer(node_id, address) catch continue;
|
||||
added += 1;
|
||||
}
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
pub fn dhtStore(p2p: *P2P, key: [32]u8, value: []const u8, ttl: u32) Error!void {
|
||||
return dht_ops.dhtStoreImpl(p2p, key, value, ttl);
|
||||
}
|
||||
@@ -905,6 +1050,238 @@ pub const P2P = struct {
|
||||
return dht_ops.dhtAddPeerImpl(p2p, peer_id, address);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Bundled STUN / IP Reflection (Observed Address Management)
|
||||
// =========================================================================
|
||||
|
||||
/// Store an observed address from a DHT response (called internally by DHT handlers)
|
||||
pub fn addObservedAddress(p2p: *P2P, addr_bytes: [18]u8, addr_len: u8, observer_id: [32]u8) void {
|
||||
const observed = ObservedAddress.fromDhtResponse(addr_bytes, addr_len, observer_id) orelse return;
|
||||
|
||||
p2p.observed_addresses_mutex.lock();
|
||||
defer p2p.observed_addresses_mutex.unlock();
|
||||
|
||||
// Check if we already have this address from this observer
|
||||
for (p2p.observed_addresses.items) |*existing| {
|
||||
const same_observer = std.mem.eql(u8, &existing.observer_id, &observer_id);
|
||||
const same_addr = switch (observed.ip) {
|
||||
.v4 => |ip| switch (existing.ip) {
|
||||
.v4 => |eip| std.mem.eql(u8, &ip, &eip) and observed.port == existing.port,
|
||||
.v6 => false,
|
||||
},
|
||||
.v6 => |ip| switch (existing.ip) {
|
||||
.v6 => |eip| std.mem.eql(u8, &ip, &eip) and observed.port == existing.port,
|
||||
.v4 => false,
|
||||
},
|
||||
};
|
||||
|
||||
if (same_observer or same_addr) {
|
||||
// Update timestamp
|
||||
existing.timestamp = observed.timestamp;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Add new observed address (limit to 10 entries to prevent unbounded growth)
|
||||
if (p2p.observed_addresses.items.len >= 10) {
|
||||
// Remove oldest entry
|
||||
_ = p2p.observed_addresses.orderedRemove(0);
|
||||
}
|
||||
|
||||
p2p.observed_addresses.append(p2p.allocator, observed) catch return;
|
||||
|
||||
// Log if this is a public address
|
||||
if (observed.isPublic()) {
|
||||
switch (observed.ip) {
|
||||
.v4 => |ip| std.log.info("Bundled STUN: Discovered public address {d}.{d}.{d}.{d}:{d}", .{ ip[0], ip[1], ip[2], ip[3], observed.port }),
|
||||
.v6 => std.log.info("Bundled STUN: Discovered public IPv6 address (port {d})", .{observed.port}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the best observed public address (most recent, public, from multiple observers)
|
||||
pub fn getObservedPublicAddress(p2p: *P2P) ?ObservedAddress {
|
||||
p2p.observed_addresses_mutex.lock();
|
||||
defer p2p.observed_addresses_mutex.unlock();
|
||||
|
||||
// Find most recent public address
|
||||
var best: ?ObservedAddress = null;
|
||||
for (p2p.observed_addresses.items) |addr| {
|
||||
if (!addr.isPublic()) continue;
|
||||
|
||||
if (best == null or addr.timestamp > best.?.timestamp) {
|
||||
best = addr;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// Get all observed addresses (for MWP to include in publications)
|
||||
pub fn getAllObservedAddresses(p2p: *P2P, allocator: Allocator) ![]ObservedAddress {
|
||||
p2p.observed_addresses_mutex.lock();
|
||||
defer p2p.observed_addresses_mutex.unlock();
|
||||
|
||||
return try allocator.dupe(ObservedAddress, p2p.observed_addresses.items);
|
||||
}
|
||||
|
||||
/// Confidence level for observed address consensus
|
||||
pub const AddressConfidence = enum {
|
||||
/// No observers yet
|
||||
none,
|
||||
/// Single observer (trusted but unverified)
|
||||
single_source,
|
||||
/// Multiple observers agree
|
||||
consensus,
|
||||
/// Multiple observers disagree (using majority)
|
||||
conflict,
|
||||
};
|
||||
|
||||
/// Result of consensus address lookup
|
||||
pub const ConsensusResult = struct {
|
||||
address: ?ObservedAddress,
|
||||
confidence: AddressConfidence,
|
||||
/// Number of unique observers reporting this address
|
||||
observer_count: u8,
|
||||
/// Total number of unique observers
|
||||
total_observers: u8,
|
||||
};
|
||||
|
||||
/// Get the consensus observed address with confidence level
|
||||
/// Returns the address that most unique observers agree on
|
||||
pub fn getConsensusAddress(p2p: *P2P) ConsensusResult {
|
||||
p2p.observed_addresses_mutex.lock();
|
||||
defer p2p.observed_addresses_mutex.unlock();
|
||||
|
||||
if (p2p.observed_addresses.items.len == 0) {
|
||||
return .{
|
||||
.address = null,
|
||||
.confidence = .none,
|
||||
.observer_count = 0,
|
||||
.total_observers = 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Count unique observers and group addresses
|
||||
// Key: (ip_hash, port) -> count of unique observers
|
||||
var address_votes: [10]struct {
|
||||
addr: ObservedAddress,
|
||||
observers: [10][32]u8,
|
||||
observer_count: u8,
|
||||
} = undefined;
|
||||
var num_addresses: usize = 0;
|
||||
var total_unique_observers: u8 = 0;
|
||||
var seen_observers: [10][32]u8 = undefined;
|
||||
var num_seen_observers: usize = 0;
|
||||
|
||||
for (p2p.observed_addresses.items) |observed| {
|
||||
// Track unique observers
|
||||
var observer_seen = false;
|
||||
for (seen_observers[0..num_seen_observers]) |seen| {
|
||||
if (std.mem.eql(u8, &seen, &observed.observer_id)) {
|
||||
observer_seen = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!observer_seen and num_seen_observers < 10) {
|
||||
seen_observers[num_seen_observers] = observed.observer_id;
|
||||
num_seen_observers += 1;
|
||||
total_unique_observers += 1;
|
||||
}
|
||||
|
||||
// Find or create address entry
|
||||
var found_idx: ?usize = null;
|
||||
for (address_votes[0..num_addresses], 0..) |*entry, idx| {
|
||||
if (addressesEqual(entry.addr, observed)) {
|
||||
found_idx = idx;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found_idx) |idx| {
|
||||
// Check if this observer already voted for this address
|
||||
var already_voted = false;
|
||||
for (address_votes[idx].observers[0..address_votes[idx].observer_count]) |obs| {
|
||||
if (std.mem.eql(u8, &obs, &observed.observer_id)) {
|
||||
already_voted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!already_voted and address_votes[idx].observer_count < 10) {
|
||||
address_votes[idx].observers[address_votes[idx].observer_count] = observed.observer_id;
|
||||
address_votes[idx].observer_count += 1;
|
||||
// Update to most recent timestamp
|
||||
if (observed.timestamp > address_votes[idx].addr.timestamp) {
|
||||
address_votes[idx].addr = observed;
|
||||
}
|
||||
}
|
||||
} else if (num_addresses < 10) {
|
||||
// New address
|
||||
address_votes[num_addresses] = .{
|
||||
.addr = observed,
|
||||
.observers = undefined,
|
||||
.observer_count = 1,
|
||||
};
|
||||
address_votes[num_addresses].observers[0] = observed.observer_id;
|
||||
num_addresses += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (num_addresses == 0) {
|
||||
return .{
|
||||
.address = null,
|
||||
.confidence = .none,
|
||||
.observer_count = 0,
|
||||
.total_observers = total_unique_observers,
|
||||
};
|
||||
}
|
||||
|
||||
// Find address with most votes
|
||||
var best_idx: usize = 0;
|
||||
var best_count: u8 = address_votes[0].observer_count;
|
||||
for (address_votes[1..num_addresses], 1..) |entry, idx| {
|
||||
if (entry.observer_count > best_count) {
|
||||
best_count = entry.observer_count;
|
||||
best_idx = idx;
|
||||
}
|
||||
}
|
||||
|
||||
const confidence: AddressConfidence = if (total_unique_observers == 1)
|
||||
.single_source
|
||||
else if (best_count == total_unique_observers)
|
||||
.consensus
|
||||
else
|
||||
.conflict;
|
||||
|
||||
if (confidence == .consensus and total_unique_observers >= 2) {
|
||||
std.log.info("IP Reflection: Consensus reached! {} observers agree on address", .{total_unique_observers});
|
||||
} else if (confidence == .conflict) {
|
||||
std.log.warn("IP Reflection: Conflict detected - {}/{} observers agree (using majority)", .{ best_count, total_unique_observers });
|
||||
}
|
||||
|
||||
return .{
|
||||
.address = address_votes[best_idx].addr,
|
||||
.confidence = confidence,
|
||||
.observer_count = best_count,
|
||||
.total_observers = total_unique_observers,
|
||||
};
|
||||
}
|
||||
|
||||
/// Helper: Compare two observed addresses (ignoring timestamp and observer)
|
||||
fn addressesEqual(a: ObservedAddress, b: ObservedAddress) bool {
|
||||
if (a.port != b.port) return false;
|
||||
return switch (a.ip) {
|
||||
.v4 => |ip_a| switch (b.ip) {
|
||||
.v4 => |ip_b| std.mem.eql(u8, &ip_a, &ip_b),
|
||||
.v6 => false,
|
||||
},
|
||||
.v6 => |ip_a| switch (b.ip) {
|
||||
.v6 => |ip_b| std.mem.eql(u8, &ip_a, &ip_b),
|
||||
.v4 => false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Small inline methods (just access fields)
|
||||
// =========================================================================
|
||||
|
||||
Reference in New Issue
Block a user