create Mutual Witness Protocol specs and implementation. #1

Merged
mdt merged 26 commits from mwp into main 2026-02-11 17:38:08 +00:00
84 changed files with 11264 additions and 411 deletions
Showing only changes of commit 88a2abe521 - Show all commits

View File

@@ -484,11 +484,14 @@ pub fn shutdownImpl(p2p: *P2P) void {
p2p.state_mutex.unlock();
// Clear event queue
p2p.event_mutex.lock();
defer p2p.event_mutex.unlock();
p2p.event_queue.clearRetainingCapacity();
{
p2p.event_mutex.lock();
defer p2p.event_mutex.unlock();
p2p.event_queue.clearRetainingCapacity();
}
// Emit final event (ignore errors during shutdown)
// Must be outside event_mutex scope — emitEvent takes the lock internally
p2p.emitEvent(P2PEvent.create(.library_stopped, .library_stopped)) catch |err| {
std.log.warn("Failed to emit shutdown event: {}", .{err});
};

View File

@@ -1043,23 +1043,28 @@ pub const P2P = struct {
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();
// Snapshot node mappings under lock, then release before calling other locked functions
const Mapping = struct { node_id: [32]u8, peer_id: PeerId };
var mappings: [64]Mapping = undefined;
var count: usize = 0;
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.*;
{
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
// Get the socket for this connection peer
const socket = p2p.getPeerSocket(connection_peer_id) orelse continue;
var iter = p2p.dht_node_to_peer.iterator();
while (iter.next()) |entry| {
if (count >= mappings.len) break;
mappings[count] = .{ .node_id = entry.key_ptr.*, .peer_id = entry.value_ptr.* };
count += 1;
}
}
// Get the peer's address from the socket (already in our Address type)
// Process mappings without holding dht_node_to_peer_mutex
for (mappings[0..count]) |mapping| {
const socket = p2p.getPeerSocket(mapping.peer_id) orelse continue;
const address = socket.getPeerAddress() catch continue;
// Add to routing table
p2p.dhtAddPeer(node_id, address) catch continue;
p2p.dhtAddPeer(mapping.node_id, address) catch continue;
added += 1;
}
@@ -1124,8 +1129,16 @@ pub const P2P = struct {
// 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);
// Remove the entry with the oldest timestamp (least recently observed)
var oldest_idx: usize = 0;
var oldest_ts: i64 = p2p.observed_addresses.items[0].timestamp;
for (p2p.observed_addresses.items[1..], 1..) |item, i| {
if (item.timestamp < oldest_ts) {
oldest_ts = item.timestamp;
oldest_idx = i;
}
}
_ = p2p.observed_addresses.orderedRemove(oldest_idx);
}
p2p.observed_addresses.append(p2p.allocator, observed) catch return;

View File

@@ -372,9 +372,27 @@ test "lifecycle: error state and recovery" {
// This is expected behavior - recovery resets to clean state
}
// Note: shutdown test disabled due to deadlock in event emission during shutdown
// This is a known limitation - shutdown should be called only when not holding locks
// test "lifecycle: shutdown force terminates" { ... }
test "lifecycle: shutdown completes cleanly" {
const allocator = testing.allocator;
var instance = try P2P.init(allocator, createTestConfig());
defer instance.deinit();
try instance.start();
// Process a few update cycles to let the system settle
var i: usize = 0;
while (i < 5) : (i += 1) {
try instance.update();
std.Thread.sleep(10 * std.time.ns_per_ms);
}
// Shutdown should complete without deadlock (H2 fix: event_mutex scoped in shutdownImpl)
try instance.stop();
// Verify state is stopped
try testing.expectEqual(P2PState.Initialized, instance.getState());
}
// ============================================================================
// TIER 1: Event System