//! Real P2P Bidirectional Communication Test //! //! Tests actual bidirectional message exchange between two P2P instances over TCP. //! Each peer receives a number, squares it, and sends it back for 50 rounds. //! Uses arbitrary precision integers to handle the exponentially growing numbers. const std = @import("std"); const p2p_lib = @import("p2p"); const core = @import("core"); const network = @import("network"); const P2P = p2p_lib.P2P; const P2PEvent = p2p_lib.P2PEvent; const Address = core.address.Address; const PeerId = network.PeerId; const BigInt = std.math.big.int.Managed; // Using 1.01 as base with fixed-point arithmetic // Scale doubles each round: Round 16 ~130KB, Round 17 ~260KB, Round 18 ~520KB // Network limits prevent messages larger than ~260KB with reasonable timeouts const ROUNDS = 17; const MSG_TYPE_NUMBER: u8 = 0x80; pub fn main() !void { const allocator = std.heap.page_allocator; std.debug.print("=== Real P2P Bidirectional Communication Test ===\n", .{}); std.debug.print(" Testing {d} rounds of number exchange (with big integers)\n\n", .{ROUNDS}); // Create two P2P instances with different ports // Use random ports in the 30000-39999 range to avoid conflicts const random_base = @mod(@as(u16, @truncate(@as(u64, @bitCast(std.time.milliTimestamp())))), 1000); const port1 = 30000 + random_base; const port2 = 30001 + random_base; const listen_port = 30002 + random_base; std.debug.print(" Using ports: P2P1={}, P2P2={}, Listen={}\n\n", .{ port1, port2, listen_port }); var config1 = p2p_lib.P2PConfig.default(); config1.network.listen_port = port1; config1.events.enable_logging = false; config1.protocol.max_message_size = 1024 * 1024; // 1MB for large numbers var config2 = p2p_lib.P2PConfig.default(); config2.network.listen_port = port2; config2.events.enable_logging = false; config2.protocol.max_message_size = 1024 * 1024; // 1MB for large numbers std.debug.print("1. Creating P2P instances...\n", .{}); var p2p1 = try P2P.init(allocator, config1); defer p2p1.deinit(); var p2p2 = try P2P.init(allocator, config2); defer p2p2.deinit(); std.debug.print(" Done.\n", .{}); // Start instances std.debug.print("2. Starting P2P instances...\n", .{}); try p2p1.start(); try p2p2.start(); std.debug.print(" Done.\n", .{}); // P2P1 listens on a port std.debug.print("3. P2P1 listening on port {d}...\n", .{listen_port}); const listen_addr = Address.ipv4(.{ 127, 0, 0, 1 }, listen_port); try p2p1.startListening(listen_addr); std.debug.print(" Done.\n", .{}); // Give server time to start listening std.Thread.sleep(100 * std.time.ns_per_ms); // P2P2 connects to P2P1 std.debug.print("4. P2P2 connecting to P2P1...\n", .{}); const peer_id_from_p2p2 = try p2p2.connectToPeer(listen_addr); std.debug.print(" Connected! Peer ID: {x}\n", .{peer_id_from_p2p2.bytes[0..8].*}); // Let P2P1 accept the connection std.debug.print("5. Processing connection...\n", .{}); try p2p1.update(); // Get the peer ID that P2P1 sees for P2P2 var peer_id_from_p2p1: ?PeerId = null; var iter = p2p1.peer_connections.iterator(); if (iter.next()) |entry| { peer_id_from_p2p1 = entry.key_ptr.*; } if (peer_id_from_p2p1 == null) { std.debug.print(" ERROR: No connection accepted!\n", .{}); return; } std.debug.print(" P2P1 sees peer: {x}\n", .{peer_id_from_p2p1.?.bytes[0..8].*}); std.debug.print(" Done.\n", .{}); // Start bidirectional test std.debug.print("\n6. Starting {d}-round bidirectional test...\n", .{ROUNDS}); std.debug.print(" Rule: Receive number N, send back N*N\n\n", .{}); var round: u32 = 0; var p2p2_is_sender = true; // P2P2 starts var successful_rounds: u32 = 0; // Message buffer - needs to be large for big numbers // Scale doubles each round: round 16 has 32768 decimal places, round 20 has 524288 var msg_buf: [1024 * 1024]u8 = undefined; // Initial send from P2P2: start with 1.01 (grows slower than 1.1) const initial_msg = "my number is 1.01"; _ = try p2p2.sendMessage(peer_id_from_p2p2, MSG_TYPE_NUMBER, initial_msg); std.debug.print(" [Round {d:2}] P2P2 -> P2P1: \"{s}\"\n", .{ round + 1, initial_msg }); const max_iterations = ROUNDS * 20; // Safety limit var iteration: u32 = 0; const start_time = std.time.milliTimestamp(); const timeout_ms: i64 = 30000; // 30 second timeout while (round < ROUNDS and iteration < max_iterations) : (iteration += 1) { // Check for timeout if (std.time.milliTimestamp() - start_time > timeout_ms) { std.debug.print("\n TIMEOUT: Test exceeded {d}ms\n", .{timeout_ms}); break; } // Process both instances try p2p1.update(); try p2p2.update(); // Check P2P1 for received messages (when P2P2 was sender) if (p2p2_is_sender) { while (p2p1.getNextEvent()) |event| { if (event.event_type == .message_received) { const received_data = event.data.message_received.data; if (received_data.len > 0) { // Parse and square the number using big integers if (parseAndSquare(allocator, received_data, &msg_buf)) |result| { const received_str = result.received; const response = result.response; _ = p2p1.sendMessage(peer_id_from_p2p1, MSG_TYPE_NUMBER, response) catch continue; round += 1; successful_rounds += 1; // Truncate display for very large numbers const recv_display = truncateForDisplay(received_str); const resp_display = truncateForDisplay(response); std.debug.print(" [Round {d:2}] P2P1 <- P2P2: received {s}, P2P1 -> P2P2: \"{s}\"\n", .{ round, recv_display, resp_display }); p2p2_is_sender = false; } } } } } else { // Check P2P2 for received messages (when P2P1 was sender) while (p2p2.getNextEvent()) |event| { if (event.event_type == .message_received) { const received_data = event.data.message_received.data; if (received_data.len > 0) { // Parse and square the number using big integers if (parseAndSquare(allocator, received_data, &msg_buf)) |result| { const received_str = result.received; const response = result.response; _ = p2p2.sendMessage(peer_id_from_p2p2, MSG_TYPE_NUMBER, response) catch continue; round += 1; successful_rounds += 1; // Truncate display for very large numbers const recv_display = truncateForDisplay(received_str); const resp_display = truncateForDisplay(response); std.debug.print(" [Round {d:2}] P2P2 <- P2P1: received {s}, P2P2 -> P2P1: \"{s}\"\n", .{ round, recv_display, resp_display }); p2p2_is_sender = true; } } } } } // Small delay to allow network processing std.Thread.sleep(10 * std.time.ns_per_ms); } // Show statistics std.debug.print("\n7. Test Results:\n", .{}); std.debug.print(" Rounds completed: {d}/{d}\n", .{ successful_rounds, ROUNDS }); std.debug.print(" P2P1 - Messages Sent: {d}, Received: {d}\n", .{ p2p1.stats.messages_sent.load(.monotonic), p2p1.stats.messages_received.load(.monotonic), }); std.debug.print(" P2P2 - Messages Sent: {d}, Received: {d}\n", .{ p2p2.stats.messages_sent.load(.monotonic), p2p2.stats.messages_received.load(.monotonic), }); // Verify connectivity worked if (successful_rounds >= ROUNDS) { std.debug.print("\n SUCCESS: All {d} rounds completed successfully!\n", .{ROUNDS}); } else if (successful_rounds > 0) { std.debug.print("\n PARTIAL: {d}/{d} rounds completed\n", .{ successful_rounds, ROUNDS }); } else { std.debug.print("\n FAILED: No rounds completed\n", .{}); } // Clean up std.debug.print("\n8. Cleaning up...\n", .{}); try p2p2.disconnectPeer(peer_id_from_p2p2); try p2p1.stop(); try p2p2.stop(); std.debug.print("\n=== Test Complete ===\n", .{}); } const ParseResult = struct { received: []const u8, response: []const u8, }; /// Fixed-point decimal number: value = mantissa / 10^scale const FixedPoint = struct { mantissa: BigInt, scale: usize, // number of decimal places fn init(allocator: std.mem.Allocator) !FixedPoint { return .{ .mantissa = try BigInt.init(allocator), .scale = 0, }; } fn deinit(self: *FixedPoint) void { self.mantissa.deinit(); } }; /// Parse a decimal string like "1.1" or "123.456" into fixed-point fn parseDecimal(allocator: std.mem.Allocator, str: []const u8) ?FixedPoint { // Find decimal point position var decimal_pos: ?usize = null; for (str, 0..) |c, i| { if (c == '.') { decimal_pos = i; break; } } var fp = FixedPoint.init(allocator) catch return null; errdefer fp.deinit(); if (decimal_pos) |pos| { // Has decimal point: "1.1" -> mantissa=11, scale=1 const int_part = str[0..pos]; const frac_part = str[pos + 1 ..]; fp.scale = frac_part.len; // Build mantissa string: integer part + fractional part var mantissa_str = allocator.alloc(u8, int_part.len + frac_part.len) catch return null; defer allocator.free(mantissa_str); @memcpy(mantissa_str[0..int_part.len], int_part); @memcpy(mantissa_str[int_part.len..], frac_part); fp.mantissa.setString(10, mantissa_str) catch return null; } else { // No decimal point: just an integer with scale 0 fp.mantissa.setString(10, str) catch return null; fp.scale = 0; } return fp; } /// Convert fixed-point to decimal string fn fixedPointToString(allocator: std.mem.Allocator, fp: *FixedPoint, buf: []u8) ?[]const u8 { const mantissa_str = fp.mantissa.toString(allocator, 10, .lower) catch return null; defer allocator.free(mantissa_str); if (fp.scale == 0) { // No decimal places needed return std.fmt.bufPrint(buf, "{s}", .{mantissa_str}) catch return null; } // Check buffer size const needed = if (mantissa_str.len <= fp.scale) 2 + fp.scale // "0." + zeros + mantissa else mantissa_str.len + 1; // mantissa + decimal point if (needed > buf.len) return null; if (mantissa_str.len <= fp.scale) { // Need leading zeros: e.g., mantissa=1, scale=2 -> "0.01" const zeros_needed = fp.scale - mantissa_str.len; var writer = std.io.fixedBufferStream(buf); writer.writer().writeAll("0.") catch return null; for (0..zeros_needed) |_| { writer.writer().writeByte('0') catch return null; } writer.writer().writeAll(mantissa_str) catch return null; return buf[0..writer.pos]; } else { // Insert decimal point: e.g., mantissa=121, scale=2 -> "1.21" const int_digits = mantissa_str.len - fp.scale; return std.fmt.bufPrint(buf, "{s}.{s}", .{ mantissa_str[0..int_digits], mantissa_str[int_digits..], }) catch return null; } } /// Parse number from message, square it using fixed-point, return both as strings fn parseAndSquare(allocator: std.mem.Allocator, data: []const u8, buf: []u8) ?ParseResult { const prefix = "my number is "; if (data.len <= prefix.len) return null; // Check if it starts with the prefix if (!std.mem.eql(u8, data[0..prefix.len], prefix)) return null; // Get the number string const num_str = data[prefix.len..]; // Parse as fixed-point number var num = parseDecimal(allocator, num_str) orelse return null; defer num.deinit(); // Square it: mantissa = mantissa * mantissa, scale = scale * 2 var squared = FixedPoint.init(allocator) catch return null; defer squared.deinit(); squared.mantissa.mul(&num.mantissa, &num.mantissa) catch return null; squared.scale = num.scale * 2; // Convert to decimal string const squared_str = fixedPointToString(allocator, &squared, buf[prefix.len..]) orelse return null; // Build the response message by prepending prefix @memcpy(buf[0..prefix.len], prefix); const response = buf[0 .. prefix.len + squared_str.len]; return ParseResult{ .received = num_str, .response = response, }; } /// Format display buffers for scientific notation (two buffers to allow two calls in same print) var display_buf1: [80]u8 = undefined; var display_buf2: [80]u8 = undefined; var use_buf1: bool = true; /// Format large numbers in scientific notation for display fn truncateForDisplay(s: []const u8) []const u8 { // Find the number part after "my number is " const prefix = "my number is "; const num_start = if (std.mem.startsWith(u8, s, prefix)) prefix.len else 0; const num_part = s[num_start..]; // If the number is short enough, return as-is if (num_part.len <= 25) { return s; } // Alternate between buffers so two calls in the same statement work const buf = if (use_buf1) &display_buf1 else &display_buf2; use_buf1 = !use_buf1; // Find decimal point position for proper exponent calculation var decimal_pos: ?usize = null; var significant_digits: usize = 0; for (num_part, 0..) |c, i| { if (c == '.') { decimal_pos = i; } else if (c >= '0' and c <= '9') { significant_digits += 1; } } // Calculate exponent: position of first digit relative to decimal const exponent: i64 = if (decimal_pos) |pos| @as(i64, @intCast(pos)) - 1 else @as(i64, @intCast(num_part.len)) - 1; // Collect significant digits (skip decimal point) var sig_buf: [10]u8 = undefined; var sig_idx: usize = 0; for (num_part) |c| { if (c >= '0' and c <= '9') { if (sig_idx < sig_buf.len) { sig_buf[sig_idx] = c; sig_idx += 1; } } } // Format in scientific notation: "1.234567e+N" if (sig_idx >= 2) { const result = std.fmt.bufPrint(buf, "{c}.{s}e{s}{d}", .{ sig_buf[0], sig_buf[1..@min(7, sig_idx)], if (exponent >= 0) "+" else "", exponent, }) catch return s; return result; } return s; }