351 lines
11 KiB
Zig
351 lines
11 KiB
Zig
//! Mutual Witness Protocol - Meeting Point Logic
|
|
//!
|
|
//! 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;
|
|
|
|
const MeetingPublication = types.MeetingPublication;
|
|
const Address = types.Address;
|
|
const Defaults = types.Defaults;
|
|
|
|
/// DHT interface that MWP requires
|
|
pub const DHTInterface = struct {
|
|
ptr: *anyopaque,
|
|
vtable: *const VTable,
|
|
|
|
pub const VTable = struct {
|
|
/// Store value at key
|
|
put: *const fn (ptr: *anyopaque, key: [32]u8, value: []const u8) anyerror!void,
|
|
|
|
/// Get all values at key
|
|
getAll: *const fn (ptr: *anyopaque, key: [32]u8, allocator: Allocator) anyerror![][]u8,
|
|
|
|
/// Subscribe to changes at key (optional)
|
|
subscribe: ?*const fn (ptr: *anyopaque, key: [32]u8, callback: *const fn ([]const u8) void) anyerror!void,
|
|
};
|
|
|
|
pub fn put(self: DHTInterface, key: [32]u8, value: []const u8) !void {
|
|
return self.vtable.put(self.ptr, key, value);
|
|
}
|
|
|
|
pub fn getAll(self: DHTInterface, key: [32]u8, allocator: Allocator) ![][]u8 {
|
|
return self.vtable.getAll(self.ptr, key, allocator);
|
|
}
|
|
|
|
pub fn subscribe(self: DHTInterface, key: [32]u8, callback: *const fn ([]const u8) void) !void {
|
|
if (self.vtable.subscribe) |sub| {
|
|
return sub(self.ptr, key, callback);
|
|
}
|
|
return error.SubscribeNotSupported;
|
|
}
|
|
};
|
|
|
|
/// Meeting point manager
|
|
pub const MeetingPoint = struct {
|
|
allocator: Allocator,
|
|
dht: DHTInterface,
|
|
our_keypair: KeyPair,
|
|
our_addresses: []const Address,
|
|
next_sequence: u64,
|
|
|
|
/// Ed25519 key pair
|
|
pub const KeyPair = struct {
|
|
public: [32]u8,
|
|
secret: [64]u8,
|
|
|
|
/// Sign a message
|
|
pub fn sign(self: KeyPair, message: [32]u8) error{InvalidKeyData}![64]u8 {
|
|
const secret_key = std.crypto.sign.Ed25519.SecretKey.fromBytes(self.secret) catch return error.InvalidKeyData;
|
|
const public_key = std.crypto.sign.Ed25519.PublicKey.fromBytes(self.public) catch return error.InvalidKeyData;
|
|
const key_pair = std.crypto.sign.Ed25519.KeyPair{
|
|
.secret_key = secret_key,
|
|
.public_key = public_key,
|
|
};
|
|
const sig = std.crypto.sign.Ed25519.KeyPair.sign(key_pair, &message, null) catch return error.InvalidKeyData;
|
|
return sig.toBytes();
|
|
}
|
|
};
|
|
|
|
/// Initialize meeting point manager
|
|
pub fn init(
|
|
allocator: Allocator,
|
|
dht: DHTInterface,
|
|
keypair: KeyPair,
|
|
addresses: []const Address,
|
|
) MeetingPoint {
|
|
return .{
|
|
.allocator = allocator,
|
|
.dht = dht,
|
|
.our_keypair = keypair,
|
|
.our_addresses = addresses,
|
|
.next_sequence = 1,
|
|
};
|
|
}
|
|
|
|
/// Compute the deterministic meeting key for two peers
|
|
pub fn computeMeetingKey(our_pubkey: [32]u8, their_pubkey: [32]u8) [32]u8 {
|
|
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
|
|
|
// Protocol identifier
|
|
hasher.update("mwp-v1");
|
|
|
|
// Deterministic ordering of public keys
|
|
if (std.mem.lessThan(u8, &our_pubkey, &their_pubkey)) {
|
|
hasher.update(&our_pubkey);
|
|
hasher.update(&their_pubkey);
|
|
} else {
|
|
hasher.update(&their_pubkey);
|
|
hasher.update(&our_pubkey);
|
|
}
|
|
|
|
var result: [32]u8 = undefined;
|
|
hasher.final(&result);
|
|
return result;
|
|
}
|
|
|
|
/// Create a new publication
|
|
pub fn createPublication(self: *MeetingPoint, ttl: u32) error{InvalidKeyData}!MeetingPublication {
|
|
var pub_data = MeetingPublication{
|
|
.peer_id = self.our_keypair.public,
|
|
.addresses = self.our_addresses,
|
|
.nonce = undefined,
|
|
.timestamp = platform_time.milliTimestamp(),
|
|
.ttl = ttl,
|
|
.sequence = self.next_sequence,
|
|
.signature = undefined,
|
|
};
|
|
|
|
// Generate random nonce
|
|
platform_random.bytes(&pub_data.nonce);
|
|
|
|
// Sign
|
|
const hash = pub_data.computeHash();
|
|
pub_data.signature = try self.our_keypair.sign(hash);
|
|
|
|
self.next_sequence += 1;
|
|
|
|
return pub_data;
|
|
}
|
|
|
|
/// Publish to a meeting point
|
|
pub fn publish(self: *MeetingPoint, their_pubkey: [32]u8, ttl: u32) !MeetingPublication {
|
|
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
|
|
const publication = try self.createPublication(ttl);
|
|
|
|
const serialized = try publication.serialize(self.allocator);
|
|
defer self.allocator.free(serialized);
|
|
|
|
try self.dht.put(meeting_key, serialized);
|
|
|
|
return publication;
|
|
}
|
|
|
|
/// Wait for peer's publication at meeting point
|
|
pub fn waitForPeer(
|
|
self: *MeetingPoint,
|
|
their_pubkey: [32]u8,
|
|
timeout_ms: u64,
|
|
) !struct { publication: MeetingPublication, seen_time: i64 } {
|
|
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
|
|
const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
|
|
|
|
while (platform_time.milliTimestamp() < deadline) {
|
|
// Query DHT
|
|
const entries = try self.dht.getAll(meeting_key, self.allocator);
|
|
defer {
|
|
for (entries) |entry| {
|
|
self.allocator.free(entry);
|
|
}
|
|
self.allocator.free(entries);
|
|
}
|
|
|
|
// Look for peer's publication
|
|
for (entries) |entry| {
|
|
var publication = MeetingPublication.deserialize(self.allocator, entry) catch continue;
|
|
|
|
// Is this from our target peer?
|
|
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
|
|
publication.deinit(self.allocator);
|
|
continue;
|
|
}
|
|
|
|
// Verify signature
|
|
if (!publication.verify()) {
|
|
publication.deinit(self.allocator);
|
|
continue;
|
|
}
|
|
|
|
// Check not expired
|
|
if (publication.isExpired()) {
|
|
publication.deinit(self.allocator);
|
|
continue;
|
|
}
|
|
|
|
// Found valid publication
|
|
return .{
|
|
.publication = publication,
|
|
.seen_time = platform_time.milliTimestamp(),
|
|
};
|
|
}
|
|
|
|
// Poll interval
|
|
platform.time.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms);
|
|
}
|
|
|
|
return error.Timeout;
|
|
}
|
|
|
|
/// Find peer's publication (non-blocking)
|
|
pub fn findPeer(
|
|
self: *MeetingPoint,
|
|
their_pubkey: [32]u8,
|
|
) !?MeetingPublication {
|
|
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
|
|
|
|
const entries = try self.dht.getAll(meeting_key, self.allocator);
|
|
defer {
|
|
for (entries) |entry| {
|
|
self.allocator.free(entry);
|
|
}
|
|
self.allocator.free(entries);
|
|
}
|
|
|
|
for (entries) |entry| {
|
|
var publication = MeetingPublication.deserialize(self.allocator, entry) catch continue;
|
|
|
|
if (!std.mem.eql(u8, &publication.peer_id, &their_pubkey)) {
|
|
publication.deinit(self.allocator);
|
|
continue;
|
|
}
|
|
|
|
if (!publication.verify()) {
|
|
publication.deinit(self.allocator);
|
|
continue;
|
|
}
|
|
|
|
if (publication.isExpired()) {
|
|
publication.deinit(self.allocator);
|
|
continue;
|
|
}
|
|
|
|
return publication;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// Update our addresses and republish
|
|
pub fn updateAddresses(self: *MeetingPoint, new_addresses: []const Address) void {
|
|
self.our_addresses = new_addresses;
|
|
}
|
|
};
|
|
|
|
/// Compute shared rendezvous parameters from two publications
|
|
pub fn computeRendezvousParams(
|
|
our_pub: MeetingPublication,
|
|
their_pub: MeetingPublication,
|
|
seen_time: i64,
|
|
buffer_ms: i64,
|
|
) types.RendezvousParams {
|
|
// Combine nonces deterministically
|
|
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
|
|
|
if (std.mem.lessThan(u8, &our_pub.nonce, &their_pub.nonce)) {
|
|
hasher.update(&our_pub.nonce);
|
|
hasher.update(&their_pub.nonce);
|
|
} else {
|
|
hasher.update(&their_pub.nonce);
|
|
hasher.update(&our_pub.nonce);
|
|
}
|
|
|
|
var shared_randomness: [32]u8 = undefined;
|
|
hasher.final(&shared_randomness);
|
|
|
|
// Rendezvous time: relative to when we saw peer (robust to clock skew)
|
|
const rendezvous_time = seen_time + buffer_ms;
|
|
|
|
// Port hint from shared randomness
|
|
const port_offset = std.mem.readInt(u16, shared_randomness[0..2], .little);
|
|
const port_hint = 49152 + (port_offset % 16384);
|
|
|
|
// Connection ID from shared randomness
|
|
var connection_id: [16]u8 = undefined;
|
|
@memcpy(&connection_id, shared_randomness[16..32]);
|
|
|
|
return .{
|
|
.shared_randomness = shared_randomness,
|
|
.rendezvous_time = rendezvous_time,
|
|
.port_hint = port_hint,
|
|
.connection_id = connection_id,
|
|
};
|
|
}
|
|
|
|
// Tests
|
|
test "computeMeetingKey is deterministic" {
|
|
const key_a = [_]u8{1} ** 32;
|
|
const key_b = [_]u8{2} ** 32;
|
|
|
|
const result1 = MeetingPoint.computeMeetingKey(key_a, key_b);
|
|
const result2 = MeetingPoint.computeMeetingKey(key_b, key_a);
|
|
|
|
// Order shouldn't matter
|
|
try std.testing.expect(std.mem.eql(u8, &result1, &result2));
|
|
}
|
|
|
|
test "computeMeetingKey is unique per pair" {
|
|
const key_a = [_]u8{1} ** 32;
|
|
const key_b = [_]u8{2} ** 32;
|
|
const key_c = [_]u8{3} ** 32;
|
|
|
|
const result_ab = MeetingPoint.computeMeetingKey(key_a, key_b);
|
|
const result_ac = MeetingPoint.computeMeetingKey(key_a, key_c);
|
|
|
|
try std.testing.expect(!std.mem.eql(u8, &result_ab, &result_ac));
|
|
}
|
|
|
|
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;
|
|
platform_random.bytes(&our_nonce);
|
|
platform_random.bytes(&their_nonce);
|
|
|
|
const our_pub = MeetingPublication{
|
|
.peer_id = [_]u8{1} ** 32,
|
|
.addresses = &[_]Address{},
|
|
.nonce = our_nonce,
|
|
.timestamp = 1000,
|
|
.ttl = 300,
|
|
.sequence = 1,
|
|
.signature = [_]u8{0} ** 64,
|
|
};
|
|
|
|
const their_pub = MeetingPublication{
|
|
.peer_id = [_]u8{2} ** 32,
|
|
.addresses = &[_]Address{},
|
|
.nonce = their_nonce,
|
|
.timestamp = 1050,
|
|
.ttl = 300,
|
|
.sequence = 1,
|
|
.signature = [_]u8{0} ** 64,
|
|
};
|
|
|
|
// Both peers compute with their own seen_time
|
|
const our_params = computeRendezvousParams(our_pub, their_pub, 1100, 500);
|
|
const their_params = computeRendezvousParams(their_pub, our_pub, 1100, 500);
|
|
|
|
// Shared randomness should be identical
|
|
try std.testing.expect(std.mem.eql(u8, &our_params.shared_randomness, &their_params.shared_randomness));
|
|
|
|
// Port hint should be identical
|
|
try std.testing.expectEqual(our_params.port_hint, their_params.port_hint);
|
|
|
|
// Connection ID should be identical
|
|
try std.testing.expect(std.mem.eql(u8, &our_params.connection_id, &their_params.connection_id));
|
|
}
|