630 lines
22 KiB
Zig
630 lines
22 KiB
Zig
//! Docker P2P Test Peer
|
|
//!
|
|
//! A simple peer binary that can act as either a seeder or leecher.
|
|
//! Controlled via environment variables:
|
|
//! - PEER_MODE: "seeder" or "leecher"
|
|
//! - PEER_PORT: Port to listen on (default: 8080)
|
|
//! - SEEDER_HOST: Host of seeder to connect to (for leecher mode)
|
|
//! - SEEDER_PORT: Port of seeder (for leecher mode)
|
|
//! - FILE_SIZE_MB: Size of test file in MB (default: 10)
|
|
|
|
const std = @import("std");
|
|
const p2p = @import("p2p");
|
|
const files = @import("files");
|
|
const core = @import("core");
|
|
|
|
const P2P = p2p.P2P;
|
|
const P2PConfig = p2p.P2PConfig;
|
|
const Address = core.Address;
|
|
const FileMetadata = files.hash.FileMetadata;
|
|
|
|
const METADATA_PATH = "/shared/metadata.bin";
|
|
const DOWNLOAD_PATH = "/data/downloaded_file.bin";
|
|
|
|
pub fn main() !void {
|
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
|
defer _ = gpa.deinit();
|
|
const allocator = gpa.allocator();
|
|
|
|
// Parse environment variables
|
|
const mode = std.posix.getenv("PEER_MODE") orelse "seeder";
|
|
const port_str = std.posix.getenv("PEER_PORT") orelse "8080";
|
|
const port = std.fmt.parseInt(u16, port_str, 10) catch 8080;
|
|
const file_size_str = std.posix.getenv("FILE_SIZE_MB") orelse "10";
|
|
const file_size_mb = std.fmt.parseInt(u64, file_size_str, 10) catch 10;
|
|
|
|
const file_size = file_size_mb * 1024 * 1024;
|
|
|
|
std.debug.print("\n", .{});
|
|
std.debug.print("========================================\n", .{});
|
|
std.debug.print(" P2P Docker Test Peer\n", .{});
|
|
std.debug.print("========================================\n", .{});
|
|
std.debug.print("Mode: {s}\n", .{mode});
|
|
std.debug.print("Port: {}\n", .{port});
|
|
std.debug.print("File Size: {} MB\n", .{file_size_mb});
|
|
std.debug.print("========================================\n\n", .{});
|
|
|
|
if (std.mem.eql(u8, mode, "seeder")) {
|
|
const leecher_count_str = std.posix.getenv("LEECHER_COUNT") orelse "3";
|
|
const leecher_count = std.fmt.parseInt(u32, leecher_count_str, 10) catch 3;
|
|
try runSeeder(allocator, port, file_size, leecher_count);
|
|
} else if (std.mem.eql(u8, mode, "leecher")) {
|
|
const seeder_host = std.posix.getenv("SEEDER_HOST") orelse "seeder";
|
|
const seeder_port_str = std.posix.getenv("SEEDER_PORT") orelse "8080";
|
|
const seeder_port = std.fmt.parseInt(u16, seeder_port_str, 10) catch 8080;
|
|
try runLeecher(allocator, port, seeder_host, seeder_port, file_size);
|
|
} else {
|
|
std.debug.print("ERROR: Unknown mode '{s}'. Use 'seeder' or 'leecher'\n", .{mode});
|
|
return error.InvalidMode;
|
|
}
|
|
}
|
|
|
|
/// Serialize FileMetadata to a binary format
|
|
fn serializeMetadata(metadata: FileMetadata, allocator: std.mem.Allocator) ![]u8 {
|
|
// Format: name_len(4) + name + size(8) + piece_count(4) + created_at(8) + modified_at(8) + piece_hashes
|
|
const name_len: u32 = @intCast(metadata.name.len);
|
|
const total_size = 4 + metadata.name.len + 8 + 4 + 8 + 8 + (metadata.piece_count * 32);
|
|
|
|
const buffer = try allocator.alloc(u8, total_size);
|
|
var offset: usize = 0;
|
|
|
|
// Name length and name
|
|
@memcpy(buffer[offset .. offset + 4], std.mem.asBytes(&name_len));
|
|
offset += 4;
|
|
@memcpy(buffer[offset .. offset + metadata.name.len], metadata.name);
|
|
offset += metadata.name.len;
|
|
|
|
// Size
|
|
@memcpy(buffer[offset .. offset + 8], std.mem.asBytes(&metadata.size));
|
|
offset += 8;
|
|
|
|
// Piece count
|
|
@memcpy(buffer[offset .. offset + 4], std.mem.asBytes(&metadata.piece_count));
|
|
offset += 4;
|
|
|
|
// Created at
|
|
@memcpy(buffer[offset .. offset + 8], std.mem.asBytes(&metadata.created_at));
|
|
offset += 8;
|
|
|
|
// Modified at
|
|
@memcpy(buffer[offset .. offset + 8], std.mem.asBytes(&metadata.modified_at));
|
|
offset += 8;
|
|
|
|
// Piece hashes
|
|
for (metadata.piece_hashes) |hash| {
|
|
@memcpy(buffer[offset .. offset + 32], &hash);
|
|
offset += 32;
|
|
}
|
|
|
|
return buffer;
|
|
}
|
|
|
|
/// Deserialize FileMetadata from binary format
|
|
fn deserializeMetadata(data: []const u8, allocator: std.mem.Allocator) !FileMetadata {
|
|
var offset: usize = 0;
|
|
|
|
// Name length and name
|
|
const name_len = std.mem.bytesToValue(u32, data[offset .. offset + 4][0..4]);
|
|
offset += 4;
|
|
const name = try allocator.dupe(u8, data[offset .. offset + name_len]);
|
|
offset += name_len;
|
|
|
|
// Size
|
|
const size = std.mem.bytesToValue(u64, data[offset .. offset + 8][0..8]);
|
|
offset += 8;
|
|
|
|
// Piece count
|
|
const piece_count = std.mem.bytesToValue(u32, data[offset .. offset + 4][0..4]);
|
|
offset += 4;
|
|
|
|
// Created at
|
|
const created_at = std.mem.bytesToValue(i64, data[offset .. offset + 8][0..8]);
|
|
offset += 8;
|
|
|
|
// Modified at
|
|
const modified_at = std.mem.bytesToValue(i64, data[offset .. offset + 8][0..8]);
|
|
offset += 8;
|
|
|
|
// Piece hashes
|
|
const piece_hashes = try allocator.alloc([32]u8, piece_count);
|
|
for (0..piece_count) |i| {
|
|
@memcpy(&piece_hashes[i], data[offset .. offset + 32][0..32]);
|
|
offset += 32;
|
|
}
|
|
|
|
return FileMetadata{
|
|
.name = name,
|
|
.size = size,
|
|
.piece_count = piece_count,
|
|
.piece_hashes = piece_hashes,
|
|
.created_at = created_at,
|
|
.modified_at = modified_at,
|
|
};
|
|
}
|
|
|
|
fn runSeeder(allocator: std.mem.Allocator, port: u16, file_size: u64, expected_leechers: u32) !void {
|
|
std.debug.print("[SEEDER] Starting seeder on port {}...\n", .{port});
|
|
std.debug.print("[SEEDER] Expecting {} leecher(s) to complete download\n", .{expected_leechers});
|
|
|
|
// Create directories
|
|
std.fs.cwd().makeDir("data") catch |e| switch (e) {
|
|
error.PathAlreadyExists => {},
|
|
else => return e,
|
|
};
|
|
|
|
// Ensure /shared exists (Docker volume)
|
|
std.fs.makeDirAbsolute("/shared") catch |e| switch (e) {
|
|
error.PathAlreadyExists => {},
|
|
else => {
|
|
std.debug.print("[SEEDER] Warning: Could not create /shared: {}\n", .{e});
|
|
},
|
|
};
|
|
|
|
// Create test file with deterministic content
|
|
const test_file = "/data/data/test_file.bin";
|
|
|
|
// Make parent directory
|
|
std.fs.makeDirAbsolute("/data/data") catch |e| switch (e) {
|
|
error.PathAlreadyExists => {},
|
|
else => return e,
|
|
};
|
|
|
|
std.debug.print("[SEEDER] Creating test file: {} bytes...\n", .{file_size});
|
|
|
|
{
|
|
const file = try std.fs.createFileAbsolute(test_file, .{});
|
|
defer file.close();
|
|
|
|
// Write deterministic pattern
|
|
var buffer: [4096]u8 = undefined;
|
|
var written: u64 = 0;
|
|
var chunk_num: u64 = 0;
|
|
while (written < file_size) {
|
|
const remaining = file_size - written;
|
|
const to_write = @min(buffer.len, remaining);
|
|
|
|
// Fill buffer with pattern based on position
|
|
for (buffer[0..to_write], 0..) |*b, i| {
|
|
b.* = @truncate((chunk_num * buffer.len + i) % 251);
|
|
}
|
|
|
|
try file.writeAll(buffer[0..to_write]);
|
|
written += to_write;
|
|
chunk_num += 1;
|
|
}
|
|
}
|
|
|
|
// Calculate file hash for verification
|
|
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
|
{
|
|
const file = try std.fs.openFileAbsolute(test_file, .{});
|
|
defer file.close();
|
|
|
|
var buffer: [8192]u8 = undefined;
|
|
while (true) {
|
|
const n = try file.read(&buffer);
|
|
if (n == 0) break;
|
|
hasher.update(buffer[0..n]);
|
|
}
|
|
}
|
|
const file_hash = hasher.finalResult();
|
|
std.debug.print("[SEEDER] File created. Hash: {x}\n", .{file_hash});
|
|
|
|
// Initialize P2P library
|
|
var config = P2PConfig.default();
|
|
config.network.listen_port = port;
|
|
config.network.enable_nat_traversal = false;
|
|
// Allow more simultaneous connections for multi-peer testing
|
|
config.network.connection_rate_limit = 100;
|
|
config.network.connection_burst_size = 50;
|
|
config.file_sharing.allowed_share_directories = &[_][]const u8{ "/data", "/data/data", ".", "data" };
|
|
config.file_sharing.temp_dir = "/data/temp";
|
|
|
|
var p2p_instance = P2P.init(allocator, config) catch |e| {
|
|
std.debug.print("[SEEDER] Failed to initialize P2P: {}\n", .{e});
|
|
return e;
|
|
};
|
|
defer p2p_instance.deinit();
|
|
|
|
p2p_instance.start() catch |e| {
|
|
std.debug.print("[SEEDER] Failed to start P2P: {}\n", .{e});
|
|
return e;
|
|
};
|
|
defer p2p_instance.stop() catch {};
|
|
|
|
// Start listening on all interfaces
|
|
const listen_addr = Address.ipv4(.{ 0, 0, 0, 0 }, port);
|
|
p2p_instance.startListening(listen_addr) catch |e| {
|
|
std.debug.print("[SEEDER] Failed to start listening: {}\n", .{e});
|
|
return e;
|
|
};
|
|
std.debug.print("[SEEDER] Listening on 0.0.0.0:{}\n", .{port});
|
|
|
|
// Share the file
|
|
const session_id = p2p_instance.addFile(test_file) catch |e| {
|
|
std.debug.print("[SEEDER] Failed to add file: {}\n", .{e});
|
|
return e;
|
|
};
|
|
std.debug.print("[SEEDER] File shared with session ID: {}\n", .{session_id});
|
|
|
|
// Start sharing
|
|
p2p_instance.startSharing(session_id) catch |e| {
|
|
std.debug.print("[SEEDER] Failed to start sharing: {}\n", .{e});
|
|
return e;
|
|
};
|
|
|
|
// Get file metadata and save to shared volume
|
|
const metadata = p2p_instance.getFileMetadata(session_id) catch |e| {
|
|
std.debug.print("[SEEDER] Failed to get metadata: {}\n", .{e});
|
|
return e;
|
|
} orelse {
|
|
std.debug.print("[SEEDER] No metadata found for session\n", .{});
|
|
return error.MetadataNotFound;
|
|
};
|
|
|
|
std.debug.print("[SEEDER] Got metadata - name: {s}, size: {}, pieces: {}\n", .{
|
|
metadata.name,
|
|
metadata.size,
|
|
metadata.piece_count,
|
|
});
|
|
|
|
// Serialize and save metadata
|
|
const serialized = try serializeMetadata(metadata, allocator);
|
|
defer allocator.free(serialized);
|
|
|
|
{
|
|
const meta_file = std.fs.createFileAbsolute(METADATA_PATH, .{}) catch |e| {
|
|
std.debug.print("[SEEDER] Failed to create metadata file: {}\n", .{e});
|
|
return e;
|
|
};
|
|
defer meta_file.close();
|
|
try meta_file.writeAll(serialized);
|
|
}
|
|
std.debug.print("[SEEDER] Metadata saved to {s} ({} bytes)\n", .{ METADATA_PATH, serialized.len });
|
|
|
|
// Ready to serve
|
|
std.debug.print("\n[SEEDER] Ready to serve file!\n", .{});
|
|
std.debug.print("[SEEDER] Expected hash: {x}\n", .{file_hash});
|
|
|
|
// Calculate expected total upload (file_size * number of leechers)
|
|
const expected_upload = file_size * expected_leechers;
|
|
std.debug.print("[SEEDER] Will exit after uploading {} bytes ({} MB) to {} leecher(s)\n", .{
|
|
expected_upload,
|
|
expected_upload / (1024 * 1024),
|
|
expected_leechers,
|
|
});
|
|
|
|
// Run main loop
|
|
var stats_timer: u64 = 0;
|
|
var last_uploaded: u64 = 0;
|
|
var upload_target_reached = false;
|
|
var time_since_target: u64 = 0;
|
|
var had_connections = false;
|
|
const max_test_duration: u64 = 300; // 5 minute max
|
|
const max_wait_after_target: u64 = 120; // 2 minutes max after target reached
|
|
|
|
var update_counter: u64 = 0;
|
|
while (stats_timer < max_test_duration) {
|
|
// Fast update loop - 10ms for high throughput
|
|
std.Thread.sleep(10 * std.time.ns_per_ms);
|
|
update_counter += 1;
|
|
|
|
// Process events
|
|
while (p2p_instance.getEventCount() > 0) {
|
|
if (p2p_instance.getNextEvent()) |event| {
|
|
std.debug.print("[SEEDER] Event: {}\n", .{event.event_type});
|
|
}
|
|
}
|
|
|
|
// Call update to process network activity
|
|
p2p_instance.update() catch {};
|
|
|
|
// Increment stats timer every 100 updates (= 1 second)
|
|
if (update_counter % 100 == 0) {
|
|
stats_timer += 1;
|
|
}
|
|
|
|
const stats = p2p_instance.getStats();
|
|
const uploaded = stats.total_uploaded.load(.acquire);
|
|
const connections = stats.active_connections.load(.acquire);
|
|
|
|
// Track if we ever had connections
|
|
if (connections > 0) {
|
|
had_connections = true;
|
|
}
|
|
|
|
// Print stats every 5 seconds (500 updates)
|
|
if (update_counter % 500 == 0) {
|
|
const speed = (uploaded - last_uploaded) / 5;
|
|
last_uploaded = uploaded;
|
|
const progress: f32 = if (expected_upload > 0)
|
|
@as(f32, @floatFromInt(uploaded)) / @as(f32, @floatFromInt(expected_upload)) * 100.0
|
|
else
|
|
0.0;
|
|
std.debug.print("[SEEDER] Stats - Connections: {}, Uploaded: {} / {} bytes ({d:.1}%), {} KB/s, Uptime: {}s\n", .{
|
|
connections,
|
|
uploaded,
|
|
expected_upload,
|
|
progress,
|
|
speed / 1024,
|
|
stats_timer,
|
|
});
|
|
}
|
|
|
|
// Check if we've uploaded enough data (queued)
|
|
if (uploaded >= expected_upload and !upload_target_reached) {
|
|
upload_target_reached = true;
|
|
std.debug.print("\n[SEEDER] Upload target reached! Waiting for all leechers to complete...\n", .{});
|
|
}
|
|
|
|
if (upload_target_reached) {
|
|
time_since_target += 1;
|
|
|
|
// Success: All peers disconnected after we had connections
|
|
if (had_connections and connections == 0) {
|
|
std.debug.print("[SEEDER] All leechers disconnected. Test PASSED!\n", .{});
|
|
std.debug.print("[SEEDER] Successfully uploaded {} bytes to {} leecher(s)\n", .{
|
|
uploaded,
|
|
expected_leechers,
|
|
});
|
|
break;
|
|
}
|
|
|
|
// Timeout waiting for peers to disconnect
|
|
if (time_since_target >= max_wait_after_target) {
|
|
std.debug.print("[SEEDER] Timeout waiting for leechers to complete. {} connections still active.\n", .{connections});
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (stats_timer >= max_test_duration) {
|
|
const stats = p2p_instance.getStats();
|
|
const uploaded = stats.total_uploaded.load(.acquire);
|
|
std.debug.print("[SEEDER] Test TIMEOUT after {} seconds. Uploaded {} / {} bytes\n", .{
|
|
stats_timer,
|
|
uploaded,
|
|
expected_upload,
|
|
});
|
|
}
|
|
|
|
std.debug.print("\n[SEEDER] Shutting down...\n", .{});
|
|
}
|
|
|
|
fn runLeecher(
|
|
allocator: std.mem.Allocator,
|
|
port: u16,
|
|
seeder_host: []const u8,
|
|
seeder_port: u16,
|
|
file_size: u64,
|
|
) !void {
|
|
std.debug.print("[LEECHER] Starting leecher on port {}...\n", .{port});
|
|
std.debug.print("[LEECHER] Will connect to seeder at {s}:{}\n", .{ seeder_host, seeder_port });
|
|
|
|
// Create directories
|
|
std.fs.makeDirAbsolute("/data/data") catch |e| switch (e) {
|
|
error.PathAlreadyExists => {},
|
|
else => return e,
|
|
};
|
|
|
|
// Wait for metadata file from seeder
|
|
std.debug.print("[LEECHER] Waiting for metadata file...\n", .{});
|
|
var wait_count: u32 = 0;
|
|
while (wait_count < 30) {
|
|
if (std.fs.openFileAbsolute(METADATA_PATH, .{})) |file| {
|
|
file.close();
|
|
break;
|
|
} else |_| {
|
|
std.Thread.sleep(1 * std.time.ns_per_s);
|
|
wait_count += 1;
|
|
if (wait_count % 5 == 0) {
|
|
std.debug.print("[LEECHER] Still waiting for metadata... ({} seconds)\n", .{wait_count});
|
|
}
|
|
}
|
|
}
|
|
|
|
if (wait_count >= 30) {
|
|
std.debug.print("[LEECHER] Timeout waiting for metadata file\n", .{});
|
|
return error.MetadataTimeout;
|
|
}
|
|
|
|
// Read and deserialize metadata
|
|
std.debug.print("[LEECHER] Reading metadata...\n", .{});
|
|
const metadata_data = blk: {
|
|
const file = try std.fs.openFileAbsolute(METADATA_PATH, .{});
|
|
defer file.close();
|
|
const stat = try file.stat();
|
|
const data = try allocator.alloc(u8, stat.size);
|
|
_ = try file.readAll(data);
|
|
break :blk data;
|
|
};
|
|
defer allocator.free(metadata_data);
|
|
|
|
const metadata = try deserializeMetadata(metadata_data, allocator);
|
|
std.debug.print("[LEECHER] Got metadata - name: {s}, size: {}, pieces: {}\n", .{
|
|
metadata.name,
|
|
metadata.size,
|
|
metadata.piece_count,
|
|
});
|
|
|
|
// Initialize P2P library
|
|
var config = P2PConfig.default();
|
|
config.network.listen_port = port;
|
|
config.network.enable_nat_traversal = false;
|
|
config.file_sharing.allowed_share_directories = &[_][]const u8{ "/data", "/data/data", ".", "data" };
|
|
config.file_sharing.temp_dir = "/data/temp";
|
|
|
|
var p2p_instance = P2P.init(allocator, config) catch |e| {
|
|
std.debug.print("[LEECHER] Failed to initialize P2P: {}\n", .{e});
|
|
return e;
|
|
};
|
|
defer p2p_instance.deinit();
|
|
|
|
p2p_instance.start() catch |e| {
|
|
std.debug.print("[LEECHER] Failed to start P2P: {}\n", .{e});
|
|
return e;
|
|
};
|
|
defer p2p_instance.stop() catch {};
|
|
|
|
std.debug.print("[LEECHER] P2P library started\n", .{});
|
|
|
|
// Start download BEFORE connecting (so we can receive bitfield)
|
|
std.debug.print("[LEECHER] Starting download to {s}...\n", .{DOWNLOAD_PATH});
|
|
const download_session_id = p2p_instance.downloadFile(metadata, DOWNLOAD_PATH) catch |e| {
|
|
std.debug.print("[LEECHER] Failed to start download: {}\n", .{e});
|
|
return e;
|
|
};
|
|
std.debug.print("[LEECHER] Download session created: {}\n", .{download_session_id});
|
|
|
|
// Resolve and connect to seeder
|
|
std.debug.print("[LEECHER] Resolving seeder address...\n", .{});
|
|
const seeder_addr = blk: {
|
|
const addr_list = std.net.getAddressList(allocator, seeder_host, seeder_port) catch |e| {
|
|
std.debug.print("[LEECHER] DNS lookup failed: {}\n", .{e});
|
|
const addr = std.net.Address.parseIp4(seeder_host, seeder_port) catch |e2| {
|
|
std.debug.print("[LEECHER] IP parse failed: {}\n", .{e2});
|
|
return e;
|
|
};
|
|
break :blk addr;
|
|
};
|
|
defer addr_list.deinit();
|
|
|
|
if (addr_list.addrs.len == 0) {
|
|
std.debug.print("[LEECHER] No addresses found\n", .{});
|
|
return error.AddressNotFound;
|
|
}
|
|
break :blk addr_list.addrs[0];
|
|
};
|
|
|
|
const core_addr = Address.ipv4(
|
|
@bitCast(seeder_addr.in.sa.addr),
|
|
seeder_addr.getPort(),
|
|
);
|
|
|
|
std.debug.print("[LEECHER] Connecting to seeder...\n", .{});
|
|
const peer_id = p2p_instance.connectToPeer(core_addr) catch |e| {
|
|
std.debug.print("[LEECHER] Failed to connect: {}\n", .{e});
|
|
return e;
|
|
};
|
|
std.debug.print("[LEECHER] Connected! Peer ID: {x}\n", .{peer_id.bytes[0..8].*});
|
|
|
|
// Monitor download progress
|
|
const start_time = std.time.milliTimestamp();
|
|
var download_complete = false;
|
|
var last_downloaded: u64 = 0;
|
|
|
|
var last_progress_time: i64 = 0;
|
|
while (!download_complete) {
|
|
// Fast update loop - 10ms for high throughput
|
|
std.Thread.sleep(10 * std.time.ns_per_ms);
|
|
|
|
// Process events
|
|
while (p2p_instance.getNextEvent()) |event| {
|
|
std.debug.print("[LEECHER] Event: {}\n", .{event.event_type});
|
|
if (event.event_type == .file_download_completed) {
|
|
download_complete = true;
|
|
}
|
|
}
|
|
|
|
// Call update to process network activity
|
|
p2p_instance.update() catch {};
|
|
|
|
const elapsed = std.time.milliTimestamp() - start_time;
|
|
// Print progress every 2 seconds
|
|
if (elapsed - last_progress_time >= 2000) {
|
|
last_progress_time = elapsed;
|
|
const stats = p2p_instance.getStats();
|
|
const downloaded = stats.total_downloaded.load(.acquire);
|
|
const speed = if (elapsed > 0) @as(u64, @intCast(downloaded)) * 1000 / @as(u64, @intCast(elapsed)) else 0;
|
|
|
|
// Calculate progress
|
|
const progress = if (file_size > 0)
|
|
@as(f32, @floatFromInt(downloaded)) / @as(f32, @floatFromInt(file_size)) * 100.0
|
|
else
|
|
0.0;
|
|
|
|
std.debug.print("[LEECHER] Progress: {d:.1}% ({} / {} bytes) - {} KB/s\n", .{
|
|
progress,
|
|
downloaded,
|
|
file_size,
|
|
speed / 1024,
|
|
});
|
|
|
|
// Check if download is complete by bytes
|
|
if (downloaded >= file_size) {
|
|
std.debug.print("[LEECHER] Download appears complete by size!\n", .{});
|
|
download_complete = true;
|
|
}
|
|
|
|
last_downloaded = downloaded;
|
|
}
|
|
|
|
// Timeout after 120 seconds
|
|
if (elapsed > 120000) {
|
|
std.debug.print("[LEECHER] Download timeout after 120 seconds\n", .{});
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Verify downloaded file
|
|
if (download_complete) {
|
|
std.debug.print("\n[LEECHER] Verifying downloaded file...\n", .{});
|
|
|
|
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
|
{
|
|
const file = std.fs.openFileAbsolute(DOWNLOAD_PATH, .{}) catch |e| {
|
|
std.debug.print("[LEECHER] Could not open downloaded file: {}\n", .{e});
|
|
return;
|
|
};
|
|
defer file.close();
|
|
|
|
var buffer: [8192]u8 = undefined;
|
|
while (true) {
|
|
const n = file.read(&buffer) catch break;
|
|
if (n == 0) break;
|
|
hasher.update(buffer[0..n]);
|
|
}
|
|
}
|
|
const downloaded_hash = hasher.finalResult();
|
|
|
|
// Compare with expected (generate expected hash same way as seeder)
|
|
var expected_hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
|
{
|
|
var buffer: [4096]u8 = undefined;
|
|
var written: u64 = 0;
|
|
var chunk_num: u64 = 0;
|
|
while (written < file_size) {
|
|
const remaining = file_size - written;
|
|
const to_write = @min(buffer.len, remaining);
|
|
|
|
for (buffer[0..to_write], 0..) |*b, i| {
|
|
b.* = @truncate((chunk_num * buffer.len + i) % 251);
|
|
}
|
|
|
|
expected_hasher.update(buffer[0..to_write]);
|
|
written += to_write;
|
|
chunk_num += 1;
|
|
}
|
|
}
|
|
const expected_hash = expected_hasher.finalResult();
|
|
|
|
std.debug.print("[LEECHER] Downloaded hash: {x}\n", .{downloaded_hash});
|
|
std.debug.print("[LEECHER] Expected hash: {x}\n", .{expected_hash});
|
|
|
|
if (std.mem.eql(u8, &downloaded_hash, &expected_hash)) {
|
|
std.debug.print("\n[LEECHER] SUCCESS! File verified correctly!\n", .{});
|
|
} else {
|
|
std.debug.print("\n[LEECHER] FAILED! Hash mismatch!\n", .{});
|
|
}
|
|
}
|
|
|
|
const total_time = std.time.milliTimestamp() - start_time;
|
|
const stats = p2p_instance.getStats();
|
|
const total_downloaded = stats.total_downloaded.load(.acquire);
|
|
const avg_speed = if (total_time > 0) total_downloaded * 1000 / @as(u64, @intCast(total_time)) else 0;
|
|
|
|
std.debug.print("\n[LEECHER] Test complete.\n", .{});
|
|
std.debug.print("[LEECHER] Total downloaded: {} bytes in {} ms\n", .{ total_downloaded, total_time });
|
|
std.debug.print("[LEECHER] Average speed: {} KB/s ({} MB/s)\n", .{ avg_speed / 1024, avg_speed / (1024 * 1024) });
|
|
}
|