//! Multi-peer coordination and file sharing integration tests //! //! This module tests complex scenarios involving multiple peers, network topology, //! peer discovery, coordination mechanisms, and distributed file sharing. const std = @import("std"); const testing = std.testing; const fs = std.fs; const mem = std.mem; const ArrayList = std.ArrayList; const AutoHashMap = std.AutoHashMap; // Import P2P library components const P2P = @import("../../src/p2p.zig").P2P; const P2PConfig = @import("../../src/p2p.zig").P2PConfig; const P2PEvent = @import("../../src/p2p.zig").P2PEvent; const Address = @import("../../src/core/address.zig").Address; const PeerId = @import("../../src/network/peer.zig").PeerId; const Node = @import("../../src/network/node.zig").Node; const NodeConfig = @import("../../src/network/node.zig").NodeConfig; const NetworkTopology = @import("../../src/network/topology.zig").NetworkTopology; const TopologyRole = @import("../../src/network/topology.zig").TopologyRole; const FileMetadata = @import("../../src/files/hash.zig").FileMetadata; const FileUtils = @import("../../src/files/hash.zig").FileUtils; const { FileSharingManager, FileSharingConfig } = @import("../../src/files/manager.zig"); const { DownloadManager } = @import("../../src/files/download.zig"); const Error = @import("../../src/core/error.zig").Error; /// Multi-peer test scenarios and coordination mechanisms pub const MultiPeerTests = struct { allocator: mem.Allocator, pub fn init(allocator: mem.Allocator) MultiPeerTests { return MultiPeerTests{ .allocator = allocator }; } pub fn deinit(self: *MultiPeerTests) void { _ = self; } /// Test peer discovery and connection establishment pub fn testPeerDiscoveryAndConnection(self: *MultiPeerTests) !void { std.debug.print("\n=== Testing Peer Discovery and Connection ===\n", .{}); const peer_count = 5; var peers = ArrayList(P2P).init(self.allocator); defer { for (peers.items) |*p2p| { p2p.deinit(); } peers.deinit(); } // Initialize multiple peers for (0..peer_count) |i| { var config = P2PConfig.default(); config.network.listen_port = @as(u16, 8000 + i); // Different ports var p2p = try P2P.init(self.allocator, config); try peers.append(p2p); } // Start all peers for (peers.items) |*p2p| { try p2p.start(); try std.testing.expect(p2p.isOperational()); } // Test peer connections for (0..peer_count) |i| { for (i + 1..peer_count) |j| { var address = Address.init(); address.port = @as(u16, 8000 + j); const peer_id = try peers.items[i].connectToPeer(address); try std.testing.expect(peer_id.bytes.len == 32); // Process events _ = peers.items[i].processAllEvents(); _ = peers.items[j].processAllEvents(); } } // Verify all peers have connections for (peers.items) |p2p| { const stats = p2p.getStats(); try std.testing.expect(stats.active_connections >= 0); } // Clean shutdown for (peers.items) |*p2p| { try p2p.stop(); } std.debug.print("✓ Peer discovery and connection test passed\n", .{}); } /// Test distributed file sharing across multiple peers pub fn testDistributedFileSharing(self: *MultiPeerTests) !void { std.debug.print("\n=== Testing Distributed File Sharing ===\n", .{}); const peer_count = 4; const file_count = 3; // Create test files var file_paths = ArrayList([]const u8).init(self.allocator); defer { for (file_paths.items) |path| { self.allocator.free(path); } file_paths.deinit(); } for (0..file_count) |i| { const file_path = try std.fmt.allocPrint(self.allocator, "distributed_file_{d}.bin", .{i}); try file_paths.append(file_path); const content = try std.fmt.allocPrint(self.allocator, "Distributed file {d} content for testing", .{i}); defer self.allocator.free(content); try self.createTestFile(file_path, content); defer fs.cwd().deleteFile(file_path) catch {}; } var peers = ArrayList(P2P).init(self.allocator); defer { for (peers.items) |*p2p| { p2p.deinit(); } peers.deinit(); } // Initialize peers for (0..peer_count) |i| { var p2p = try P2P.init(self.allocator, P2PConfig.default()); try peers.append(p2p); } // Start all peers for (peers.items) |*p2p| { try p2p.start(); } // Distribute files across peers (peer 0 has all files, others have some) var session_ids = AutoHashMap(usize, u64).init(self.allocator); defer session_ids.deinit(); // Peer 0 shares all files for (0..file_count) |i| { const session_id = try peers.items[0].addFile(file_paths.items[i]); try peers.items[0].startSharing(session_id); try session_ids.put(i, session_id); } // Other peers share some files for (1..peer_count) |peer_idx| { const file_idx = peer_idx - 1; if (file_idx < file_count) { const session_id = try peers.items[peer_idx].addFile(file_paths.items[file_idx]); try peers.items[peer_idx].startSharing(session_id); } } // Process all events for (peers.items) |*p2p| { _ = p2p.processAllEvents(); } // Test peer-to-peer file discovery and download for (0..file_count) |file_idx| { for (1..peer_count) |peer_idx| { // Simulate downloading file from peer 0 const chunker = try self.getFileChunker(); defer chunker.deinit(); const metadata = try chunker.createMetadata(file_paths.items[file_idx]); defer self.allocator.free(metadata.piece_hashes); const download_session_id = try peers.items[peer_idx].downloadFile(metadata, try std.fmt.allocPrint(self.allocator, "peer_{d}_file_{d}.bin", .{peer_idx, file_idx})); self.allocator.free(file_paths.items[file_idx]); // Free the string from allocPrint try peers.items[peer_idx].startSharing(download_session_id); } } // Verify distributed sharing var total_active_sessions: usize = 0; for (peers.items) |p2p| { const stats = p2p.getStats(); total_active_sessions += stats.active_downloads + stats.active_uploads; } try std.testing.expect(total_active_sessions > 0); // Clean shutdown for (peers.items) |*p2p| { try p2p.stop(); } std.debug.print("✓ Distributed file sharing test passed\n", .{}); } /// Test network topology management with multiple peers pub fn testNetworkTopologyManagement(self: *MultiPeerTests) !void { std.debug.print("\n=== Testing Network Topology Management ===\n", .{}); const allocator = self.allocator; var topology = NetworkTopology.init(allocator, .Mesh); defer topology.deinit(); const peer_count = 6; var nodes = ArrayList(*Node).init(allocator); defer { for (nodes.items) |node| { node.deinit(); allocator.destroy(node); } nodes.deinit(); } // Create nodes with different roles const roles = .{ TopologyRole.Regular, TopologyRole.Super, TopologyRole.Hub, TopologyRole.Gateway }; for (0..peer_count) |i| { const peer_id = PeerId.init(); var address = Address.init(); address.port = @as(u16, 9000 + i); const role = roles[i % roles.len]; const node = try allocator.create(Node); node.* = Node.init(allocator, peer_id, address, &topology, NodeConfig{}); try topology.addNode(peer_id, role); try nodes.append(node); } // Start all nodes for (nodes.items) |node| { try node.start(); } // Establish connections between nodes for (0..peer_count) |i| { for (i + 1..peer_count) |j| { const source_peer_id = topology.getNodePeerId(i).?; const dest_peer_id = topology.getNodePeerId(j).?; try topology.addConnection(source_peer_id, dest_peer_id, 100); try topology.addConnection(dest_peer_id, source_peer_id, 100); // Update routing tables try nodes.items[i].addNeighbor(dest_peer_id); try nodes.items[j].addNeighbor(source_peer_id); } } // Test topology metrics const total_connections = topology.getTotalConnections(); try std.testing.expect(total_connections > 0); const diameter = topology.getDiameter(); try std.testing.expect(diameter >= 0); // Test shortest path finding const source_peer_id = topology.getNodePeerId(0).?; const dest_peer_id = topology.getNodePeerId(peer_count - 1).?; const path = topology.findShortestPath(source_peer_id, dest_peer_id); if (path) |p| { try std.testing.expect(p.len > 0); } // Test node removal const removed_peer_id = topology.getNodePeerId(1).?; try topology.removeNode(removed_peer_id); try std.testing.expect(topology.nodes.size() == peer_count - 1); // Clean shutdown for (nodes.items) |node| { node.stop(); } std.debug.print("✓ Network topology management test passed\n", .{}); } /// Test peer coordination with bandwidth management pub fn testPeerBandwidthCoordination(self: *MultiPeerTests) !void { std.debug.print("\n=== Testing Peer Bandwidth Coordination ===\n", .{}); const peer_count = 3; var peers = ArrayList(P2P).init(self.allocator); defer { for (peers.items) |*p2p| { p2p.deinit(); } peers.deinit(); } // Create peers with different bandwidth configurations const bandwidth_configs = .{ P2PConfig.high_performance(), // High bandwidth P2PConfig.default(), // Medium bandwidth P2PConfig.low_resource() // Low bandwidth }; for (0..peer_count) |i| { var config = bandwidth_configs[i % bandwidth_configs.len]; config.network.max_bandwidth = @as(u64, 1024 * 1024 * (i + 1)); // 1MB, 2MB, 3MB var p2p = try P2P.init(self.allocator, config); try peers.append(p2p); } // Start all peers for (peers.items) |*p2p| { try p2p.start(); } // Create shared files for (0..peer_count) |i| { const file_path = try std.fmt.allocPrint(self.allocator, "bandwidth_test_{d}.bin", .{i}); defer self.allocator.free(file_path); const content = try std.fmt.allocPrint(self.allocator, "Bandwidth test file {d}", .{i}); defer self.allocator.free(content); try self.createTestFile(file_path, content); defer fs.cwd().deleteFile(file_path) catch {}; const session_id = try peers.items[i].addFile(file_path); try peers.items[i].startSharing(session_id); } // Test bandwidth-aware peer connections for (0..peer_count) |i| { for (i + 1..peer_count) |j| { var address = Address.init(); address.port = @as(u16, 10000 + j); // Higher bandwidth peer initiates connection const initiator_idx = if (i < j) i else j; const peer_id = try peers.items[initiator_idx].connectToPeer(address); _ = peer_id; // Process events _ = peers.items[i].processAllEvents(); _ = peers.items[j].processAllEvents(); } } // Verify bandwidth coordination for (peers.items) |p2p| { const stats = p2p.getStats(); try std.testing.expect(stats.current_download_rate >= 0); try std.testing.expect(stats.current_upload_rate >= 0); // Check that bandwidth is being tracked const formatted_stats = try stats.formatString(self.allocator); defer self.allocator.free(formatted_stats); try std.testing.expect(mem.indexOf(u8, formatted_stats, "Bandwidth") != null); } // Clean shutdown for (peers.items) |*p2p| { try p2p.stop(); } std.debug.print("✓ Peer bandwidth coordination test passed\n", .{}); } /// Test peer failure and recovery scenarios pub fn testPeerFailureAndRecovery(self: *MultiPeerTests) !void { std.debug.print("\n=== Testing Peer Failure and Recovery ===\n", .{}); const peer_count = 4; var peers = ArrayList(P2P).init(self.allocator); defer { for (peers.items) |*p2p| { p2p.deinit(); } peers.deinit(); } // Initialize all peers for (peer_count) |_| { var p2p = try P2P.init(self.allocator, P2PConfig.default()); try peers.append(p2p); } // Start all peers for (peers.items) |*p2p| { try p2p.start(); } // Establish initial connections for (0..peer_count) |i| { for (i + 1..peer_count) |j| { var address = Address.init(); address.port = @as(u16, 11000 + j); _ = try peers.items[i].connectToPeer(address); } } // Process initial events for (peers.items) |*p2p| { _ = p2p.processAllEvents(); } // Simulate peer failure (stop one peer) const failed_peer_idx = 1; try peers.items[failed_peer_idx].stop(); // Verify peer is offline try std.testing.expect(!peers.items[failed_peer_idx].isOperational()); // Process failure events for (peers.items) |*p2p| { if (p2p != &peers.items[failed_peer_idx]) { _ = p2p.processAllEvents(); } } // Test recovery by restarting the failed peer try peers.items[failed_peer_idx].start(); // Verify recovery try std.testing.expect(peers.items[failed_peer_idx].isOperational()); // Test reconnection after recovery var address = Address.init(); address.port = @as(u16, 11000 + failed_peer_idx); _ = try peers.items[0].connectToPeer(address); // Process reconnection events for (peers.items) |*p2p| { _ = p2p.processAllEvents(); } // Verify network is restored for (peers.items) |p2p| { const stats = p2p.getStats(); try std.testing.expect(p2p.isOperational()); // Note: connection count may vary due to network changes } // Clean shutdown for (peers.items) |*p2p| { try p2p.stop(); } std.debug.print("✓ Peer failure and recovery test passed\n", .{}); } /// Helper: Create test file fn createTestFile(self: *MultiPeerTests, file_path: []const u8, content: []const u8) !void { const file = fs.cwd().createFile(file_path, .{}) catch return; defer file.close(); _ = try file.write(content); } /// Helper: Get file chunker fn getFileChunker(self: *MultiPeerTests) !FileUtils { return FileUtils.init(self.allocator); } }; // Individual test functions for Zig test runner test "peer discovery and connection establishment" { const allocator = testing.allocator; var tests = MultiPeerTests.init(allocator); defer tests.deinit(); try tests.testPeerDiscoveryAndConnection(); } test "distributed file sharing across multiple peers" { const allocator = testing.allocator; var tests = MultiPeerTests.init(allocator); defer tests.deinit(); try tests.testDistributedFileSharing(); } test "network topology management with multiple peers" { const allocator = testing.allocator; var tests = MultiPeerTests.init(allocator); defer tests.deinit(); try tests.testNetworkTopologyManagement(); } test "peer bandwidth coordination and management" { const allocator = testing.allocator; var tests = MultiPeerTests.init(allocator); defer tests.deinit(); try tests.testPeerBandwidthCoordination(); } test "peer failure and recovery scenarios" { const allocator = testing.allocator; var tests = MultiPeerTests.init(allocator); defer tests.deinit(); try tests.testPeerFailureAndRecovery(); } test "multi-peer message routing" { const allocator = testing.allocator; var topology = NetworkTopology.init(allocator, .Mesh); defer topology.deinit(); // Create test peer IDs var peer_ids = ArrayList(PeerId).init(allocator); defer peer_ids.deinit(); for (0..3) |_| { try peer_ids.append(PeerId.init()); } // Add nodes to topology for (peer_ids.items) |peer_id| { try topology.addNode(peer_id, .Regular); } // Add connections try topology.addConnection(peer_ids.items[0], peer_ids.items[1], 100); try topology.addConnection(peer_ids.items[1], peer_ids.items[2], 100); // Test message routing const source_id = peer_ids.items[0]; const dest_id = peer_ids.items[2]; const path = topology.findShortestPath(source_id, dest_id); try testing.expect(path != null); if (path) |p| { // Should find path through peer_ids.items[1] try testing.expect(p.len >= 2); } } test "multi-peer bandwidth fairness" { const allocator = testing.allocator; // Test different bandwidth configurations const configs = .{ P2PConfig.high_performance(), P2PConfig.default(), P2PConfig.low_resource(), }; try testing.expect(configs[0].network.max_bandwidth > configs[2].network.max_bandwidth); } test "peer coordination under load" { const allocator = testing.allocator; const peer_count = 10; var peers = ArrayList(P2P).init(allocator); defer { for (peers.items) |*p2p| { p2p.deinit(); } peers.deinit(); } // Initialize many peers for (0..peer_count) |_| { var p2p = try P2P.init(allocator, P2PConfig.default()); try peers.append(p2p); } // Start all peers for (peers.items) |*p2p| { try p2p.start(); } // Process events for all peers for (peers.items) |*p2p| { _ = p2p.processAllEvents(); const stats = p2p.getStats(); try testing.expect(stats.state == P2PState.Running); } // Clean shutdown for (peers.items) |*p2p| { try p2p.stop(); } } test "peer network partition handling" { const allocator = testing.allocator; const peer_count = 5; var peers = ArrayList(P2P).init(allocator); defer { for (peers.items) |*p2p| { p2p.deinit(); } peers.deinit(); } // Initialize peers for (0..peer_count) |_| { var p2p = try P2P.init(allocator, P2PConfig.default()); try peers.append(p2p); } // Start all peers for (peers.items) |*p2p| { try p2p.start(); } // Create initial network (fully connected) for (0..peer_count) |i| { for (i + 1..peer_count) |j| { var address = Address.init(); address.port = @as(u16, 12000 + j); _ = try peers.items[i].connectToPeer(address); } } // Simulate network partition (stop some peers) const partition_size = 2; for (0..partition_size) |i| { try peers.items[i].stop(); } // Remaining peers should still be operational for (partition_size..peer_count) |i| { try testing.expect(peers.items[i].isOperational()); } // Clean up for (peers.items) |*p2p| { try p2p.stop(); } } test "peer reconnection and state synchronization" { const allocator = testing.allocator; var p2p1 = try P2P.init(allocator, P2PConfig.default()); defer p2p1.deinit(); var p2p2 = try P2P.init(allocator, P2PConfig.default()); defer p2p2.deinit(); try p2p1.start(); try p2p2.start(); // Initial connection var address = Address.init(); address.port = 13000; const peer_id = try p2p1.connectToPeer(address); try testing.expect(peer_id.bytes.len == 32); // Process events _ = p2p1.processAllEvents(); _ = p2p2.processAllEvents(); // Disconnect try p2p2.stop(); try testing.expect(!p2p2.isOperational()); // Reconnect try p2p2.start(); const new_peer_id = try p2p1.connectToPeer(address); try testing.expect(new_peer_id.bytes.len == 32); // Process reconnection events _ = p2p1.processAllEvents(); _ = p2p2.processAllEvents(); try p2p1.stop(); try p2p2.stop(); }