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,
total_size,
piece_size,
null,
.rarest_first,
);

View File

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

View File

@@ -532,6 +532,8 @@ pub const DownloadManager = struct {
endgame_initialized: bool = false,
/// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates)
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(
total_size: u64,
@@ -756,7 +758,9 @@ pub const DownloadManager = struct {
/// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation
fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void {
// 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 total_cancelled: usize = 0;
while (true) {
var to_cancel: [1024]u32 = undefined;
var cancel_count: usize = 0;
@@ -770,6 +774,9 @@ pub const DownloadManager = struct {
}
}
if (cancel_count == 0) break;
total_cancelled += cancel_count;
// Move cancelled downloads back to pending queue
for (to_cancel[0..cancel_count]) |piece_index| {
_ = self.active_downloads.remove(piece_index);
@@ -818,9 +825,10 @@ pub const DownloadManager = struct {
};
}
}
}
if (cancel_count > 0) {
std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{cancel_count});
if (total_cancelled > 0) {
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_count = self.state.piece_count,
.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
@@ -2152,6 +2160,7 @@ pub const DownloadManager = struct {
resume_path: []const u8,
expected_total_size: u64,
expected_piece_size: u64,
expected_content_hash: ?[32]u8,
strategy: SelectionStrategy,
) Error!?DownloadManager {
// Validate path
@@ -2197,6 +2206,17 @@ pub const DownloadManager = struct {
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
var manager = try DownloadManager.init(
header.total_size,
@@ -2206,6 +2226,7 @@ pub const DownloadManager = struct {
allocator,
);
errdefer manager.deinit();
manager.content_hash = header.file_hash;
// Read bitfield
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 = [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);
off += 4;
@@ -933,6 +939,7 @@ pub const FileSharingSession = struct {
allocator,
);
manager.content_hash = self.content_hash;
try manager.setOutputFile(output_path);
self.download_manager = manager;
self.status = .ready;
@@ -4567,7 +4574,7 @@ pub const FileSharingManager = struct {
else
self.config.piece_size;
existing.download_manager = download_mod.DownloadManager.init(
var dm = download_mod.DownloadManager.init(
metadata.size,
metadata.piece_count,
.rarest_first,
@@ -4577,6 +4584,8 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err});
return err;
};
dm.content_hash = existing.content_hash;
existing.download_manager = dm;
}
return;
}
@@ -4611,7 +4620,7 @@ pub const FileSharingManager = struct {
else
self.config.piece_size;
session.download_manager = download_mod.DownloadManager.init(
var new_dm = download_mod.DownloadManager.init(
metadata.size,
metadata.piece_count,
.rarest_first,
@@ -4621,12 +4630,14 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err});
return err;
};
new_dm.content_hash = session.content_hash;
session.download_manager = new_dm;
// Store session
self.sessions.put(session.session_id, session) catch |err| {
std.log.err("Failed to store session: {}", .{err});
if (session.download_manager) |*dm| {
dm.deinit();
if (session.download_manager) |*cleanup_dm| {
cleanup_dm.deinit();
}
return err;
};