Files
zigp2p/examples/encrypted_server.zig
2026-02-06 21:03:59 -03:00

150 lines
5.5 KiB
Zig

//! Encrypted P2P Server Example
//!
//! Demonstrates a P2P server with Noise Protocol encryption enabled.
//! Messages are automatically encrypted/decrypted using Noise_XX_25519_ChaChaPoly_BLAKE2b.
//! Also demonstrates DoS protection with stateless cookies.
const std = @import("std");
const p2p_lib = @import("p2p");
const P2P = p2p_lib.P2P;
const P2PConfig = p2p_lib.P2PConfig;
const Address = p2p_lib.Address;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
std.debug.print("=== Encrypted P2P Server ===\n\n", .{});
// Create P2P config with Noise encryption and DoS protection enabled
var config = P2PConfig.default();
config.network.listen_port = 9000;
config.network.enable_noise_encryption = true; // Enable Noise protocol
config.network.enable_dos_protection = true; // Enable DoS protection
config.network.dos_cookie_threshold = 1; // Low threshold for testing (1 conn/sec triggers cookies)
config.network.idle_timeout_ms = 300000; // 5 minute timeout
// Initialize P2P
var p2p = try P2P.init(allocator, config);
defer p2p.deinit();
// Verify encryption is enabled
if (p2p.isNoiseEnabled()) {
std.debug.print("Noise encryption: ENABLED\n", .{});
if (p2p.getNoisePublicKey()) |pk| {
std.debug.print("Server public key: ", .{});
for (pk) |b| {
std.debug.print("{x:0>2}", .{b});
}
std.debug.print("\n", .{});
}
} else {
std.debug.print("WARNING: Noise encryption is NOT enabled!\n", .{});
}
// Show DoS protection status
std.debug.print("DoS protection: ENABLED (threshold: {d} conn/sec)\n\n", .{
config.network.dos_cookie_threshold,
});
// Start P2P
try p2p.start();
std.debug.print("P2P started\n", .{});
// Start listening
var listen_addr = Address.init();
listen_addr.port = 9000;
listen_addr.data = .{ .ipv4 = .{ .bytes = .{ 0, 0, 0, 0 } } }; // Listen on all interfaces
try p2p.startListening(listen_addr);
std.debug.print("Listening on port 9000 for encrypted connections...\n\n", .{});
// Main loop
var message_count: u32 = 0;
while (true) {
// Update P2P (process network events)
try p2p.update();
// Process events
while (p2p.getNextEvent()) |event| {
defer {
var evt = event;
evt.deinit();
}
switch (event.event_type) {
.peer_connected => {
const data = event.data.peer_connected;
std.debug.print("[EVENT] Peer connected: ", .{});
for (data.peer_id.bytes[0..8]) |b| {
std.debug.print("{x:0>2}", .{b});
}
std.debug.print("...\n", .{});
// In a real app, you could verify the peer's public key here
// by checking the remote_static_key from the handshake
},
.connection_established => {
std.debug.print("[EVENT] Encrypted connection established!\n", .{});
},
.message_received => {
const msg = event.data.message_received;
message_count += 1;
std.debug.print("[MESSAGE #{d}] Received {d} bytes from peer: ", .{
message_count,
msg.data.len,
});
for (msg.source.bytes[0..8]) |b| {
std.debug.print("{x:0>2}", .{b});
}
std.debug.print("...\n", .{});
// Print message content (already decrypted by Noise layer)
if (msg.data.len > 0) {
std.debug.print(" Content: \"{s}\"\n", .{msg.data});
}
// Echo back with prefix
const response = std.fmt.allocPrint(allocator, "Server received: {s}", .{msg.data}) catch continue;
defer allocator.free(response);
_ = p2p.sendMessage(msg.source, 0x80, response) catch |err| {
std.debug.print(" Failed to send response: {}\n", .{err});
};
std.debug.print(" Sent encrypted response\n\n", .{});
},
.peer_disconnected => {
std.debug.print("[EVENT] Peer disconnected\n", .{});
},
.connection_failed => {
std.debug.print("[EVENT] Connection failed\n", .{});
},
.library_error => {
const err_data = event.data.library_error;
std.debug.print("[ERROR] {s}\n", .{err_data.message});
},
else => {},
}
}
// Print stats periodically
const stats = p2p.getStats();
const connections = stats.active_connections.load(.acquire);
if (connections > 0) {
// Keep running while we have connections
}
// Short sleep to prevent busy-waiting
std.Thread.sleep(10 * std.time.ns_per_ms);
// Run for a limited time for demo purposes (5 minutes)
// In production, you'd have proper shutdown handling
}
try p2p.stop();
std.debug.print("\nServer stopped. Total messages processed: {d}\n", .{message_count});
}