threshold from 1ms to 10ms, demote ADAPTIVE in_flight log to debug, switch 3 tests from full init to initForTesting eliminating thread pool overhead under kcov
File Sharing Module
A comprehensive BitTorrent-inspired file sharing system implemented in Zig for the P2P library.
Overview
This module provides a complete file sharing and transfer system with the following features:
- File chunking and metadata management
- Piece selection algorithms (rarest-first, random, sequential, priority-based)
- Download management with progress tracking and rate limiting
- Upload management with bandwidth control and peer coordination
- Transfer protocol for peer-to-peer communication
- Hash-based integrity verification using SHA-256
- Comprehensive testing suite
Architecture
Core Components
-
Hash Module (
hash.zig)- SHA-256 hashing for piece verification
- Content addressing and metadata hashing
- Batch verification operations
- Hash pool for efficient computation
-
File Module (
file.zig)- File metadata creation and management
- File chunking into pieces (fixed and variable size)
- File reading/writing operations with streaming support
- Integrity verification with SHA-256
- File type detection and classification
- Compression/decompression utilities
- File backup and copy operations
- Progress tracking for file operations
-
Piece Selection Module (
piece.zig)- Multiple selection strategies
- Piece availability tracking
- Priority-based selection
- Piece pool management
-
Download Module (
download.zig)- Download state tracking
- Piece request management
- Progress monitoring
- Download queue coordination
-
Upload Module (
upload.zig)- Upload state management
- Bandwidth limiting and rate control
- Peer upload coordination
- Upload queue management
-
Transfer Module (
transfer.zig)- Protocol message handling
- Session management
- Peer communication
- Error handling and recovery
-
Manager Module (
manager.zig)- Central coordination
- Session lifecycle management
- Configuration and statistics
- Integration point for the entire system
Key Features
Piece Selection Strategies
- Rarest First: Prioritizes pieces that are less available
- Random: Random piece selection
- Sequential: Sequential piece selection
- Priority First: Priority-based selection
- Balanced: Combination of rarity and priority
Download Management
- Concurrent download tracking
- Progress monitoring with speed calculation
- Time remaining estimation
- Bandwidth utilization tracking
- Piece verification during download
Upload Management
- Bandwidth limiting and throttling
- Peer upload coordination
- Upload queue management
- Rate limiting per peer
- Bandwidth utilization monitoring
File Integrity
- SHA-256 hash verification for each piece
- Content-based addressing
- Batch verification operations
- Corruption detection and recovery
Transfer Protocol
- Message-based communication
- Session management
- Error handling and recovery
- Timeout management
- Peer capability exchange
Usage Examples
Basic File Operations
const allocator = std.heap.page_allocator;
// File metadata creation
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
const metadata = try chunker.createMetadata("path/to/file.bin");
defer allocator.free(metadata.piece_hashes);
// File integrity verification
const is_valid = try chunker.verifyFile("path/to/file.bin", metadata);
// Streaming file reader
var reader = try FileReader.init("large_file.bin", allocator, 64 * 1024);
defer reader.deinit();
try reader.readInChunks(fn(data: []const u8) Error!void {
// Process chunk data
std.debug.print("Read {} bytes\n", .{data.len});
});
// File operations with progress
try FileUtils.copyFileWithProgress(
"source.bin",
"dest.bin",
allocator,
fn(current: u64, total: u64) void {
const percentage = @as(f64, @floatFromInt(current)) / @as(f64, @floatFromInt(total)) * 100.0;
std.debug.print("Progress: {d:.1}%\n", .{percentage});
}
);
// File type detection and compression
const file_type = FileUtils.getFileType("document.txt");
const compression_ratio = FileUtils.estimateCompressionRatio("document.txt");
std.debug.print("File type: {s}, estimated ratio: {d:.2}\n", .{
file_type.description(),
compression_ratio
});
Basic File Sharing
const allocator = std.heap.page_allocator;
const config = FileSharingConfig.default();
var manager = try FileSharingManager.init(config, allocator);
defer manager.deinit();
// Add file for sharing
const session = try manager.addFile("path/to/file.bin");
try manager.startSharing(session.session_id);
// Process sessions
try manager.processSessions();
// Monitor progress
const stats = manager.getStats();
std.debug.print("Progress: {d:.1}%\n", .{stats.getCompletionRate()});
Download Management
// Configure download settings
const download_config = DownloadConfig{
.max_concurrent_downloads = 4,
.piece_size = 16 * 1024 * 1024, // 16MB
};
// Create download manager
var download_manager = try DownloadManager.init(
file_size,
piece_count,
.rarest_first,
piece_size,
allocator
);
// Set output file
try download_manager.setOutputFile("output.bin");
// Add peer and request pieces
try download_manager.addPeer("peer_id", &available_pieces);
try download_manager.requestPiece(0, .high, "peer_id");
// Process downloads
try download_manager.processRequests(4);
Upload Management
// Configure upload settings
var upload_manager = try UploadManager.init(
1024 * 1024, // 1MB/s max bandwidth
piece_size,
allocator
);
// Add available pieces
for (piece_hashes) |hash, i| {
try upload_manager.addAvailablePiece(@as(u32, @intCast(i)), hash);
}
// Handle upload requests
const accepted = try upload_manager.handleUploadRequest(
piece_index,
offset,
length,
"peer_id",
.normal
);
// Process uploads
try upload_manager.processRequests(4);
Piece Selection
// Create piece selector
var selector = PieceSelector.init(.rarest_first, seed, allocator);
defer selector.deinit();
// Add pieces with availability
for (available_pieces) |piece_index| {
try selector.addPiece(piece_index, peer_count);
}
// Select next pieces to download
const selected = try selector.selectNext(5);
defer allocator.free(selected);
// Update piece status
try selector.markDownloaded(selected[0]);
try selector.markVerified(selected[0]);
Configuration
File Sharing Config
const config = FileSharingConfig{
.piece_size = 16 * 1024 * 1024, // 16MB pieces
.max_concurrent_downloads = 4, // 4 concurrent downloads
.max_concurrent_uploads = 4, // 4 concurrent uploads
.max_bandwidth_download = 1024 * 1024, // 1MB/s download
.max_bandwidth_upload = 1024 * 1024, // 1MB/s upload
.selection_strategy = .rarest_first, // Selection algorithm
.enable_upload = true, // Enable uploading
.enable_download = true, // Enable downloading
.auto_verify = true, // Auto-verify pieces
.temp_dir = "temp", // Temporary directory
};
Performance Configurations
// High performance configuration
const hp_config = FileSharingConfig.high_performance();
// - 8 concurrent operations
// - 10MB/s bandwidth
// - 32MB pieces
// - Balanced selection
// Low bandwidth configuration
const lb_config = FileSharingConfig.low_bandwidth();
// - 2 concurrent operations
// - 256KB/s bandwidth
// - 8MB pieces
// - Sequential selection
Testing
The module includes comprehensive tests:
- Unit tests for each component
- Integration tests for end-to-end functionality
- Performance tests for large file handling
- Stress tests for multiple file operations
- Error recovery tests for corrupted data
- Concurrent access tests for multi-peer scenarios
Run tests with:
zig test test/files/test_main.zig
Performance Characteristics
- Piece Selection: O(n log n) for sorting-based strategies
- Hash Verification: O(n) for batch operations
- File Chunking: O(n) where n is file size
- Memory Usage: Configurable based on piece size and concurrency
- Bandwidth Efficiency: Adaptive rate limiting
Error Handling
The module includes comprehensive error handling:
- Network errors: Connection timeouts, peer disconnections
- File errors: Read/write failures, disk space issues
- Protocol errors: Message format errors, version mismatches
- Integrity errors: Hash mismatches, corrupted pieces
- Resource errors: Memory exhaustion, bandwidth limits
Future Enhancements
Potential improvements for future versions:
- Encryption: End-to-end encryption for transfers
- Compression: On-the-fly data compression
- Streaming: Support for streaming large files
- DHT: Distributed hash table integration
- Magnet Links: Magnet link support
- WebRTC: WebRTC transport for browser compatibility
Dependencies
- Zig standard library
- No external dependencies for core functionality
- Optional dependencies for enhanced features (compression, encryption)
License
This module is part of the P2P library and follows the same licensing terms.