add IP Reflection to DHT for zero-infrastructure NAT traversal

bundled STUN. every DHT response now includes observed_addr field so
nodes discover their public IP without external STUN servers
This commit is contained in:
2026-02-07 21:09:59 -03:00
parent abb398d363
commit f86119f571
7 changed files with 377 additions and 15 deletions

View File

@@ -559,6 +559,10 @@ pub const DhtFindNodeResponse = struct {
request_id: u64,
closest_nodes: []const NodeInfo,
/// IP Reflection: The observed source address of the requester (bundled STUN)
/// Format: IPv4 = 6 bytes (4 IP + 2 port), IPv6 = 18 bytes (16 IP + 2 port)
observed_addr: [18]u8 = [_]u8{0} ** 18,
observed_addr_len: u8 = 0,
pub const NodeInfo = struct {
node_id: NodeId,
@@ -570,6 +574,17 @@ pub const DhtFindNodeResponse = struct {
return .{
.request_id = request_id,
.closest_nodes = closest_nodes,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
};
}
pub fn initWithObserved(request_id: u64, closest_nodes: []const NodeInfo, addr: [18]u8, addr_len: u8) DhtFindNodeResponse {
return .{
.request_id = request_id,
.closest_nodes = closest_nodes,
.observed_addr = addr,
.observed_addr_len = addr_len,
};
}
};
@@ -599,11 +614,25 @@ pub const DhtStoreResponse = struct {
request_id: u64,
success: bool,
/// IP Reflection: The observed source address of the requester (bundled STUN)
observed_addr: [18]u8 = [_]u8{0} ** 18,
observed_addr_len: u8 = 0,
pub fn init(request_id: u64, success: bool) DhtStoreResponse {
return .{
.request_id = request_id,
.success = success,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
};
}
pub fn initWithObserved(request_id: u64, success: bool, addr: [18]u8, addr_len: u8) DhtStoreResponse {
return .{
.request_id = request_id,
.success = success,
.observed_addr = addr,
.observed_addr_len = addr_len,
};
}
};
@@ -631,6 +660,9 @@ pub const DhtFindValueResponse = struct {
found: bool,
value: ?[]const u8,
closest_nodes: []const DhtFindNodeResponse.NodeInfo,
/// IP Reflection: The observed source address of the requester (bundled STUN)
observed_addr: [18]u8 = [_]u8{0} ** 18,
observed_addr_len: u8 = 0,
pub fn init(request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const DhtFindNodeResponse.NodeInfo) DhtFindValueResponse {
return .{
@@ -638,6 +670,19 @@ pub const DhtFindValueResponse = struct {
.found = found,
.value = value,
.closest_nodes = closest_nodes,
.observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0,
};
}
pub fn initWithObserved(request_id: u64, found: bool, value: ?[]const u8, closest_nodes: []const DhtFindNodeResponse.NodeInfo, addr: [18]u8, addr_len: u8) DhtFindValueResponse {
return .{
.request_id = request_id,
.found = found,
.value = value,
.closest_nodes = closest_nodes,
.observed_addr = addr,
.observed_addr_len = addr_len,
};
}
};