Files
zigp2p/src/p2p/p2p.zig

1657 lines
62 KiB
Zig

//! Main P2P Library Implementation
//!
//! This module contains the core P2P struct and its implementation.
//! It integrates all components including network, protocol, file sharing,
//! discovery, and routing into a unified, easy-to-use API.
//!
//! # Thread Safety and Lock Ordering
//!
//! CRITICAL: To prevent deadlocks, all locks MUST be acquired in this order:
//! 1. state_mutex (P2P state transitions - HIGHEST PRIORITY)
//! 2. event_mutex (P2P event queue)
//! 3. callbacks_mutex (P2P callback registration)
//! 4. peer_connections_mutex (P2P peer connections map)
//! 5. file_manager.sessions_mutex (if file_manager exists)
//! 6. network_manager.mutex (if network_manager exists)
//!
//! NEVER acquire locks in a different order. NEVER hold a lower-level lock
//! when acquiring a higher-level lock.
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap;
const Thread = std.Thread;
const Mutex = std.Thread.Mutex;
const atomic = std.atomic;
const Ed25519 = std.crypto.sign.Ed25519;
// Core components (via module import)
const core = @import("core");
const Error = core.errors.Error;
pub const Address = core.Address;
const Socket = core.Socket;
const Buffer = core.Buffer;
const Connection = core.Connection;
const RateLimiter = core.rate_limiter.RateLimiter;
const PeerRateLimiter = core.rate_limiter.PeerRateLimiter;
const ConnectionRateLimiter = core.rate_limiter.ConnectionRateLimiter;
// Network components (via module import)
const network = @import("network");
const PeerId = network.peer.PeerId;
const Peer = network.peer.Peer;
const Node = network.node.Node;
const DiscoveryManager = network.discovery.DiscoveryManager;
const NetworkTopology = network.topology.NetworkTopology;
const NetworkBridge = network.bridge.NetworkBridge;
const NetworkManager = network.network_manager.NetworkManager;
const PeerConnection = network.PeerConnection;
const PendingSend = network.PendingSend;
const DoSProtection = network.DoSProtection;
const KeyPinStore = network.KeyPinStore;
const PinningMode = network.PinningMode;
const VerifyResult = network.VerifyResult;
const NatPmp = network.NatPmp;
const Upnp = network.Upnp;
// Protocol components (via module import)
const protocol = @import("protocol");
const MessageHandler = protocol.handler.MessageHandler;
const HandlerRegistry = protocol.handler.HandlerRegistry;
const MessageRouter = protocol.router.MessageRouter;
const ProtocolHandler = protocol.protocol.ProtocolHandler;
const Message = protocol.message.Message;
const DataResponseHandler = protocol.handler.DataResponseHandler;
const RequestTracker = protocol.handler.RequestTracker;
const HandlerMetrics = protocol.handler.HandlerMetrics;
const DataResponse = protocol.message.DataResponse;
// File sharing components (via module import)
const files = @import("files");
const FileSharingManager = files.manager.FileSharingManager;
const FileMetadata = files.hash.FileMetadata;
const SessionStats = files.manager.SessionStats;
// Noise protocol components (via module import)
const noise = @import("noise");
const NoiseKeyPair = noise.KeyPair;
const SecureConnection = network.SecureConnection;
// Sibling module imports
const types = @import("types.zig");
const config = @import("config.zig");
const events = @import("events.zig");
const stats = @import("stats.zig");
const circuit_breaker = @import("circuit_breaker.zig");
// Re-export types from sibling modules
pub const P2PState = types.P2PState;
pub const P2PConfig = config.P2PConfig;
pub const LibraryConfig = config.LibraryConfig;
pub const NetworkConfig = config.NetworkConfig;
pub const ProtocolConfig = config.ProtocolConfig;
pub const FileSharingConfig = config.FileSharingConfig;
pub const EventConfig = config.EventConfig;
pub const BootstrapNode = config.BootstrapNode;
pub const P2PEvent = events.P2PEvent;
pub const EventCallback = events.EventCallback;
pub const UserContext = events.UserContext;
pub const P2PStats = stats.P2PStats;
pub const CircuitBreaker = circuit_breaker.CircuitBreaker;
/// Observed address from DHT response (Bundled STUN / IP Reflection)
pub const ObservedAddress = struct {
/// The observed IP address (IPv4 or IPv6)
ip: union(enum) {
v4: [4]u8,
v6: [16]u8,
},
/// The observed port
port: u16,
/// Timestamp when this was observed
timestamp: i64,
/// Which peer observed this address
observer_id: [32]u8,
/// Create from raw DHT response bytes
pub fn fromDhtResponse(addr_bytes: [18]u8, addr_len: u8, observer: [32]u8) ?ObservedAddress {
if (addr_len == 0) return null;
var result: ObservedAddress = undefined;
result.timestamp = std.time.milliTimestamp();
result.observer_id = observer;
if (addr_len == 6) {
// IPv4: 4 bytes IP + 2 bytes port
result.ip = .{ .v4 = addr_bytes[0..4].* };
result.port = std.mem.readInt(u16, addr_bytes[4..6], .big);
} else if (addr_len == 18) {
// IPv6: 16 bytes IP + 2 bytes port
result.ip = .{ .v6 = addr_bytes[0..16].* };
result.port = std.mem.readInt(u16, addr_bytes[16..18], .big);
} else {
return null;
}
return result;
}
/// Check if this is a valid public address (not localhost/private)
pub fn isPublic(self: ObservedAddress) bool {
switch (self.ip) {
.v4 => |ip| {
// Skip localhost (127.x.x.x)
if (ip[0] == 127) return false;
// Skip private ranges
if (ip[0] == 10) return false; // 10.0.0.0/8
if (ip[0] == 172 and ip[1] >= 16 and ip[1] <= 31) return false; // 172.16.0.0/12
if (ip[0] == 192 and ip[1] == 168) return false; // 192.168.0.0/16
if (ip[0] == 0) return false; // 0.0.0.0
return true;
},
.v6 => |ip| {
// Skip loopback (::1)
if (std.mem.eql(u8, &ip, &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 })) return false;
// Skip link-local (fe80::/10)
if (ip[0] == 0xfe and (ip[1] & 0xc0) == 0x80) return false;
return true;
},
}
}
};
// Implementation modules
const lifecycle = @import("lifecycle.zig");
const connection = @import("connection.zig");
const file_ops = @import("file_ops.zig");
const messaging = @import("messaging.zig");
const dht_ops = @import("dht.zig");
const event_handling = @import("event_handling.zig");
// ============================================================================
// Helper Callbacks
// ============================================================================
/// Callback to register a DHT node ID to connection peer ID mapping.
/// Called during key exchange when a remote peer's identity key is verified.
/// The identity public key serves as the DHT node ID (industry standard approach).
pub fn registerNodeIdCallback(node_id: [32]u8, peer_id: [32]u8, context: ?*anyopaque) void {
const p2p: *P2P = @ptrCast(@alignCast(context orelse {
std.log.err("registerNodeIdCallback: null context", .{});
return;
}));
// Store the mapping: DHT node ID -> connection peer ID
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
p2p.dht_node_to_peer.put(node_id, PeerId{ .bytes = peer_id }) catch |err| {
std.log.warn("Failed to register node ID mapping: {}", .{err});
return;
};
std.log.info("Registered DHT node ID mapping: {x} -> connection peer {x}", .{ node_id[0..8].*, peer_id[0..8].* });
}
/// Callback to send DHT messages using simple binary format.
/// Called by DHT handlers to send responses in the same format as requests.
pub fn sendDhtMessageCallback(peer_id: [32]u8, msg: protocol.message.Message, context: ?*anyopaque) bool {
const p2p: *P2P = @ptrCast(@alignCast(context orelse {
std.log.err("sendDhtMessageCallback: null context", .{});
return false;
}));
// Use the dht module's sendDhtMessageImpl which uses simple binary format
const dht_module = @import("dht.zig");
return dht_module.sendDhtMessageImpl(p2p, peer_id, msg);
}
/// Callback to record observed addresses from DHT responses (IP Reflection / Bundled STUN).
/// Called by DHT response handlers when they receive our public IP from peers.
pub fn addObservedAddressCallback(observed_addr: [18]u8, observed_addr_len: u8, observer_id: [32]u8, context: ?*anyopaque) void {
const p2p: *P2P = @ptrCast(@alignCast(context orelse {
std.log.err("addObservedAddressCallback: null context", .{});
return;
}));
p2p.addObservedAddress(observed_addr, observed_addr_len, observer_id);
}
/// Callback to handle data responses during file downloads.
///
/// This function processes incoming DataResponse messages and writes
/// the received data to the appropriate file via the FileSharingManager.
///
/// CRIT-1 FIX: Uses writePieceDataByHash() which holds the session mutex during
/// the entire operation, preventing TOCTOU race conditions.
///
/// CRIT-NEW-15 FIX: The `orelse` pattern ensures null is checked BEFORE the cast.
/// In Zig, `@ptrCast(@alignCast(x orelse { return; }))` evaluates as:
/// 1. Evaluate `x` (the optional)
/// 2. Check if null via `orelse`, return early if so
/// 3. Only if non-null, cast the unwrapped pointer
pub fn handleDataResponseCallback(
context: ?*anyopaque,
request_tracker: *RequestTracker,
data_resp: DataResponse,
metrics: *HandlerMetrics,
) anyerror!void {
// CRIT-NEW-15 FIX: Null check happens before cast via orelse
const p2p: *P2P = @ptrCast(@alignCast(context orelse {
std.log.err("CRIT-1: Data response handler called with null context", .{});
return error.InvalidContext;
}));
const fm = p2p.file_manager orelse {
std.log.err("DataResponse rejected: No file manager configured", .{});
metrics.recordMessageFailed();
return error.FileManagerNotConfigured;
};
// Resolve the request ID to get piece information
const request_info = request_tracker.resolveRequest(data_resp.request_id) orelse {
std.log.warn("Unknown or expired request_id: {d}", .{data_resp.request_id});
metrics.recordMessageFailed();
return error.InvalidData;
};
const piece_index = request_info.piece_index;
const offset_in_piece = request_info.offset;
const content_hash = request_info.file_hash;
// Verify data size matches expected size
if (data_resp.data.len != request_info.size) {
std.log.warn("Data size mismatch: expected {d}, got {d}", .{
request_info.size,
data_resp.data.len,
});
}
// CRIT-1 FIX: Use writePieceDataByHash which holds the session mutex during
// the entire operation, preventing TOCTOU race. This replaces the unsafe pattern:
// session = findSessionByHash(hash) // mutex released after this
// session.download_manager.write() // race: session could be invalidated
const result = fm.writePieceDataByHash(
content_hash,
piece_index,
offset_in_piece,
data_resp.data,
) catch |err| {
std.log.err("Failed to write piece {d} at offset {d}: {}", .{
piece_index,
offset_in_piece,
err,
});
metrics.recordMessageFailed();
return err;
};
// Log progress
std.log.debug("Downloaded piece {d} offset {d} ({d} bytes) - Progress: {d:.1}%", .{
piece_index,
offset_in_piece,
data_resp.data.len,
result.progress * 100,
});
// Check completion
if (result.is_complete) {
std.log.info("Download completed for file!", .{});
}
metrics.recordMessageProcessed(0.0);
}
// ============================================================================
// P2P Struct Definition
// ============================================================================
/// Main P2P Library Interface
///
/// This is the central entry point for all P2P functionality. It manages
/// all subsystems and provides a unified API for users.
pub const P2P = struct {
/// Allocator for memory management
allocator: Allocator,
/// CRIT-8 FIX: Tracking allocator for global memory budget enforcement
/// If set, this is owned by this P2P instance and must be deinitialized
memory_tracker: ?*core.TrackingAllocator = null,
/// Library state (protected by state_mutex)
state: P2PState = .Uninitialized,
/// State mutex to protect state field transitions
state_mutex: Mutex = .{},
/// Configuration
config: P2PConfig,
/// Event queue and management
event_queue: ArrayList(P2PEvent),
event_mutex: Mutex,
user_contexts: ArrayList(UserContext),
event_handlers: ArrayList(EventCallback),
/// Mutex to protect user_contexts and event_handlers (THREAD SAFETY)
callbacks_mutex: Mutex,
/// Network components
address: Address,
node: ?*Node,
discovery_manager: ?*DiscoveryManager,
topology: ?*NetworkTopology,
network_bridge: ?*NetworkBridge,
peer_manager: ?*network.peer.PeerManager,
/// Connection layer components
connection_pool: ?*core.connection.ConnectionPool,
/// Map of peer IDs to PeerConnection structs (each with its own send mutex for parallel I/O)
peer_connections: std.AutoHashMap(PeerId, *PeerConnection),
/// Mutex for modifying the peer_connections map itself (add/remove peers).
/// Note: Individual sends use per-peer mutexes for parallelism.
peer_connections_mutex: Mutex,
listen_socket: ?*Socket,
listen_address: ?Address,
/// Protocol components
handler_registry: ?*HandlerRegistry,
message_router: ?*MessageRouter,
network_manager: ?*NetworkManager,
/// File sharing components
file_manager: ?*FileSharingManager,
/// Rate limiting components
peer_rate_limiter: ?*PeerRateLimiter,
connection_rate_limiter: ?*ConnectionRateLimiter,
/// NAT traversal components
turn_integration: ?*network.TurnIntegration,
/// DHT components
routing_table: ?*network.KademliaRoutingTable,
dht_coordinator: ?*network.DhtCoordinator,
/// Identity and node ID management
/// Ed25519 keypair for node identity - public key serves as DHT node ID
identity_keypair: Ed25519.KeyPair,
/// Local node ID (= identity public key) - used for DHT and peer identification
local_node_id: [32]u8,
/// Noise protocol keypair for encrypted transport (X25519)
/// Used for Noise XX handshake - separate from Ed25519 identity
noise_keypair: ?NoiseKeyPair,
/// Whether Noise encryption is enabled for connections
noise_enabled: bool,
/// DoS protection manager (stateless cookie-based)
dos_protection: ?*DoSProtection,
/// Key pinning store for TOFU/strict mode
key_pin_store: ?*KeyPinStore,
/// Connection backoff manager for retry with exponential backoff
connection_backoff: ?*network.ConnectionBackoff,
/// Mapping from remote DHT node IDs to connection peer IDs
/// This allows DHT to send messages to peers by their node ID
dht_node_to_peer: std.AutoHashMap([32]u8, PeerId),
/// Mutex for dht_node_to_peer map
dht_node_to_peer_mutex: Mutex,
/// Observed public addresses from DHT responses (Bundled STUN / IP Reflection)
/// Stores our public IP:port as seen by DHT peers
observed_addresses: std.ArrayList(ObservedAddress),
/// Mutex for observed_addresses
observed_addresses_mutex: Mutex,
/// Statistics
stats: P2PStats,
/// Internal flags (THREAD SAFETY: atomic for lock-free access from multiple threads)
initialized: atomic.Value(bool) = atomic.Value(bool).init(false),
running: atomic.Value(bool) = atomic.Value(bool).init(false),
/// Start time for uptime tracking
start_time: i64 = 0,
/// Last health check timestamp
last_health_check: i64 = 0,
/// Last replay protection cleanup timestamp
last_replay_cleanup: i64 = 0,
/// Error rate tracking for maintenance mode
error_window_start: i64 = 0,
errors_in_window: atomic.Value(u32) = atomic.Value(u32).init(0),
/// Last maintenance check timestamp
last_maintenance_check: i64 = 0,
/// IMP-2 FIX: Circuit breaker for preventing cascading failures
/// Used to protect against repeated connection/operation failures
circuit_breaker: CircuitBreaker = CircuitBreaker.init(5, 3, 30000),
/// Last error summary emission
last_error_summary: i64 = 0,
// =========================================================================
// Init/Deinit Methods (kept inline - complex initialization logic)
// =========================================================================
/// Initialize the P2P library
pub fn init(backing_allocator: Allocator, p2p_config: P2PConfig) Error!P2P {
return initWithMemoryLimitCustom(backing_allocator, p2p_config, core.limits.global.memory.max_global_memory_quota);
}
/// Initialize P2P library WITHOUT memory limit enforcement
pub fn initWithoutMemoryLimit(allocator: Allocator, p2p_config: P2PConfig) Error!P2P {
var p2p = P2P{
.allocator = allocator,
.config = p2p_config,
.event_queue = .{},
.event_mutex = Mutex{},
.user_contexts = .{},
.event_handlers = .{},
.callbacks_mutex = Mutex{},
.address = Address.init(),
.node = null,
.discovery_manager = null,
.topology = null,
.network_bridge = null,
.peer_manager = null,
.connection_pool = null,
.peer_connections = std.AutoHashMap(PeerId, *PeerConnection).init(allocator),
.peer_connections_mutex = Mutex{},
.listen_socket = null,
.listen_address = null,
.handler_registry = null,
.message_router = null,
.network_manager = null,
.file_manager = null,
.peer_rate_limiter = null,
.connection_rate_limiter = null,
.turn_integration = null,
.routing_table = null,
.dht_coordinator = null,
.identity_keypair = Ed25519.KeyPair.generate(),
.local_node_id = undefined,
.noise_keypair = if (p2p_config.network.enable_noise_encryption)
(if (p2p_config.network.noise_static_key) |key|
NoiseKeyPair.fromPrivate(key) catch return Error.EncryptionFailed
else
NoiseKeyPair.generate())
else
null,
.noise_enabled = p2p_config.network.enable_noise_encryption,
.dos_protection = null,
.key_pin_store = null,
.connection_backoff = null,
.dht_node_to_peer = std.AutoHashMap([32]u8, PeerId).init(allocator),
.dht_node_to_peer_mutex = Mutex{},
.observed_addresses = .{},
.observed_addresses_mutex = Mutex{},
.stats = P2PStats{
.state = .Uninitialized,
.uptime_seconds = 0,
.memory_allocated = 0,
.active_connections = atomic.Value(u32).init(0),
.total_connections = atomic.Value(u64).init(0),
.messages_sent = atomic.Value(u64).init(0),
.messages_received = atomic.Value(u64).init(0),
.current_download_rate = atomic.Value(u64).init(0),
.current_upload_rate = atomic.Value(u64).init(0),
.active_downloads = atomic.Value(u32).init(0),
.active_uploads = atomic.Value(u32).init(0),
.total_downloaded = atomic.Value(u64).init(0),
.total_uploaded = atomic.Value(u64).init(0),
.event_queue_size = 0,
.events_processed = atomic.Value(u64).init(0),
.events_dropped = atomic.Value(u64).init(0),
.errors_total = atomic.Value(u64).init(0),
.receive_errors = atomic.Value(u64).init(0),
},
.start_time = 0,
.last_health_check = 0,
.last_replay_cleanup = 0,
.error_window_start = 0,
.last_maintenance_check = 0,
};
errdefer p2p.peer_connections.deinit();
errdefer p2p.event_queue.deinit(allocator);
errdefer p2p.user_contexts.deinit(allocator);
errdefer p2p.event_handlers.deinit(allocator);
errdefer p2p.dht_node_to_peer.deinit();
// Set local node ID from identity public key
p2p.local_node_id = p2p.identity_keypair.public_key.bytes;
std.log.info("P2P local node ID (from identity): ", .{});
// Log Noise encryption status
if (p2p.noise_enabled) {
if (p2p.noise_keypair) |_| {
std.log.info("Noise encryption enabled", .{});
}
} else {
std.log.debug("Noise encryption disabled", .{});
}
// Initialize DoS protection if enabled
if (p2p_config.network.enable_dos_protection) {
const dos = try allocator.create(DoSProtection);
dos.* = DoSProtection.initWithThreshold(p2p_config.network.dos_cookie_threshold);
p2p.dos_protection = dos;
std.log.debug("DoS protection enabled, cookie threshold: {d} connections/sec", .{p2p_config.network.dos_cookie_threshold});
} else {
std.log.debug("DoS protection disabled", .{});
}
errdefer if (p2p.dos_protection) |dos| allocator.destroy(dos);
// Initialize key pinning if Noise encryption is enabled
if (p2p_config.network.enable_noise_encryption) {
const kps = try allocator.create(KeyPinStore);
kps.* = KeyPinStore.initWithConfig(allocator, p2p_config.network.key_pinning_mode, p2p_config.network.max_pinned_keys);
p2p.key_pin_store = kps;
if (p2p_config.network.key_pin_file) |path| {
const loaded = network.key_pinning.loadFromFile(kps, path) catch |err| blk: {
std.log.warn("Failed to load pinned keys from {s}: {}", .{ path, err });
break :blk @as(usize, 0);
};
if (loaded > 0) {
std.log.info("Loaded {d} pinned keys from {s}", .{ loaded, path });
}
}
std.log.debug("Key pinning enabled, mode: {s}, max keys: {d}", .{
@tagName(p2p_config.network.key_pinning_mode),
p2p_config.network.max_pinned_keys,
});
}
errdefer if (p2p.key_pin_store) |kps| {
kps.deinit();
allocator.destroy(kps);
};
// Initialize connection backoff if retry is enabled
if (p2p_config.network.handshake_retry_enabled) {
const backoff = try allocator.create(network.ConnectionBackoff);
backoff.* = network.ConnectionBackoff.init(allocator, .{
.max_attempts = p2p_config.network.handshake_max_attempts,
.initial_delay_ms = p2p_config.network.handshake_initial_backoff_ms,
.max_delay_ms = p2p_config.network.handshake_max_backoff_ms,
.multiplier = p2p_config.network.handshake_backoff_multiplier,
});
p2p.connection_backoff = backoff;
std.log.debug("Connection backoff enabled, max attempts: {d}, initial delay: {d}ms", .{
p2p_config.network.handshake_max_attempts,
p2p_config.network.handshake_initial_backoff_ms,
});
}
errdefer if (p2p.connection_backoff) |backoff| {
backoff.deinit();
allocator.destroy(backoff);
};
// Set up address
p2p.address.port = p2p_config.network.listen_port;
p2p.state_mutex.lock();
p2p.state = .Initialized;
p2p.state_mutex.unlock();
p2p.initialized.store(true, .release);
try p2p.emitEvent(P2PEvent.create(.library_initialized, .library_initialized));
return p2p;
}
/// Initialize with global memory budget enforcement
pub fn initWithMemoryLimit(backing_allocator: Allocator, p2p_config: P2PConfig) Error!P2P {
return initWithMemoryLimitCustom(backing_allocator, p2p_config, core.limits.global.memory.max_global_memory_quota);
}
/// Initialize with custom memory budget
pub fn initWithMemoryLimitCustom(backing_allocator: Allocator, p2p_config: P2PConfig, max_memory_bytes: u64) Error!P2P {
const tracker_ptr = backing_allocator.create(core.TrackingAllocator) catch {
return Error.SystemError;
};
errdefer backing_allocator.destroy(tracker_ptr);
tracker_ptr.* = core.TrackingAllocator.init(backing_allocator, max_memory_bytes);
const tracked_allocator = tracker_ptr.allocator();
var p2p = initWithoutMemoryLimit(tracked_allocator, p2p_config) catch |err| {
backing_allocator.destroy(tracker_ptr);
return err;
};
p2p.memory_tracker = tracker_ptr;
std.log.info("CRIT-8: P2P initialized with memory budget: {d} MB", .{max_memory_bytes / (1024 * 1024)});
return p2p;
}
/// Get memory statistics if tracking is enabled
pub fn getMemoryStats(p2p: *const P2P) ?core.TrackingAllocator.Stats {
if (p2p.memory_tracker) |tracker| {
return tracker.getStats();
}
return null;
}
/// Deinitialize the P2P library
pub fn deinit(p2p: *P2P) void {
if (!p2p.initialized.load(.acquire)) return;
if (p2p.running.load(.acquire)) {
p2p.stop() catch |err| {
std.log.warn("Failed to stop P2P library during deinit: {}", .{err});
};
}
// Clean up file sharing manager
if (p2p.file_manager) |manager| {
if (manager.network_sender) |sender| {
p2p.allocator.destroy(sender);
}
manager.deinit();
p2p.allocator.destroy(manager);
}
// Clean up protocol components
if (p2p.network_manager) |manager| {
manager.deinit();
p2p.allocator.destroy(manager);
}
if (p2p.message_router) |router| {
router.deinit();
p2p.allocator.destroy(router);
}
if (p2p.handler_registry) |registry| {
registry.deinit();
p2p.allocator.destroy(registry);
}
// Clean up rate limiters
if (p2p.peer_rate_limiter) |prl| {
prl.deinit();
p2p.allocator.destroy(prl);
}
if (p2p.connection_rate_limiter) |crl| {
crl.deinit();
p2p.allocator.destroy(crl);
}
// Clean up DoS protection
if (p2p.dos_protection) |dos| {
p2p.allocator.destroy(dos);
}
// Clean up key pinning store
if (p2p.key_pin_store) |kps| {
if (p2p.config.network.key_pin_file) |path| {
network.key_pinning.saveToFile(kps, path) catch |err| {
std.log.warn("Failed to save pinned keys to {s}: {}", .{ path, err });
};
}
kps.deinit();
p2p.allocator.destroy(kps);
}
// Clean up connection backoff manager
if (p2p.connection_backoff) |backoff| {
backoff.deinit();
p2p.allocator.destroy(backoff);
}
// Clean up NAT traversal components
if (p2p.turn_integration) |integration| {
integration.deinit();
p2p.allocator.destroy(integration);
}
// Clean up DHT components
if (p2p.dht_coordinator) |dht| {
dht.deinit();
p2p.allocator.destroy(dht);
}
if (p2p.routing_table) |rt| {
rt.deinit();
p2p.allocator.destroy(rt);
}
p2p.dht_node_to_peer.deinit();
p2p.observed_addresses.deinit(p2p.allocator);
// Clean up network components
if (p2p.network_bridge) |bridge| {
bridge.deinit();
p2p.allocator.destroy(bridge);
}
if (p2p.discovery_manager) |discovery| {
discovery.deinit();
p2p.allocator.destroy(discovery);
}
if (p2p.topology) |topo| {
topo.deinit();
p2p.allocator.destroy(topo);
}
if (p2p.node) |node_ptr| {
node_ptr.deinit();
p2p.allocator.destroy(node_ptr);
}
// Clean up connection layer
if (p2p.connection_pool) |pool| {
pool.deinit();
p2p.allocator.destroy(pool);
}
if (p2p.peer_manager) |pm| {
pm.deinit();
p2p.allocator.destroy(pm);
}
// Close and cleanup peer connections
p2p.peer_connections_mutex.lock();
var iter = p2p.peer_connections.iterator();
while (iter.next()) |entry| {
const peer_conn = entry.value_ptr.*;
peer_conn.socket.deinit();
p2p.allocator.destroy(peer_conn.socket);
peer_conn.deinit();
}
p2p.peer_connections.deinit();
p2p.peer_connections_mutex.unlock();
// Close listen socket
if (p2p.listen_socket) |socket| {
socket.deinit();
p2p.allocator.destroy(socket);
}
// Clean up event system
for (p2p.event_queue.items) |*event| {
event.deinit();
}
p2p.event_handlers.deinit(p2p.allocator);
p2p.user_contexts.deinit(p2p.allocator);
p2p.event_queue.deinit(p2p.allocator);
// Clean up memory tracker
if (p2p.memory_tracker) |tracker| {
const mem_stats = tracker.getStats();
std.log.info("CRIT-8: Final memory stats - peak: {d} MB, allocated: {d} bytes, rejected: {d}", .{
mem_stats.peak_bytes / (1024 * 1024),
mem_stats.allocated_bytes,
mem_stats.rejected_count,
});
const backing = tracker.backing_allocator;
backing.destroy(tracker);
}
p2p.initialized.store(false, .release);
p2p.state_mutex.lock();
p2p.state = .Uninitialized;
p2p.state_mutex.unlock();
}
// =========================================================================
// Lifecycle Methods (delegate to lifecycle.zig)
// =========================================================================
pub fn start(p2p: *P2P) Error!void {
return lifecycle.startImpl(p2p);
}
pub fn stop(p2p: *P2P) Error!void {
return lifecycle.stopImpl(p2p);
}
pub fn shutdown(p2p: *P2P) void {
return lifecycle.shutdownImpl(p2p);
}
pub fn enterMaintenanceMode(p2p: *P2P) Error!void {
return lifecycle.enterMaintenanceModeImpl(p2p);
}
pub fn exitMaintenanceMode(p2p: *P2P) Error!void {
return lifecycle.exitMaintenanceModeImpl(p2p);
}
pub fn setErrorState(p2p: *P2P, err: Error, message: []const u8) Error!void {
return lifecycle.setErrorStateImpl(p2p, err, message);
}
pub fn recoverFromError(p2p: *P2P) Error!void {
return lifecycle.recoverFromErrorImpl(p2p);
}
pub fn updateConfig(p2p: *P2P, new_config: P2PConfig) Error!void {
return lifecycle.updateConfigImpl(p2p, new_config);
}
// =========================================================================
// Connection Methods (delegate to connection.zig)
// =========================================================================
pub fn connectToPeer(p2p: *P2P, address: Address) Error!PeerId {
return connection.connectToPeerImpl(p2p, address);
}
pub fn disconnectPeer(p2p: *P2P, peer_id: PeerId) Error!void {
return connection.disconnectPeerImpl(p2p, peer_id);
}
pub fn acceptConnections(p2p: *P2P) Error!void {
return connection.acceptConnectionsImpl(p2p);
}
pub fn startListening(p2p: *P2P, address: Address) Error!void {
return connection.startListeningImpl(p2p, address);
}
pub fn getPeerSocket(p2p: *P2P, peer_id: PeerId) ?*Socket {
return connection.getPeerSocketImpl(p2p, peer_id);
}
pub fn addPeerConnection(p2p: *P2P, peer_id: PeerId, socket: *Socket) Error!void {
return connection.addPeerConnectionImpl(p2p, peer_id, socket);
}
pub fn addPeerConnectionSecure(p2p: *P2P, peer_id: PeerId, socket: *Socket, secure: ?*SecureConnection) Error!void {
return connection.addPeerConnectionSecureImpl(p2p, peer_id, socket, secure);
}
pub fn removePeerConnection(p2p: *P2P, peer_id: PeerId) ?*Socket {
return connection.removePeerConnectionImpl(p2p, peer_id);
}
pub fn sendToPeerAtomic(p2p: *P2P, peer_id: PeerId, data: []const u8) Error!bool {
return connection.sendToPeerAtomicImpl(p2p, peer_id, data);
}
pub fn sendSegmentsToPeerAtomic(p2p: *P2P, peer_id: PeerId, segments: []const []const u8) Error!bool {
return connection.sendSegmentsToPeerAtomicImpl(p2p, peer_id, segments);
}
pub fn drainPendingSends(p2p: *P2P) void {
return connection.drainPendingSendsImpl(p2p);
}
// =========================================================================
// File Operations (delegate to file_ops.zig)
// =========================================================================
pub fn addFile(p2p: *P2P, file_path: []const u8) Error!u64 {
return file_ops.addFileImpl(p2p, file_path);
}
pub fn addFileWithMetadata(p2p: *P2P, file_path: []const u8, metadata: FileMetadata) Error!u64 {
return file_ops.addFileWithMetadataImpl(p2p, file_path, metadata);
}
pub fn downloadFile(p2p: *P2P, metadata: FileMetadata, output_path: []const u8) Error!u64 {
return file_ops.downloadFileImpl(p2p, metadata, output_path);
}
pub fn startSharing(p2p: *P2P, session_id: u64) Error!void {
return file_ops.startSharingImpl(p2p, session_id);
}
pub fn stopSharing(p2p: *P2P, session_id: u64) Error!void {
return file_ops.stopSharingImpl(p2p, session_id);
}
pub fn getFileMetadata(p2p: *P2P, session_id: u64) Error!?FileMetadata {
return file_ops.getFileMetadataImpl(p2p, session_id);
}
/// Free file metadata that was returned by getFileMetadata()
///
/// The metadata returned by getFileMetadata() contains heap-allocated
/// name and piece_hashes fields that must be freed when no longer needed.
pub fn freeFileMetadata(p2p: *P2P, metadata: FileMetadata) void {
if (metadata.piece_hashes.len > 0) {
p2p.allocator.free(metadata.piece_hashes);
}
if (metadata.name.len > 0) {
p2p.allocator.free(metadata.name);
}
}
// =========================================================================
// Messaging Methods (delegate to messaging.zig)
// =========================================================================
pub fn sendMessage(p2p: *P2P, destination: ?PeerId, message_type: u8, data: []const u8) Error!u64 {
return messaging.sendMessageImpl(p2p, destination, message_type, data);
}
pub fn emitEvent(p2p: *P2P, event: P2PEvent) Error!void {
return messaging.emitEventImpl(p2p, event);
}
/// Process network I/O and internal state updates.
///
/// **CRITICAL**: This function MUST be called periodically in your application's
/// main loop. Without calling update(), the library will not:
/// - Receive incoming messages
/// - Accept new connections
/// - Process DHT queries/responses
/// - Handle file transfers
///
/// This poll-based design enables WASM compatibility and single-threaded operation.
///
/// ## Example
/// ```zig
/// while (running) {
/// try p2p.update(); // Process all pending I/O
/// // ... your application logic ...
/// std.Thread.sleep(10 * std.time.ns_per_ms);
/// }
/// ```
///
/// ## Recommended Call Frequency
/// - 10-100ms intervals for most applications
/// - More frequent for lower latency requirements
/// - Less frequent is OK for idle applications (but responses will be delayed)
pub fn update(p2p: *P2P) Error!void {
return messaging.updateImpl(p2p);
}
// =========================================================================
// Event Handling Methods (delegate to event_handling.zig)
// =========================================================================
pub fn registerCallback(p2p: *P2P, callback: EventCallback, context_data: ?*anyopaque) Error!void {
return event_handling.registerCallbackImpl(p2p, callback, context_data);
}
pub fn unregisterCallback(p2p: *P2P, callback: EventCallback) Error!void {
return event_handling.unregisterCallbackImpl(p2p, callback);
}
pub fn getEventCount(p2p: *P2P) usize {
return event_handling.getEventCountImpl(p2p);
}
pub fn getNextEvent(p2p: *P2P) ?P2PEvent {
return event_handling.getNextEventImpl(p2p);
}
pub fn processNextEvent(p2p: *P2P) bool {
return event_handling.processNextEventImpl(p2p);
}
pub fn processAllEvents(p2p: *P2P) usize {
return event_handling.processAllEventsImpl(p2p);
}
pub fn getStats(p2p: *P2P) P2PStats {
return event_handling.getStatsImpl(p2p);
}
pub fn isOperational(p2p: *P2P) bool {
return event_handling.isOperationalImpl(p2p);
}
pub fn getState(p2p: *P2P) P2PState {
return event_handling.getStateImpl(p2p);
}
// =========================================================================
// DHT Methods (delegate to dht.zig)
// =========================================================================
pub fn getDhtPeerCount(p2p: *P2P) usize {
return dht_ops.getDhtPeerCountImpl(p2p);
}
/// Get the number of active connections (connected peers)
pub fn getActiveConnectionCount(p2p: *P2P) u32 {
return p2p.stats.active_connections.load(.monotonic);
}
/// Get the number of DHT node ID mappings (peers we can route DHT messages to)
pub fn getDhtMappingCount(p2p: *P2P) usize {
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
return p2p.dht_node_to_peer.count();
}
/// Add all currently mapped DHT peers to the routing table.
/// This is useful when you want to be able to query peers that have connected to you
/// but haven't been explicitly added to your routing table via dhtAddPeer.
pub fn addMappedPeersToRoutingTable(p2p: *P2P) !usize {
var added: usize = 0;
// Collect node IDs and their connection peer IDs
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
var iter = p2p.dht_node_to_peer.iterator();
while (iter.next()) |entry| {
const node_id = entry.key_ptr.*;
const connection_peer_id = entry.value_ptr.*;
// Get the socket for this connection peer
const socket = p2p.getPeerSocket(connection_peer_id) orelse continue;
// Get the peer's address from the socket (already in our Address type)
const address = socket.getPeerAddress() catch continue;
// Add to routing table
p2p.dhtAddPeer(node_id, address) catch continue;
added += 1;
}
return added;
}
pub fn dhtStore(p2p: *P2P, key: [32]u8, value: []const u8, ttl: u32) Error!void {
return dht_ops.dhtStoreImpl(p2p, key, value, ttl);
}
pub fn dhtFindValue(p2p: *P2P, key: [32]u8) Error!?[]u8 {
return dht_ops.dhtFindValueImpl(p2p, key);
}
pub fn dhtFindNode(p2p: *P2P, target_id: [32]u8) Error![]const [32]u8 {
return dht_ops.dhtFindNodeImpl(p2p, target_id);
}
pub fn getDhtLocalId(p2p: *P2P) ?[32]u8 {
return dht_ops.getDhtLocalIdImpl(p2p);
}
pub fn registerDhtNodeId(p2p: *P2P, node_id: [32]u8, connection_peer_id: PeerId) Error!void {
return dht_ops.registerDhtNodeIdImpl(p2p, node_id, connection_peer_id);
}
pub fn dhtAddPeer(p2p: *P2P, peer_id: [32]u8, address: Address) Error!void {
return dht_ops.dhtAddPeerImpl(p2p, peer_id, address);
}
// =========================================================================
// Bundled STUN / IP Reflection (Observed Address Management)
// =========================================================================
/// Store an observed address from a DHT response (called internally by DHT handlers)
pub fn addObservedAddress(p2p: *P2P, addr_bytes: [18]u8, addr_len: u8, observer_id: [32]u8) void {
const observed = ObservedAddress.fromDhtResponse(addr_bytes, addr_len, observer_id) orelse return;
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
// Check if we already have this address from this observer
for (p2p.observed_addresses.items) |*existing| {
const same_observer = std.mem.eql(u8, &existing.observer_id, &observer_id);
const same_addr = switch (observed.ip) {
.v4 => |ip| switch (existing.ip) {
.v4 => |eip| std.mem.eql(u8, &ip, &eip) and observed.port == existing.port,
.v6 => false,
},
.v6 => |ip| switch (existing.ip) {
.v6 => |eip| std.mem.eql(u8, &ip, &eip) and observed.port == existing.port,
.v4 => false,
},
};
if (same_observer or same_addr) {
// Update timestamp
existing.timestamp = observed.timestamp;
return;
}
}
// Add new observed address (limit to 10 entries to prevent unbounded growth)
if (p2p.observed_addresses.items.len >= 10) {
// Remove oldest entry
_ = p2p.observed_addresses.orderedRemove(0);
}
p2p.observed_addresses.append(p2p.allocator, observed) catch return;
// Log if this is a public address
if (observed.isPublic()) {
switch (observed.ip) {
.v4 => |ip| std.log.info("Bundled STUN: Discovered public address {d}.{d}.{d}.{d}:{d}", .{ ip[0], ip[1], ip[2], ip[3], observed.port }),
.v6 => std.log.info("Bundled STUN: Discovered public IPv6 address (port {d})", .{observed.port}),
}
}
}
/// Sentinel observer ID for NAT-PMP discovered addresses (hash of "NAT-PMP")
pub const NAT_PMP_OBSERVER_ID: [32]u8 = [_]u8{
0x4e, 0x41, 0x54, 0x2d, 0x50, 0x4d, 0x50, 0x00, // "NAT-PMP\0"
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
/// Try to discover external address via NAT-PMP and request a port mapping.
/// Returns the external IP if successful, null if NAT-PMP is not available.
pub fn tryNatPmpDiscovery(p2p: *P2P, internal_port: u16, lifetime_seconds: u32) ?[4]u8 {
var nat = NatPmp.init(p2p.allocator) catch |err| {
std.log.debug("NAT-PMP: Gateway discovery failed: {}", .{err});
return null;
};
defer nat.deinit();
// First try to get external address
const external_ip = nat.getExternalAddress() catch |err| {
std.log.debug("NAT-PMP: getExternalAddress failed: {}", .{err});
return null;
} orelse return null;
std.log.info("NAT-PMP: External address is {d}.{d}.{d}.{d}", .{
external_ip[0], external_ip[1], external_ip[2], external_ip[3],
});
// Request port mapping (UDP for P2P)
const mapping = nat.mapPort(.udp, internal_port, internal_port, lifetime_seconds) catch |err| {
std.log.debug("NAT-PMP: mapPort failed: {}", .{err});
// Still return external IP even if mapping fails
p2p.addNatPmpAddress(external_ip, internal_port);
return external_ip;
} orelse {
// Mapping returned null but we have external IP
p2p.addNatPmpAddress(external_ip, internal_port);
return external_ip;
};
std.log.info("NAT-PMP: Mapped port {d} -> external port {d} (lifetime: {d}s)", .{
mapping.internal_port, mapping.external_port, mapping.lifetime_seconds,
});
// Add the mapped address to observed addresses
p2p.addNatPmpAddress(mapping.external_ip, mapping.external_port);
return mapping.external_ip;
}
/// Sentinel observer ID for UPnP IGD discovered addresses (hash of "UPnP-IGD")
pub const UPNP_OBSERVER_ID: [32]u8 = [_]u8{
0x55, 0x50, 0x6e, 0x50, 0x2d, 0x49, 0x47, 0x44, // "UPnP-IGD"
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
/// Try to discover external address via UPnP IGD and request a port mapping.
/// Returns the external IP if successful, null if UPnP is not available.
pub fn tryUpnpDiscovery(p2p: *P2P, internal_port: u16, lifetime_seconds: u32) ?[4]u8 {
var upnp_client = Upnp.init(p2p.allocator) catch |err| {
std.log.debug("UPnP: Gateway discovery failed: {}", .{err});
return null;
};
defer upnp_client.deinit();
// First try to get external address
const external_ip = upnp_client.getExternalAddress() catch |err| {
std.log.debug("UPnP: getExternalAddress failed: {}", .{err});
return null;
} orelse return null;
std.log.info("UPnP: External address is {d}.{d}.{d}.{d}", .{
external_ip[0], external_ip[1], external_ip[2], external_ip[3],
});
// Request port mapping (UDP for P2P)
const mapping = upnp_client.mapPort(.udp, internal_port, internal_port, lifetime_seconds) catch |err| {
std.log.debug("UPnP: mapPort failed: {}", .{err});
// Still return external IP even if mapping fails
p2p.addUpnpAddress(external_ip, internal_port);
return external_ip;
} orelse {
// Mapping returned null but we have external IP
p2p.addUpnpAddress(external_ip, internal_port);
return external_ip;
};
std.log.info("UPnP: Mapped port {d} -> external port {d} (lifetime: {d}s)", .{
mapping.internal_port, mapping.external_port, mapping.lifetime_seconds,
});
// Add the mapped address to observed addresses
p2p.addUpnpAddress(mapping.external_ip, mapping.external_port);
return mapping.external_ip;
}
/// Add an address discovered via UPnP IGD
fn addUpnpAddress(p2p: *P2P, ip: [4]u8, port: u16) void {
var addr_bytes: [18]u8 = [_]u8{0} ** 18;
addr_bytes[0] = ip[0];
addr_bytes[1] = ip[1];
addr_bytes[2] = ip[2];
addr_bytes[3] = ip[3];
std.mem.writeInt(u16, addr_bytes[4..6], port, .big);
p2p.addObservedAddress(addr_bytes, 6, UPNP_OBSERVER_ID);
}
/// Add an address discovered via NAT-PMP
fn addNatPmpAddress(p2p: *P2P, ip: [4]u8, port: u16) void {
// Encode as DHT address format: 4 bytes IP + 2 bytes port (big-endian)
var addr_bytes: [18]u8 = [_]u8{0} ** 18;
addr_bytes[0] = ip[0];
addr_bytes[1] = ip[1];
addr_bytes[2] = ip[2];
addr_bytes[3] = ip[3];
std.mem.writeInt(u16, addr_bytes[4..6], port, .big);
p2p.addObservedAddress(addr_bytes, 6, NAT_PMP_OBSERVER_ID);
}
/// Get the best observed public address (most recent, public, from multiple observers)
pub fn getObservedPublicAddress(p2p: *P2P) ?ObservedAddress {
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
// Find most recent public address
var best: ?ObservedAddress = null;
for (p2p.observed_addresses.items) |addr| {
if (!addr.isPublic()) continue;
if (best == null or addr.timestamp > best.?.timestamp) {
best = addr;
}
}
return best;
}
/// Get all observed addresses (for MWP to include in publications)
pub fn getAllObservedAddresses(p2p: *P2P, allocator: Allocator) ![]ObservedAddress {
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
return try allocator.dupe(ObservedAddress, p2p.observed_addresses.items);
}
/// Confidence level for observed address consensus
pub const AddressConfidence = enum {
/// No observers yet
none,
/// Single observer (trusted but unverified)
single_source,
/// Multiple observers agree
consensus,
/// Multiple observers disagree (using majority)
conflict,
};
/// Result of consensus address lookup
pub const ConsensusResult = struct {
address: ?ObservedAddress,
confidence: AddressConfidence,
/// Number of unique observers reporting this address
observer_count: u8,
/// Total number of unique observers
total_observers: u8,
};
/// Get the consensus observed address with confidence level
/// Returns the address that most unique observers agree on
pub fn getConsensusAddress(p2p: *P2P) ConsensusResult {
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
if (p2p.observed_addresses.items.len == 0) {
return .{
.address = null,
.confidence = .none,
.observer_count = 0,
.total_observers = 0,
};
}
// Count unique observers and group addresses
// Key: (ip_hash, port) -> count of unique observers
var address_votes: [10]struct {
addr: ObservedAddress,
observers: [10][32]u8,
observer_count: u8,
} = undefined;
var num_addresses: usize = 0;
var total_unique_observers: u8 = 0;
var seen_observers: [10][32]u8 = undefined;
var num_seen_observers: usize = 0;
for (p2p.observed_addresses.items) |observed| {
// Track unique observers
var observer_seen = false;
for (seen_observers[0..num_seen_observers]) |seen| {
if (std.mem.eql(u8, &seen, &observed.observer_id)) {
observer_seen = true;
break;
}
}
if (!observer_seen and num_seen_observers < 10) {
seen_observers[num_seen_observers] = observed.observer_id;
num_seen_observers += 1;
total_unique_observers += 1;
}
// Find or create address entry
var found_idx: ?usize = null;
for (address_votes[0..num_addresses], 0..) |*entry, idx| {
if (addressesEqual(entry.addr, observed)) {
found_idx = idx;
break;
}
}
if (found_idx) |idx| {
// Check if this observer already voted for this address
var already_voted = false;
for (address_votes[idx].observers[0..address_votes[idx].observer_count]) |obs| {
if (std.mem.eql(u8, &obs, &observed.observer_id)) {
already_voted = true;
break;
}
}
if (!already_voted and address_votes[idx].observer_count < 10) {
address_votes[idx].observers[address_votes[idx].observer_count] = observed.observer_id;
address_votes[idx].observer_count += 1;
// Update to most recent timestamp
if (observed.timestamp > address_votes[idx].addr.timestamp) {
address_votes[idx].addr = observed;
}
}
} else if (num_addresses < 10) {
// New address
address_votes[num_addresses] = .{
.addr = observed,
.observers = undefined,
.observer_count = 1,
};
address_votes[num_addresses].observers[0] = observed.observer_id;
num_addresses += 1;
}
}
if (num_addresses == 0) {
return .{
.address = null,
.confidence = .none,
.observer_count = 0,
.total_observers = total_unique_observers,
};
}
// Find address with most votes
var best_idx: usize = 0;
var best_count: u8 = address_votes[0].observer_count;
for (address_votes[1..num_addresses], 1..) |entry, idx| {
if (entry.observer_count > best_count) {
best_count = entry.observer_count;
best_idx = idx;
}
}
const confidence: AddressConfidence = if (total_unique_observers == 1)
.single_source
else if (best_count == total_unique_observers)
.consensus
else
.conflict;
if (confidence == .consensus and total_unique_observers >= 2) {
std.log.info("IP Reflection: Consensus reached! {} observers agree on address", .{total_unique_observers});
} else if (confidence == .conflict) {
std.log.warn("IP Reflection: Conflict detected - {}/{} observers agree (using majority)", .{ best_count, total_unique_observers });
}
return .{
.address = address_votes[best_idx].addr,
.confidence = confidence,
.observer_count = best_count,
.total_observers = total_unique_observers,
};
}
/// Helper: Compare two observed addresses (ignoring timestamp and observer)
fn addressesEqual(a: ObservedAddress, b: ObservedAddress) bool {
if (a.port != b.port) return false;
return switch (a.ip) {
.v4 => |ip_a| switch (b.ip) {
.v4 => |ip_b| std.mem.eql(u8, &ip_a, &ip_b),
.v6 => false,
},
.v6 => |ip_a| switch (b.ip) {
.v6 => |ip_b| std.mem.eql(u8, &ip_a, &ip_b),
.v4 => false,
},
};
}
// =========================================================================
// Small inline methods (just access fields)
// =========================================================================
/// Check if Noise protocol encryption is enabled
pub fn isNoiseEnabled(p2p: *const P2P) bool {
return p2p.noise_enabled;
}
/// Get the Noise protocol public key (X25519)
pub fn getNoisePublicKey(p2p: *const P2P) ?[32]u8 {
if (p2p.noise_keypair) |kp| {
return kp.public;
}
return null;
}
/// Get the local PeerId derived from the Noise public key.
pub fn getLocalPeerId(p2p: *const P2P) ?PeerId {
if (p2p.noise_keypair) |kp| {
return PeerId.fromNoisePublicKey(kp.public);
}
return null;
}
/// Verify that a remote peer's ID matches their Noise public key.
pub fn verifyPeerIdentity(peer_id: PeerId, noise_public_key: [32]u8) bool {
return peer_id.verifyPublicKey(noise_public_key);
}
// =========================================================================
// Key Pinning API (kept inline - small methods)
// =========================================================================
/// Manually pin a peer's public key.
pub fn pinPeerKey(p2p: *P2P, peer_id: PeerId, public_key: [32]u8, label: ?[]const u8) Error!void {
if (p2p.key_pin_store) |kps| {
kps.pinKey(peer_id.bytes, public_key, label) catch |err| {
return switch (err) {
network.key_pinning.Error.StorageFull => Error.SystemError,
network.key_pinning.Error.OutOfMemory => Error.OutOfMemory,
else => Error.SystemError,
};
};
std.log.info("Manually pinned key for peer: ", .{});
} else {
return Error.InvalidState;
}
}
/// Remove a pinned peer key.
pub fn unpinPeerKey(p2p: *P2P, peer_id: PeerId) bool {
if (p2p.key_pin_store) |kps| {
const removed = kps.unpinKey(peer_id.bytes);
if (removed) {
std.log.info("Unpinned key for peer: ", .{});
}
return removed;
}
return false;
}
/// Update a peer's key after confirming the key change is legitimate.
pub fn updatePeerKey(p2p: *P2P, peer_id: PeerId, new_public_key: [32]u8) Error!void {
if (p2p.key_pin_store) |kps| {
kps.updateKey(peer_id.bytes, new_public_key) catch |err| {
return switch (err) {
network.key_pinning.Error.UnknownPeer => Error.ConnectionNotFound,
else => Error.SystemError,
};
};
std.log.info("Updated pinned key for peer: ", .{});
} else {
return Error.InvalidState;
}
}
/// Check if a peer's key is pinned.
pub fn isPeerKeyPinned(p2p: *P2P, peer_id: PeerId) bool {
if (p2p.key_pin_store) |kps| {
return kps.isPeerKnown(peer_id.bytes);
}
return false;
}
/// Get information about a pinned peer.
pub fn getPinnedPeerInfo(p2p: *P2P, peer_id: PeerId) ?network.key_pinning.PinnedKey {
if (p2p.key_pin_store) |kps| {
return kps.getPinnedKey(peer_id.bytes);
}
return null;
}
/// Get the number of pinned peer keys.
pub fn getPinnedKeyCount(p2p: *P2P) usize {
if (p2p.key_pin_store) |kps| {
return kps.count();
}
return 0;
}
/// Get the current key pinning mode.
pub fn getKeyPinningMode(p2p: *const P2P) PinningMode {
return p2p.config.network.key_pinning_mode;
}
};
// ============================================================================
// Convenience Functions
// ============================================================================
/// Convenience function to create a default P2P instance
pub fn createDefault(allocator: Allocator) Error!P2P {
return P2P.init(allocator, P2PConfig.default());
}
/// Convenience function to create a high-performance P2P instance
pub fn createHighPerformance(allocator: Allocator) Error!P2P {
return P2P.init(allocator, P2PConfig.high_performance());
}
/// Convenience function to create a low-resource P2P instance
pub fn createLowResource(allocator: Allocator) Error!P2P {
return P2P.init(allocator, P2PConfig.low_resource());
}
// ============================================================================
// Tests
// ============================================================================
test "P2P library initialization" {
const allocator = std.testing.allocator;
var p2p = try P2P.init(allocator, P2PConfig.default());
defer p2p.deinit();
try std.testing.expectEqual(P2PState.Initialized, p2p.getState());
try std.testing.expect(p2p.isOperational() == false);
try std.testing.expectEqual(@as(usize, 1), p2p.getEventCount());
_ = p2p.processNextEvent();
try std.testing.expectEqual(@as(usize, 0), p2p.getEventCount());
}
test "P2P: getMemoryStats with tracking allocator" {
const allocator = std.testing.allocator;
var p2p = try P2P.initWithMemoryLimit(allocator, P2PConfig.default());
defer p2p.deinit();
const mem_stats = p2p.getMemoryStats();
try std.testing.expect(mem_stats != null);
try std.testing.expect(mem_stats.?.allocated_bytes >= 0);
}
test "P2P: getMemoryStats without tracking allocator" {
const allocator = std.testing.allocator;
var p2p = try P2P.initWithoutMemoryLimit(allocator, P2PConfig.default());
defer p2p.deinit();
const mem_stats = p2p.getMemoryStats();
try std.testing.expect(mem_stats == null);
}
test "P2P convenience functions" {
const allocator = std.testing.allocator;
var p2p1 = try createDefault(allocator);
defer p2p1.deinit();
try std.testing.expectEqual(P2PState.Initialized, p2p1.getState());
var p2p2 = try createHighPerformance(allocator);
defer p2p2.deinit();
try std.testing.expectEqual(P2PState.Initialized, p2p2.getState());
var p2p3 = try createLowResource(allocator);
defer p2p3.deinit();
try std.testing.expectEqual(P2PState.Initialized, p2p3.getState());
}
test "P2P: reference all decls" {
// This test ensures all public declarations are reachable
_ = P2P.init;
_ = P2P.initWithoutMemoryLimit;
_ = P2P.initWithMemoryLimit;
_ = P2P.initWithMemoryLimitCustom;
_ = P2P.getMemoryStats;
_ = P2P.deinit;
_ = P2P.start;
_ = P2P.stop;
_ = P2P.shutdown;
_ = P2P.enterMaintenanceMode;
_ = P2P.exitMaintenanceMode;
_ = P2P.setErrorState;
_ = P2P.recoverFromError;
_ = P2P.updateConfig;
_ = P2P.connectToPeer;
_ = P2P.disconnectPeer;
_ = P2P.acceptConnections;
_ = P2P.startListening;
_ = P2P.getPeerSocket;
_ = P2P.addPeerConnection;
_ = P2P.addPeerConnectionSecure;
_ = P2P.removePeerConnection;
_ = P2P.sendToPeerAtomic;
_ = P2P.sendSegmentsToPeerAtomic;
_ = P2P.drainPendingSends;
_ = P2P.addFile;
_ = P2P.addFileWithMetadata;
_ = P2P.downloadFile;
_ = P2P.startSharing;
_ = P2P.stopSharing;
_ = P2P.getFileMetadata;
_ = P2P.sendMessage;
_ = P2P.emitEvent;
_ = P2P.update;
_ = P2P.registerCallback;
_ = P2P.unregisterCallback;
_ = P2P.getEventCount;
_ = P2P.getNextEvent;
_ = P2P.processNextEvent;
_ = P2P.processAllEvents;
_ = P2P.getStats;
_ = P2P.isOperational;
_ = P2P.getState;
_ = P2P.getDhtPeerCount;
_ = P2P.dhtStore;
_ = P2P.dhtFindValue;
_ = P2P.dhtFindNode;
_ = P2P.getDhtLocalId;
_ = P2P.registerDhtNodeId;
_ = P2P.dhtAddPeer;
_ = P2P.isNoiseEnabled;
_ = P2P.getNoisePublicKey;
_ = P2P.getLocalPeerId;
_ = P2P.verifyPeerIdentity;
_ = P2P.pinPeerKey;
_ = P2P.unpinPeerKey;
_ = P2P.updatePeerKey;
_ = P2P.isPeerKeyPinned;
_ = P2P.getPinnedPeerInfo;
_ = P2P.getPinnedKeyCount;
_ = P2P.getKeyPinningMode;
_ = createDefault;
_ = createHighPerformance;
_ = createLowResource;
_ = registerNodeIdCallback;
_ = handleDataResponseCallback;
}