Files
zigp2p/tests/files/test_hash.zig
2026-02-06 21:03:59 -03:00

530 lines
20 KiB
Zig

//! Tests for hash functions and integrity verification
const std = @import("std");
const testing = std.testing;
const HashModule = @import("../src/files/hash.zig");
const { HashUtils, FileMetadata, PieceData, HashPool, VerificationBatch } = HashModule;
test "hash utilities - SHA-256 calculation" {
const test_data = "Hello, World! This is a test message for hashing.";
const hash = try HashUtils.sha256(test_data);
// Verify hash is 32 bytes
try testing.expectEqual(@as(usize, 32), hash.len);
// Verify hash is not all zeros (basic sanity check)
var all_zeros = true;
for (hash) |byte| {
if (byte != 0) {
all_zeros = false;
break;
}
}
try testing.expect(!all_zeros);
}
test "hash utilities - verification" {
const test_data = "Test data for verification";
const hash = try HashUtils.sha256(test_data);
// Should verify correctly
const is_valid = try HashUtils.verify(test_data, hash);
try testing.expect(is_valid);
// Should fail with different data
const wrong_data = "Different test data";
const is_invalid = try HashUtils.verify(wrong_data, hash);
try testing.expect(!is_invalid);
}
test "hash utilities - content hash generation" {
const allocator = testing.allocator;
// Create multiple piece hashes
var piece_hashes = std.ArrayList([32]u8).init(allocator);
try piece_hashes.append(try HashUtils.sha256("piece 0"));
try piece_hashes.append(try HashUtils.sha256("piece 1"));
try piece_hashes.append(try HashUtils.sha256("piece 2"));
const content_hash = try HashUtils.contentHash(piece_hashes.items);
try testing.expectEqual(@as(usize, 32), content_hash.len);
// Same pieces should generate same content hash
const content_hash2 = try HashUtils.contentHash(piece_hashes.items);
try testing.expect(mem.eql(u8, &content_hash, &content_hash2));
piece_hashes.deinit();
}
test "hash utilities - hex conversion" {
const allocator = testing.allocator;
const test_data = "Hex conversion test data";
const hash = try HashUtils.sha256(test_data);
// Convert to hex
const hex_str = try HashUtils.toHex(hash, allocator);
defer allocator.free(hex_str);
// Should be 64 characters (32 bytes * 2 hex chars per byte)
try testing.expectEqual(@as(usize, 64), hex_str.len);
// Should contain only hex characters
for (hex_str) |c| {
try testing.expect((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f') or (c >= 'A' and c <= 'F'));
}
// Parse back to hash
const parsed_hash = try HashUtils.fromHex(hex_str);
try testing.expect(mem.eql(u8, &hash, &parsed_hash));
}
test "hash utilities - invalid hex parsing" {
// Test invalid hex strings
const invalid_hex_1 = "invalid";
const invalid_hex_2 = "123"; // Odd length
const invalid_hex_3 = "gg1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"; // Invalid chars
try testing.expectError(error.InvalidData, HashUtils.fromHex(invalid_hex_1));
try testing.expectError(error.InvalidData, HashUtils.fromHex(invalid_hex_2));
try testing.expectError(error.InvalidData, HashUtils.fromHex(invalid_hex_3));
}
test "file metadata creation and operations" {
const allocator = testing.allocator;
// Create piece hashes
const piece_hashes = try allocator.alloc([32]u8, 5);
for (piece_hashes) |*hash| {
hash.* = try HashUtils.random(allocator);
}
// Create metadata
const metadata = try FileMetadata.create("test_file.bin", 1024 * 1024, piece_hashes, allocator);
defer allocator.free(piece_hashes);
try testing.expectEqualSlices(u8, "test_file.bin", metadata.name);
try testing.expectEqual(@as(u64, 1024 * 1024), metadata.size);
try testing.expectEqual(@as(u32, 5), metadata.piece_count);
try testing.expectEqualSlices([32]u8, piece_hashes, metadata.piece_hashes);
try testing.expect(metadata.created_at > 0);
try testing.expect(metadata.modified_at > 0);
// Test total size calculation
try testing.expectEqual(@as(u64, 1024 * 1024), metadata.totalSize());
}
test "file metadata - piece size calculation" {
const allocator = testing.allocator;
const piece_hashes = try allocator.alloc([32]u8, 3);
for (piece_hashes) |*hash| {
hash.* = try HashUtils.random(allocator);
}
const metadata = try FileMetadata.create("piece_test.bin", 50 * 1024 * 1024, piece_hashes, allocator);
defer allocator.free(piece_hashes);
const piece_size: u64 = 16 * 1024 * 1024; // 16MB
// Test piece sizes
try testing.expectEqual(@as(usize, piece_size), metadata.pieceSize(0));
try testing.expectEqual(@as(usize, piece_size), metadata.pieceSize(1));
// Last piece might be smaller (50MB - 32MB = 18MB)
const last_piece_size = metadata.pieceSize(2);
try testing.expect(last_piece_size <= piece_size);
try testing.expectEqual(@as(usize, 18 * 1024 * 1024), last_piece_size);
allocator.free(piece_hashes);
}
test "file metadata - verification" {
const allocator = testing.allocator;
// Create valid pieces
const piece_hashes = try allocator.alloc([32]u8, 2);
piece_hashes[0] = try HashUtils.sha256("piece 0 data");
piece_hashes[1] = try HashUtils.sha256("piece 1 data");
const metadata = try FileMetadata.create("verify_test.bin", 32, piece_hashes, allocator);
// Create valid piece data
var pieces = std.ArrayList(PieceData).init(allocator);
try pieces.append(try PieceData.create(0, "piece 0 data"));
try pieces.append(try PieceData.create(1, "piece 1 data"));
// Should verify successfully
const is_valid = try metadata.verify(pieces.items);
try testing.expect(is_valid);
// Test with wrong piece count
const wrong_pieces = pieces.items[0..1]; // Same slice, different length expectation
const is_invalid_count = try metadata.verify(wrong_pieces);
try testing.expect(!is_invalid_count);
pieces.deinit();
allocator.free(piece_hashes);
}
test "piece data creation and verification" {
const test_data = "This is a test piece of data for verification";
const piece = try PieceData.create(5, test_data);
try testing.expectEqual(@as(u32, 5), piece.index);
try testing.expectEqualSlices(u8, test_data, piece.data);
// Should verify correctly
const is_valid = try piece.verify();
try testing.expect(is_valid);
// Test with tampered data
const tampered_piece = PieceData{
.index = 5,
.data = "Tampered piece data content",
.hash = piece.hash,
};
const is_invalid = try tampered_piece.verify();
try testing.expect(!is_invalid);
}
test "verification result creation" {
const expected_hash = try HashUtils.sha256("expected");
const actual_hash = try HashUtils.sha256("actual");
// Test success result
const success_result = VerificationResult.success(0, expected_hash, actual_hash);
try testing.expect(success_result.is_valid);
try testing.expectEqual(@as(u32, 0), success_result.piece_index.?);
try testing.expect(mem.eql(u8, &expected_hash, &success_result.expected_hash));
try testing.expect(mem.eql(u8, &actual_hash, &success_result.actual_hash));
// Test failure result
const failure_result = VerificationResult.failure(1, expected_hash, actual_hash);
try testing.expect(!failure_result.is_valid);
try testing.expectEqual(@as(u32, 1), failure_result.piece_index.?);
}
test "hash pool operations" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create test metadata
const piece_hashes = try allocator.alloc([32]u8, 3);
piece_hashes[0] = try HashUtils.sha256("piece 0 data");
piece_hashes[1] = try HashUtils.sha256("piece 1 data");
piece_hashes[2] = try HashUtils.sha256("piece 2 data");
const metadata = try FileMetadata.create("pool_test.bin", 48, piece_hashes, allocator);
defer allocator.free(piece_hashes);
// Create test pieces
var pieces = std.ArrayList(PieceData).init(allocator);
try pieces.append(try PieceData.create(0, "piece 0 data"));
try pieces.append(try PieceData.create(1, "piece 1 data"));
try pieces.append(try PieceData.create(2, "piece 2 data"));
// Verify pieces
var batch = try pool.verifyPieces(metadata, pieces.items);
defer batch.deinit();
try testing.expect(batch.isCompleteSuccess());
try testing.expectEqual(@as(f32, 1.0), batch.successRate());
try testing.expectEqual(@as(u32, 3), batch.valid_pieces);
pieces.deinit();
}
test "hash pool with failed verification" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create metadata with one wrong hash
const piece_hashes = try allocator.alloc([32]u8, 2);
piece_hashes[0] = try HashUtils.sha256("piece 0 data");
piece_hashes[1] = try HashUtils.sha256("piece 1 data"); // This will be wrong
const metadata = try FileMetadata.create("fail_test.bin", 32, piece_hashes, allocator);
defer allocator.free(piece_hashes);
// Create pieces with one invalid piece
var pieces = std.ArrayList(PieceData).init(allocator);
try pieces.append(try PieceData.create(0, "piece 0 data"));
try pieces.append(try PieceData.create(1, "wrong piece 1 data")); // Wrong data
// Verify pieces
var batch = try pool.verifyPieces(metadata, pieces.items);
defer batch.deinit();
try testing.expect(!batch.isCompleteSuccess());
try testing.expectEqual(@as(f32, 0.5), batch.successRate());
try testing.expectEqual(@as(u32, 1), batch.valid_pieces);
pieces.deinit();
}
test "content address generation" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create metadata
const piece_hashes = try allocator.alloc([32]u8, 2);
piece_hashes[0] = try HashUtils.random(allocator);
piece_hashes[1] = try HashUtils.random(allocator);
const metadata = try FileMetadata.create("address_test.bin", 2048, piece_hashes, allocator);
defer allocator.free(piece_hashes);
// Generate content address
const content_address = try pool.generateContentAddress(metadata);
try testing.expectEqual(@as(usize, 32), content_address.len);
// Same metadata should generate same address
const content_address2 = try pool.generateContentAddress(metadata);
try testing.expect(mem.eql(u8, &content_address, &content_address2));
}
test "random hash generation" {
const allocator = testing.allocator;
// Generate multiple random hashes
const hash1 = try HashUtils.random(allocator);
const hash2 = try HashUtils.random(allocator);
const hash3 = try HashUtils.random(allocator);
// Should be different
try testing.expect(!mem.eql(u8, &hash1, &hash2));
try testing.expect(!mem.eql(u8, &hash2, &hash3));
try testing.expect(!mem.eql(u8, &hash1, &hash3));
// Should all be 32 bytes
try testing.expectEqual(@as(usize, 32), hash1.len);
try testing.expectEqual(@as(usize, 32), hash2.len);
try testing.expectEqual(@as(usize, 32), hash3.len);
}
test "hash equality comparison" {
const hash1 = try HashUtils.sha256("same data");
const hash2 = try HashUtils.sha256("same data");
const hash3 = try HashUtils.sha256("different data");
// Same data should produce equal hashes
try testing.expect(HashUtils.equal(hash1, hash2));
// Different data should produce different hashes
try testing.expect(!HashUtils.equal(hash1, hash3));
}
test "batch verification with empty pieces" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create empty pieces array
var empty_pieces = std.ArrayList(PieceData).init(allocator);
// This should handle empty array gracefully
const piece_hashes = try allocator.alloc([32]u8, 0);
const metadata = try FileMetadata.create("empty_test.bin", 0, piece_hashes, allocator);
defer allocator.free(piece_hashes);
var batch = try pool.verifyPieces(metadata, empty_pieces.items);
defer batch.deinit();
try testing.expect(batch.isCompleteSuccess());
try testing.expectEqual(@as(f32, 1.0), batch.successRate());
try testing.expectEqual(@as(u32, 0), batch.valid_pieces);
empty_pieces.deinit();
}
test "incremental verifier basic operations" {
const allocator = testing.allocator;
const test_data = "Test data for incremental verification";
const expected_hash = try HashUtils.sha256(test_data);
var verifier = HashModule.IncrementalVerifier.init(expected_hash, 0, test_data.len, allocator);
defer _ = verifier; // verifier is used for checking completion
// Initially no progress
try testing.expectEqual(@as(f32, 0.0), verifier.getProgress());
try testing.expect(!verifier.isComplete());
// Update with data
try verifier.update(test_data);
try testing.expectEqual(@as(f32, 1.0), verifier.getProgress());
try testing.expect(verifier.isComplete());
// Finalize verification
const result = try verifier.finalize();
try testing.expect(result.is_valid);
try testing.expectEqual(@as(u32, 0), result.piece_index.?);
}
test "incremental verifier with partial updates" {
const allocator = testing.allocator;
const full_data = "This is a longer piece of data that will be split into chunks";
const expected_hash = try HashUtils.sha256(full_data);
var verifier = HashModule.IncrementalVerifier.init(expected_hash, 5, full_data.len, allocator);
// Update in chunks
const chunk_size = 10;
var offset: usize = 0;
while (offset < full_data.len) {
const end = @min(offset + chunk_size, full_data.len);
const chunk = full_data[offset..end];
try verifier.update(chunk);
const progress = verifier.getProgress();
const expected_progress = @as(f32, @floatFromInt(end)) / @as(f32, @floatFromInt(full_data.len));
try testing.expect(@abs(progress - expected_progress) < 0.01);
offset = end;
}
try testing.expect(verifier.isComplete());
// Finalize verification
const result = try verifier.finalize();
try testing.expect(result.is_valid);
try testing.expectEqual(@as(u32, 5), result.piece_index.?);
}
test "incremental verifier with wrong data" {
const allocator = testing.allocator;
const correct_data = "Correct data for verification";
const wrong_data = "Wrong data for verification";
const correct_hash = try HashUtils.sha256(correct_data);
var verifier = HashModule.IncrementalVerifier.init(correct_hash, 1, wrong_data.len, allocator);
// Update with wrong data
try verifier.update(wrong_data);
try testing.expect(verifier.isComplete());
// Finalize verification should fail
const result = try verifier.finalize();
try testing.expect(!result.is_valid);
try testing.expectEqual(@as(u32, 1), result.piece_index.?);
}
test "verification batch performance metrics" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create metadata with multiple pieces
const piece_hashes = try allocator.alloc([32]u8, 10);
for (piece_hashes, 0..) |*hash, i| {
const data = fmt.allocPrint(allocator, "piece {d} data", .{i}) catch return;
hash.* = try HashUtils.sha256(data);
allocator.free(data);
}
const metadata = try FileMetadata.create("performance_test.bin", 100, piece_hashes, allocator);
defer allocator.free(piece_hashes);
// Create valid pieces
var pieces = std.ArrayList(PieceData).init(allocator);
for (piece_hashes, 0..) |hash, i| {
const data = fmt.allocPrint(allocator, "piece {d} data", .{i}) catch return;
try pieces.append(PieceData{ .index = @as(u32, @intCast(i)), .data = data, .hash = hash });
}
// Verify pieces and measure performance
var batch = try pool.verifyPieces(metadata, pieces.items);
defer batch.deinit();
// Check performance metrics
const metrics = batch.getPerformanceMetrics();
try testing.expectEqual(@as(usize, 10), metrics.total_pieces);
try testing.expectEqual(@as(u32, 10), metrics.valid_pieces);
try testing.expect(metrics.verification_time_ms >= 0);
try testing.expect(metrics.throughput_pieces_per_second > 0.0);
try testing.expectEqual(@as(f32, 1.0), metrics.success_rate);
// Performance should be acceptable
try testing.expect(metrics.isPerformanceAcceptable(1.0)); // At least 1 piece per second
// Cleanup
for (pieces.items) |piece| {
allocator.free(piece.data);
}
pieces.deinit();
}
test "verification batch failed verification metrics" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create metadata
const piece_hashes = try allocator.alloc([32]u8, 3);
piece_hashes[0] = try HashUtils.sha256("piece 0 data");
piece_hashes[1] = try HashUtils.sha256("piece 1 data");
piece_hashes[2] = try HashUtils.sha256("piece 2 data");
const metadata = try FileMetadata.create("partial_fail_test.bin", 60, piece_hashes, allocator);
defer allocator.free(piece_hashes);
// Create pieces with one failure
var pieces = std.ArrayList(PieceData).init(allocator);
try pieces.append(PieceData{ .index = 0, .data = "piece 0 data", .hash = piece_hashes[0] });
try pieces.append(PieceData{ .index = 1, .data = "wrong piece 1 data", .hash = piece_hashes[1] }); // Wrong
try pieces.append(PieceData{ .index = 2, .data = "piece 2 data", .hash = piece_hashes[2] });
// Verify pieces
var batch = try pool.verifyPieces(metadata, pieces.items);
defer batch.deinit();
// Check metrics for partial failure
const metrics = batch.getPerformanceMetrics();
try testing.expectEqual(@as(usize, 3), metrics.total_pieces);
try testing.expectEqual(@as(u32, 2), metrics.valid_pieces);
try testing.expectEqual(@as(f32, 2.0/3.0), metrics.success_rate);
// Performance should still be acceptable
try testing.expect(metrics.isPerformanceAcceptable(0.5)); // Lower threshold for partial failures
// Get failed pieces
const failed_pieces = batch.getFailedPieces();
defer allocator.free(failed_pieces);
try testing.expectEqual(@as(usize, 1), failed_pieces.len);
try testing.expectEqual(@as(u32, 1), failed_pieces[0]);
pieces.deinit();
}
test "hash pool content address generation" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create metadata
const piece_hashes = try allocator.alloc([32]u8, 4);
for (piece_hashes) |*hash| {
hash.* = try HashUtils.random(allocator);
}
const metadata = try FileMetadata.create("address_gen_test.bin", 4096, piece_hashes, allocator);
defer allocator.free(piece_hashes);
// Generate content address
const content_address1 = try pool.generateContentAddress(metadata);
try testing.expectEqual(@as(usize, 32), content_address1.len);
// Same metadata should generate same address
const content_address2 = try pool.generateContentAddress(metadata);
try testing.expect(mem.eql(u8, &content_address1, &content_address2));
// Different metadata should generate different address
const different_hashes = try allocator.alloc([32]u8, 4);
for (different_hashes) |*hash| {
hash.* = try HashUtils.random(allocator);
}
const different_metadata = try FileMetadata.create("different_test.bin", 4096, different_hashes, allocator);
defer allocator.free(different_hashes);
const different_address = try pool.generateContentAddress(different_metadata);
try testing.expect(!mem.eql(u8, &content_address1, &different_address));
}