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
93 changed files with 11825 additions and 773 deletions
Showing only changes of commit 47f949e4cc - Show all commits

View File

@@ -156,6 +156,7 @@ pub fn main() !void {
resume_file, resume_file,
total_size, total_size,
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );

View File

@@ -136,6 +136,7 @@ pub fn main() !void {
resume_file, resume_file,
total_size, total_size,
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );
@@ -175,6 +176,7 @@ pub fn main() !void {
resume_file, resume_file,
total_size + 1024, // Wrong size total_size + 1024, // Wrong size
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );
@@ -190,6 +192,7 @@ pub fn main() !void {
"nonexistent_resume_file.resume", "nonexistent_resume_file.resume",
total_size, total_size,
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );

View File

@@ -532,6 +532,8 @@ pub const DownloadManager = struct {
endgame_initialized: bool = false, endgame_initialized: bool = false,
/// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates) /// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates)
endgame_broadcast_pending: bool = false, endgame_broadcast_pending: bool = false,
/// Content hash of the file being downloaded (for resume state validation)
content_hash: [32]u8 = [_]u8{0} ** 32,
pub fn init( pub fn init(
total_size: u64, total_size: u64,
@@ -756,71 +758,77 @@ pub const DownloadManager = struct {
/// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation /// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation
fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void { fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void {
// Collect pieces to cancel (can't modify while iterating) // Collect pieces to cancel (can't modify while iterating)
// Use 1024 to handle large downloads (1GB = 1024 pieces at 1MB each) // Process in batches of 1024 to avoid heap allocation while handling any download size
var to_cancel: [1024]u32 = undefined; var total_cancelled: usize = 0;
var cancel_count: usize = 0; while (true) {
var to_cancel: [1024]u32 = undefined;
var cancel_count: usize = 0;
var iter = self.active_downloads.iterator(); var iter = self.active_downloads.iterator();
while (iter.next()) |entry| { while (iter.next()) |entry| {
if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) { if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) {
if (cancel_count < to_cancel.len) { if (cancel_count < to_cancel.len) {
to_cancel[cancel_count] = entry.key_ptr.*; to_cancel[cancel_count] = entry.key_ptr.*;
cancel_count += 1; cancel_count += 1;
}
}
}
// Move cancelled downloads back to pending queue
for (to_cancel[0..cancel_count]) |piece_index| {
_ = self.active_downloads.remove(piece_index);
// SOCKET FIX: Release request tracker slot so new requests can be sent
self.request_tracker.recordCompletion(peer_id, piece_index);
// DISCONNECT FIX: Clear retry tracker for this peer so piece can be
// immediately retried from another peer without counting against retry limit.
// Per BitTorrent best practices, peer disconnect should not penalize the piece.
if (self.retry_trackers.getPtr(piece_index)) |tracker| {
// Only reset if the last failure was from this peer
if (tracker.last_peer) |last| {
if (std.mem.eql(u8, &last, &peer_id)) {
tracker.reset();
} }
} }
} }
// Check if already in pending queue if (cancel_count == 0) break;
var already_pending = false; total_cancelled += cancel_count;
for (self.pending_requests.items) |pending| {
if (pending.piece_index == piece_index) { // Move cancelled downloads back to pending queue
already_pending = true; for (to_cancel[0..cancel_count]) |piece_index| {
break; _ = self.active_downloads.remove(piece_index);
// SOCKET FIX: Release request tracker slot so new requests can be sent
self.request_tracker.recordCompletion(peer_id, piece_index);
// DISCONNECT FIX: Clear retry tracker for this peer so piece can be
// immediately retried from another peer without counting against retry limit.
// Per BitTorrent best practices, peer disconnect should not penalize the piece.
if (self.retry_trackers.getPtr(piece_index)) |tracker| {
// Only reset if the last failure was from this peer
if (tracker.last_peer) |last| {
if (std.mem.eql(u8, &last, &peer_id)) {
tracker.reset();
}
}
} }
}
// Check if piece is already verified (might have completed from another peer) // Check if already in pending queue
var already_verified = false; var already_pending = false;
if (self.selector.availability_map.get(piece_index)) |info| { for (self.pending_requests.items) |pending| {
already_verified = info.is_verified; if (pending.piece_index == piece_index) {
} already_pending = true;
break;
}
}
if (!already_pending and !already_verified) { // Check if piece is already verified (might have completed from another peer)
// Re-add to pending with priority (front of queue) var already_verified = false;
self.pending_requests.insert(self.allocator, 0, DownloadRequest{ if (self.selector.availability_map.get(piece_index)) |info| {
.piece_index = piece_index, already_verified = info.is_verified;
.peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests }
.offset = 0,
.length = @intCast(self.piece_size), if (!already_pending and !already_verified) {
.priority = .high, // Boost priority for retried pieces // Re-add to pending with priority (front of queue)
.requested_at = std.time.timestamp(), self.pending_requests.insert(self.allocator, 0, DownloadRequest{
}) catch { .piece_index = piece_index,
std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index}); .peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests
}; .offset = 0,
.length = @intCast(self.piece_size),
.priority = .high, // Boost priority for retried pieces
.requested_at = std.time.timestamp(),
}) catch {
std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index});
};
}
} }
} }
if (cancel_count > 0) { if (total_cancelled > 0) {
std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{cancel_count}); std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{total_cancelled});
} }
} }
@@ -2110,7 +2118,7 @@ pub const DownloadManager = struct {
.piece_size = self.piece_size, .piece_size = self.piece_size,
.piece_count = self.state.piece_count, .piece_count = self.state.piece_count,
.completed_count = self.state.completed_pieces.load(.acquire), .completed_count = self.state.completed_pieces.load(.acquire),
.file_hash = [_]u8{0} ** 32, // TODO: Store actual file hash if available .file_hash = self.content_hash,
}; };
// Write header // Write header
@@ -2152,6 +2160,7 @@ pub const DownloadManager = struct {
resume_path: []const u8, resume_path: []const u8,
expected_total_size: u64, expected_total_size: u64,
expected_piece_size: u64, expected_piece_size: u64,
expected_content_hash: ?[32]u8,
strategy: SelectionStrategy, strategy: SelectionStrategy,
) Error!?DownloadManager { ) Error!?DownloadManager {
// Validate path // Validate path
@@ -2197,6 +2206,17 @@ pub const DownloadManager = struct {
return null; return null;
} }
// Validate content hash if provided (non-zero hash in file must match)
if (expected_content_hash) |expected_hash| {
const zero_hash = [_]u8{0} ** 32;
if (!std.mem.eql(u8, &header.file_hash, &zero_hash)) {
if (!std.crypto.timing_safe.eql([32]u8, header.file_hash, expected_hash)) {
std.log.warn("Resume file content hash mismatch", .{});
return null;
}
}
}
// Create download manager // Create download manager
var manager = try DownloadManager.init( var manager = try DownloadManager.init(
header.total_size, header.total_size,
@@ -2206,6 +2226,7 @@ pub const DownloadManager = struct {
allocator, allocator,
); );
errdefer manager.deinit(); errdefer manager.deinit();
manager.content_hash = header.file_hash;
// Read bitfield // Read bitfield
const bitfield_size = (header.piece_count + 7) / 8; const bitfield_size = (header.piece_count + 7) / 8;

View File

@@ -691,7 +691,13 @@ pub const PreSerializedPieceResponse = struct {
// Data length (4 bytes, big endian) // Data length (4 bytes, big endian)
// Data = [content_hash:32][piece_index:4][offset:4][piece_data:N] // Data = [content_hash:32][piece_index:4][offset:4][piece_data:N]
const data_len: u32 = @intCast(32 + 4 + 4 + data.len); const total_data_len = 32 + 4 + 4 + data.len;
if (total_data_len > std.math.maxInt(u32)) {
// Piece data too large for u32 length field — return empty response
result.header_len = 0;
return result;
}
const data_len: u32 = @intCast(total_data_len);
std.mem.writeInt(u32, result.header[off..][0..4], data_len, .big); std.mem.writeInt(u32, result.header[off..][0..4], data_len, .big);
off += 4; off += 4;
@@ -933,6 +939,7 @@ pub const FileSharingSession = struct {
allocator, allocator,
); );
manager.content_hash = self.content_hash;
try manager.setOutputFile(output_path); try manager.setOutputFile(output_path);
self.download_manager = manager; self.download_manager = manager;
self.status = .ready; self.status = .ready;
@@ -4567,7 +4574,7 @@ pub const FileSharingManager = struct {
else else
self.config.piece_size; self.config.piece_size;
existing.download_manager = download_mod.DownloadManager.init( var dm = download_mod.DownloadManager.init(
metadata.size, metadata.size,
metadata.piece_count, metadata.piece_count,
.rarest_first, .rarest_first,
@@ -4577,6 +4584,8 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err}); std.log.err("Failed to create download manager: {}", .{err});
return err; return err;
}; };
dm.content_hash = existing.content_hash;
existing.download_manager = dm;
} }
return; return;
} }
@@ -4611,7 +4620,7 @@ pub const FileSharingManager = struct {
else else
self.config.piece_size; self.config.piece_size;
session.download_manager = download_mod.DownloadManager.init( var new_dm = download_mod.DownloadManager.init(
metadata.size, metadata.size,
metadata.piece_count, metadata.piece_count,
.rarest_first, .rarest_first,
@@ -4621,12 +4630,14 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err}); std.log.err("Failed to create download manager: {}", .{err});
return err; return err;
}; };
new_dm.content_hash = session.content_hash;
session.download_manager = new_dm;
// Store session // Store session
self.sessions.put(session.session_id, session) catch |err| { self.sessions.put(session.session_id, session) catch |err| {
std.log.err("Failed to store session: {}", .{err}); std.log.err("Failed to store session: {}", .{err});
if (session.download_manager) |*dm| { if (session.download_manager) |*cleanup_dm| {
dm.deinit(); cleanup_dm.deinit();
} }
return err; return err;
}; };