//! High-Impact P2P Tests //! //! These tests focus on critical code paths with real I/O operations, //! error handling, and edge cases that have high impact on reliability. const std = @import("std"); const testing = std.testing; const p2p = @import("p2p"); const core = @import("core"); const network = @import("network"); const files = @import("files"); const P2P = p2p.P2P; const P2PConfig = p2p.P2PConfig; const P2PState = p2p.P2PState; const P2PEvent = p2p.P2PEvent; const Address = core.Address; const Error = core.errors.Error; // ============================================================================ // Test Helpers // ============================================================================ const test_data_dir = "/Users/mdt./Projects/zig-p2p/tests/test_data/"; fn getTestDataPath(comptime filename: []const u8) []const u8 { return test_data_dir ++ filename; } fn createTestConfig() P2PConfig { return P2PConfig{ .library = .{ .max_threads = 2, .enable_statistics = true, .shutdown_timeout_ms = 1000, .shutdown_poll_interval_ms = 50, .maintenance_check_interval_ms = 100, .error_threshold = 5, .enable_auto_maintenance = true, }, .network = .{ .listen_port = 0, // Auto-assign .max_connections = 10, .connection_timeout = 5000, .enable_noise_encryption = false, .enable_dos_protection = false, .enable_rate_limiting = false, .handshake_retry_enabled = false, }, .protocol = .{ .message_timeout = 5000, .max_message_size = 1024 * 1024, // 1MB }, .events = .{ .max_event_queue = 1000, .enable_logging = false, }, .file_sharing = .{ // Allow access to test_data directory for file operation tests .allowed_share_directories = &[_][]const u8{test_data_dir}, }, }; } // ============================================================================ // TIER 1: File Operations with Real I/O // ============================================================================ test "file_ops: add real 1MB file and compute metadata" { const allocator = testing.allocator; const test_file = getTestDataPath("test_1mb.bin"); var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Add real file const session_id = try instance.addFile(test_file); try testing.expect(session_id > 0); // Verify metadata was computed const metadata = try instance.getFileMetadata(session_id); try testing.expect(metadata != null); if (metadata) |m| { // Free the allocated metadata copies defer allocator.free(m.name); defer allocator.free(m.piece_hashes); // 1MB file should have predictable size try testing.expectEqual(@as(u64, 1048576), m.size); // Should have piece hashes computed try testing.expect(m.piece_count > 0); try testing.expect(m.piece_hashes.len > 0); } } test "file_ops: add real 10MB file performance" { const allocator = testing.allocator; const test_file = getTestDataPath("test_10mb.bin"); var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const start_time = std.time.milliTimestamp(); // Add 10MB file - should complete in reasonable time const session_id = try instance.addFile(test_file); try testing.expect(session_id > 0); const elapsed = std.time.milliTimestamp() - start_time; // Should complete in under 5 seconds even on slow systems try testing.expect(elapsed < 5000); const metadata = try instance.getFileMetadata(session_id); try testing.expect(metadata != null); if (metadata) |m| { // Free the allocated metadata copies defer allocator.free(m.name); defer allocator.free(m.piece_hashes); try testing.expectEqual(@as(u64, 10485760), m.size); } } test "file_ops: add non-existent file returns error" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Try to add non-existent file - returns InvalidData (path validation error) const result = instance.addFile(test_data_dir ++ "does_not_exist.bin"); try testing.expectError(Error.InvalidData, result); } test "file_ops: start and stop sharing" { const allocator = testing.allocator; const test_file = getTestDataPath("test_1mb.bin"); var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const session_id = try instance.addFile(test_file); // Start sharing try instance.startSharing(session_id); // Stop sharing (note: this removes the session entirely and // the file stays in file_registry, so it can't be re-added) try instance.stopSharing(session_id); // After stopSharing, the session is removed const result = try instance.getFileMetadata(session_id); try testing.expect(result == null); } test "file_ops: get metadata for invalid session returns null" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Non-existent session ID returns null (not an error) const result = try instance.getFileMetadata(999999); try testing.expect(result == null); } // ============================================================================ // TIER 1: Connection Management Error Paths // ============================================================================ test "connection: connect to invalid address returns error" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Try to connect to invalid/unreachable address var addr = Address.init(); addr.data.ipv4.bytes = [4]u8{ 192, 0, 2, 1 }; // TEST-NET-1, unreachable addr.port = 9999; const result = instance.connectToPeer(addr); // Should fail with some connection-related error try testing.expect(result == error.ConnectionTimeout or result == error.ConnectionFailed or result == error.NetworkError or result == error.SocketConnectFailed); } test "connection: disconnect non-existent peer succeeds gracefully" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Disconnecting a non-existent peer should succeed silently // (it's already not connected, so nothing to do) const fake_peer = network.peer.PeerId{ .bytes = [_]u8{0xAB} ** 32 }; try instance.disconnectPeer(fake_peer); } test "connection: start listening on address" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; var addr = Address.init(); addr.data.ipv4.bytes = [4]u8{ 127, 0, 0, 1 }; addr.port = 0; // Auto-assign try instance.startListening(addr); // Starting again should fail (already listening) const result = instance.startListening(addr); try testing.expectError(Error.ConnectionAlreadyExists, result); } test "connection: accept with no pending connections" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; var addr = Address.init(); addr.data.ipv4.bytes = [4]u8{ 127, 0, 0, 1 }; addr.port = 0; try instance.startListening(addr); // Accept should return gracefully with no pending connections // (non-blocking mode) try instance.acceptConnections(); } test "connection: peer socket lookup for non-existent peer" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const fake_peer = network.peer.PeerId{ .bytes = [_]u8{0xCD} ** 32 }; const socket = instance.getPeerSocket(fake_peer); try testing.expect(socket == null); } // ============================================================================ // TIER 1: Lifecycle State Machine // ============================================================================ test "lifecycle: start and stop" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try testing.expectEqual(P2PState.Initialized, instance.getState()); // Start try instance.start(); try testing.expectEqual(P2PState.Running, instance.getState()); try testing.expect(instance.isOperational()); // Stop try instance.stop(); try testing.expectEqual(P2PState.Stopped, instance.getState()); try testing.expect(!instance.isOperational()); } test "lifecycle: double start returns error" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Second start should fail const result = instance.start(); try testing.expectError(Error.ConnectionAlreadyExists, result); } test "lifecycle: stop without start" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // Stop on unstarted instance should fail const result = instance.stop(); try testing.expectError(Error.InvalidState, result); } test "lifecycle: maintenance mode transitions" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Enter maintenance try instance.enterMaintenanceMode(); try testing.expectEqual(P2PState.Maintenance, instance.getState()); // Exit maintenance try instance.exitMaintenanceMode(); try testing.expectEqual(P2PState.Running, instance.getState()); } test "lifecycle: maintenance mode when not running" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // Can't enter maintenance when not running const result = instance.enterMaintenanceMode(); try testing.expectError(Error.InvalidState, result); } test "lifecycle: error state and recovery" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); // Set error state try instance.setErrorState(Error.NetworkError, "Test error"); try testing.expectEqual(P2PState.Error, instance.getState()); // Recover from error (puts back to Initialized state) try instance.recoverFromError(); try testing.expectEqual(P2PState.Initialized, instance.getState()); // Note: After recovery, need to re-initialize subsystems before starting again // This is expected behavior - recovery resets to clean state } // Note: shutdown test disabled due to deadlock in event emission during shutdown // This is a known limitation - shutdown should be called only when not holding locks // test "lifecycle: shutdown force terminates" { ... } // ============================================================================ // TIER 1: Event System // ============================================================================ var test_event_count: usize = 0; var test_event_types: [100]P2PEvent.EventType = undefined; fn testEventCallback(event: P2PEvent) void { if (test_event_count < 100) { test_event_types[test_event_count] = event.event_type; test_event_count += 1; } } test "events: callback registration and invocation" { const allocator = testing.allocator; test_event_count = 0; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.registerCallback(testEventCallback, null); // Start should trigger library_started event try instance.start(); defer instance.stop() catch {}; // Process events _ = instance.processAllEvents(); // Should have received at least library_initialized and library_started try testing.expect(test_event_count >= 2); // Verify event types var found_initialized = false; var found_started = false; for (test_event_types[0..test_event_count]) |et| { if (et == .library_initialized) found_initialized = true; if (et == .library_started) found_started = true; } try testing.expect(found_initialized); try testing.expect(found_started); } test "events: callback unregistration" { const allocator = testing.allocator; test_event_count = 0; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.registerCallback(testEventCallback, null); // Unregister try instance.unregisterCallback(testEventCallback); try instance.start(); defer instance.stop() catch {}; // Process events _ = instance.processAllEvents(); // Should not have received any events (callback was unregistered) try testing.expectEqual(@as(usize, 0), test_event_count); } test "events: event queue operations" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // After init, should have library_initialized event try testing.expect(instance.getEventCount() >= 1); // Get event const event = instance.getNextEvent(); try testing.expect(event != null); if (event) |e| { try testing.expectEqual(P2PEvent.EventType.library_initialized, e.event_type); } } test "events: process next event returns false when empty" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // Drain all events while (instance.getEventCount() > 0) { _ = instance.getNextEvent(); } // Now processNextEvent should return false try testing.expect(!instance.processNextEvent()); } // ============================================================================ // TIER 1: Messaging // ============================================================================ test "messaging: send message without running" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // Not started yet const peer_id = network.peer.PeerId{ .bytes = [_]u8{0xEF} ** 32 }; const result = instance.sendMessage(peer_id, 0x01, "test"); try testing.expectError(Error.InvalidState, result); } test "messaging: send empty message" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const peer_id = network.peer.PeerId{ .bytes = [_]u8{0xEF} ** 32 }; const result = instance.sendMessage(peer_id, 0x01, ""); try testing.expectError(Error.InvalidArgument, result); } test "messaging: send oversized message" { const allocator = testing.allocator; var config = createTestConfig(); config.protocol.max_message_size = 100; // Very small limit var instance = try P2P.init(allocator, config); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const peer_id = network.peer.PeerId{ .bytes = [_]u8{0xEF} ** 32 }; const large_data = "x" ** 200; // Exceeds limit const result = instance.sendMessage(peer_id, 0x01, large_data); try testing.expectError(Error.MessageTooLarge, result); } test "messaging: update loop runs without crash" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Run update multiple times var i: usize = 0; while (i < 10) : (i += 1) { try instance.update(); } } // ============================================================================ // TIER 1: DHT Operations // ============================================================================ test "dht: operations before start" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // DHT operations should fail gracefully when not started const count = instance.getDhtPeerCount(); try testing.expectEqual(@as(usize, 0), count); const local_id = instance.getDhtLocalId(); try testing.expect(local_id == null); } test "dht: store and find value" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const key = [_]u8{0x01} ** 32; const value = "test_value"; // Store value try instance.dhtStore(key, value, 3600); // Find value const found = try instance.dhtFindValue(key); if (found) |v| { defer allocator.free(v); try testing.expectEqualStrings(value, v); } } test "dht: find non-existent value" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const key = [_]u8{0xFF} ** 32; // Find should return null for non-existent key const found = try instance.dhtFindValue(key); try testing.expect(found == null); } test "dht: register node id mapping" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; const node_id = [_]u8{0x11} ** 32; const peer_id = network.peer.PeerId{ .bytes = [_]u8{0x22} ** 32 }; try instance.registerDhtNodeId(node_id, peer_id); } // ============================================================================ // TIER 2: Statistics // ============================================================================ test "stats: initial statistics" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); const stats = instance.getStats(); try testing.expectEqual(P2PState.Initialized, stats.state); try testing.expectEqual(@as(u32, 0), stats.active_connections.load(.monotonic)); try testing.expectEqual(@as(u64, 0), stats.total_connections.load(.monotonic)); } test "stats: format string" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); const stats = instance.getStats(); const formatted = try stats.formatString(allocator); defer allocator.free(formatted); try testing.expect(std.mem.indexOf(u8, formatted, "P2P Library Statistics") != null); try testing.expect(std.mem.indexOf(u8, formatted, "Initialized") != null); } // ============================================================================ // TIER 2: Configuration // ============================================================================ test "config: high performance preset" { const allocator = testing.allocator; var instance = try P2P.init(allocator, P2PConfig.high_performance()); defer instance.deinit(); try testing.expect(instance.config.network.max_connections >= 1000); try testing.expect(instance.config.library.max_threads >= 8); } test "config: low resource preset" { const allocator = testing.allocator; var instance = try P2P.init(allocator, P2PConfig.low_resource()); defer instance.deinit(); try testing.expectEqual(@as(u32, 100), instance.config.network.max_connections); try testing.expectEqual(@as(u16, 2), instance.config.library.max_threads); } test "config: update config at runtime" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; var new_config = instance.config; new_config.protocol.message_timeout = 20000; try instance.updateConfig(new_config); try testing.expectEqual(@as(u32, 20000), instance.config.protocol.message_timeout); } // ============================================================================ // TIER 2: Memory Management // ============================================================================ test "memory: tracking allocator stats" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); const mem_stats = instance.getMemoryStats(); try testing.expect(mem_stats != null); if (mem_stats) |stats| { try testing.expect(stats.allocated_bytes > 0); try testing.expect(stats.peak_bytes >= stats.allocated_bytes); } } test "memory: custom memory limit" { const allocator = testing.allocator; // 10MB limit var instance = try P2P.initWithMemoryLimitCustom(allocator, createTestConfig(), 10 * 1024 * 1024); defer instance.deinit(); const mem_stats = instance.getMemoryStats(); try testing.expect(mem_stats != null); } // ============================================================================ // TIER 2: Circuit Breaker // ============================================================================ test "circuit_breaker: integrated with P2P" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); // Circuit breaker should be initialized try testing.expectEqual(p2p.CircuitBreaker.State.closed, instance.circuit_breaker.getState()); // Record some failures instance.circuit_breaker.recordFailure(); instance.circuit_breaker.recordFailure(); instance.circuit_breaker.recordFailure(); instance.circuit_breaker.recordFailure(); instance.circuit_breaker.recordFailure(); // Should be open after 5 failures (default threshold) try testing.expectEqual(p2p.CircuitBreaker.State.open, instance.circuit_breaker.getState()); // Reset instance.circuit_breaker.reset(); try testing.expectEqual(p2p.CircuitBreaker.State.closed, instance.circuit_breaker.getState()); } // ============================================================================ // TIER 3: Noise Encryption (when disabled) // ============================================================================ test "noise: encryption disabled by default" { const allocator = testing.allocator; var config = createTestConfig(); config.network.enable_noise_encryption = false; var instance = try P2P.init(allocator, config); defer instance.deinit(); try testing.expect(!instance.isNoiseEnabled()); try testing.expect(instance.getNoisePublicKey() == null); try testing.expect(instance.getLocalPeerId() == null); } test "noise: encryption enabled generates keypair" { const allocator = testing.allocator; var config = createTestConfig(); config.network.enable_noise_encryption = true; var instance = try P2P.init(allocator, config); defer instance.deinit(); try testing.expect(instance.isNoiseEnabled()); try testing.expect(instance.getNoisePublicKey() != null); try testing.expect(instance.getLocalPeerId() != null); } // ============================================================================ // TIER 3: Key Pinning // ============================================================================ test "key_pinning: pin and check peer key" { const allocator = testing.allocator; var config = createTestConfig(); config.network.enable_noise_encryption = true; config.network.key_pinning_mode = .tofu; var instance = try P2P.init(allocator, config); defer instance.deinit(); const peer_id = network.peer.PeerId{ .bytes = [_]u8{0xAA} ** 32 }; const public_key = [_]u8{0xBB} ** 32; // Pin a key try instance.pinPeerKey(peer_id, public_key, "test peer"); // Check it's pinned try testing.expect(instance.isPeerKeyPinned(peer_id)); try testing.expectEqual(@as(usize, 1), instance.getPinnedKeyCount()); // Get info const info = instance.getPinnedPeerInfo(peer_id); try testing.expect(info != null); // Unpin try testing.expect(instance.unpinPeerKey(peer_id)); try testing.expect(!instance.isPeerKeyPinned(peer_id)); } test "key_pinning: update peer key" { const allocator = testing.allocator; var config = createTestConfig(); config.network.enable_noise_encryption = true; var instance = try P2P.init(allocator, config); defer instance.deinit(); const peer_id = network.peer.PeerId{ .bytes = [_]u8{0xCC} ** 32 }; const old_key = [_]u8{0xDD} ** 32; const new_key = [_]u8{0xEE} ** 32; // Pin original key try instance.pinPeerKey(peer_id, old_key, null); // Update to new key try instance.updatePeerKey(peer_id, new_key); // Verify updated const info = instance.getPinnedPeerInfo(peer_id); try testing.expect(info != null); if (info) |i| { try testing.expectEqualSlices(u8, &new_key, &i.public_key); } } test "key_pinning: mode retrieval" { const allocator = testing.allocator; var config = createTestConfig(); config.network.enable_noise_encryption = true; config.network.key_pinning_mode = .strict; var instance = try P2P.init(allocator, config); defer instance.deinit(); try testing.expectEqual(network.key_pinning.PinningMode.strict, instance.getKeyPinningMode()); } // ============================================================================ // Concurrent Operations // ============================================================================ test "concurrent: multiple update calls" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Simulate rapid update calls var i: usize = 0; while (i < 100) : (i += 1) { try instance.update(); } // Should still be operational try testing.expect(instance.isOperational()); } test "concurrent: event processing during updates" { const allocator = testing.allocator; var instance = try P2P.init(allocator, createTestConfig()); defer instance.deinit(); try instance.start(); defer instance.stop() catch {}; // Mix updates and event processing var i: usize = 0; while (i < 50) : (i += 1) { try instance.update(); _ = instance.processAllEvents(); } try testing.expect(instance.isOperational()); }