fips_core/node/mod.rs
1//! FIPS Node Entity
2//!
3//! Top-level structure representing a running FIPS instance. The Node
4//! holds all state required for mesh routing: identity, tree state,
5//! Bloom filters, coordinate caches, transports, links, and peers.
6
7mod accessors_impl;
8mod acl;
9mod bloom;
10mod core_impl;
11mod decrypt_worker;
12mod discovery_rate_limit;
13mod encrypt_worker;
14mod endpoint_event;
15mod endpoint_traffic;
16mod error;
17mod handlers;
18mod identity_cache;
19mod io_impl;
20mod lifecycle;
21mod link_registry;
22mod peer_lifecycle;
23mod peer_runtime;
24mod rate_limit;
25mod recent_requests;
26mod retry;
27mod route_impl;
28mod routing;
29mod routing_error_rate_limit;
30mod send_impl;
31pub(crate) mod session;
32mod session_access_impl;
33mod session_registry;
34pub(crate) mod session_wire;
35mod state;
36pub(crate) mod stats;
37pub(crate) mod stats_history;
38mod support_state;
39#[cfg(test)]
40mod tests;
41mod tree;
42pub(crate) mod wire;
43
44pub use endpoint_event::ExternalPacketIo;
45pub use endpoint_traffic::{
46 EndpointPayloadClass, EndpointPayloadLane, classify_endpoint_payload,
47 endpoint_payload_is_latency_sensitive,
48};
49pub use error::NodeError;
50pub use identity_cache::NodeDeliveredPacket;
51pub use state::NodeState;
52
53pub(crate) use endpoint_event::EndpointBulkSendFeedback;
54#[cfg(test)]
55pub(in crate::node) use endpoint_event::EndpointEventDequeueCounts;
56pub(in crate::node) use endpoint_event::EndpointEventRuntime;
57#[cfg(test)]
58pub(in crate::node) use endpoint_event::release_endpoint_event_messages;
59#[cfg(unix)]
60pub(in crate::node) use endpoint_event::{
61 EndpointBulkSendFeedbackRecord, EndpointBulkSendSessionBookkeeping,
62};
63#[cfg(unix)]
64pub(crate) use endpoint_event::{
65 EndpointBulkSendFmpLease, EndpointBulkSendFspLease, EndpointBulkSendLease,
66 EndpointBulkSendRuntime,
67};
68pub(crate) use endpoint_event::{
69 EndpointDataDelivery, EndpointDataIo, EndpointEventReceiver, EndpointEventSender,
70 EndpointSendBatchCommand, EndpointSendCommand, NodeEndpointCommand, NodeEndpointEvent,
71 NodeEndpointPeer, NodeEndpointRelayStatus, UpdatePeersOutcome, endpoint_data_command_capacity,
72};
73#[cfg(unix)]
74pub(in crate::node) use endpoint_traffic::reserve_fmp_worker_send;
75pub(crate) use endpoint_traffic::{
76 EndpointCommandLane, EndpointDataPayload, EndpointDataSend, PendingSessionTrafficQueues,
77};
78#[cfg(test)]
79pub(crate) use endpoint_traffic::{PendingEndpointDataQueue, PendingTunPacketQueue};
80#[cfg(unix)]
81pub(in crate::node) use endpoint_traffic::{
82 classify_fmp_plaintext_traffic, endpoint_flow_dispatch_key,
83};
84#[cfg(test)]
85pub(in crate::node) use endpoint_traffic::{
86 endpoint_command_lane_for_payload, endpoint_payload_is_tcp,
87 fmp_plaintext_is_bulk_session_datagram,
88};
89pub(in crate::node) use identity_cache::IdentityCache;
90#[cfg(test)]
91pub(in crate::node) use link_registry::LinkAddressIndex;
92pub(in crate::node) use link_registry::{LinkRegistry, PendingConnect, TransportDropTracker};
93pub(in crate::node) use peer_lifecycle::*;
94pub(in crate::node) use peer_runtime::*;
95#[cfg(test)]
96pub(crate) use recent_requests::RecentRequest;
97pub(crate) use recent_requests::{RecentDiscoveryRequests, RecentResponseForward};
98pub(in crate::node) use session_registry::*;
99pub(in crate::node) use support_state::{
100 BootstrapTransports, DiscoveryFallbackTransit, LocalSendFailures, SessionDirectDegradation,
101};
102
103use self::decrypt_worker::DecryptSessionKey;
104use self::discovery_rate_limit::{DiscoveryBackoff, DiscoveryForwardRateLimiter};
105use self::rate_limit::HandshakeRateLimiter;
106use self::routing::{LearnedRouteTable, LearnedRouteTableSnapshot};
107use self::routing_error_rate_limit::RoutingErrorRateLimiter;
108#[cfg(unix)]
109use self::wire::ESTABLISHED_HEADER_SIZE;
110use self::wire::{
111 FLAG_CE, FLAG_KEY_EPOCH, FLAG_SP, build_encrypted, build_established_header,
112 prepend_inner_header,
113};
114use crate::bloom::{BloomFilter, BloomState};
115use crate::cache::CoordCache;
116use crate::config::{NostrDiscoveryPolicy, PeerConfig, RoutingMode};
117#[cfg(unix)]
118use crate::node::session::FspSendReservation;
119use crate::node::session::SessionEntry;
120use crate::node::session_wire::{FSP_PHASE_ESTABLISHED, FspCommonPrefix};
121use crate::peer::{ActivePeer, PeerConnection};
122#[cfg(any(target_os = "linux", target_os = "macos"))]
123use crate::transport::ethernet::EthernetTransport;
124use crate::transport::tcp::TcpTransport;
125use crate::transport::tor::TorTransport;
126use crate::transport::udp::UdpTransport;
127#[cfg(feature = "webrtc-transport")]
128use crate::transport::webrtc::WebRtcTransport;
129use crate::transport::{
130 ConnectionState, Link, LinkId, PacketRx, PacketTx, TransportAddr, TransportError,
131 TransportHandle, TransportId,
132};
133use crate::tree::TreeState;
134use crate::upper::hosts::HostMap;
135use crate::upper::icmp_rate_limit::IcmpRateLimiter;
136use crate::upper::tun::{TunError, TunOutboundRx, TunState, TunTx};
137use crate::utils::index::{IndexAllocator, SessionIndex};
138use crate::{
139 Config, ConfigError, FipsAddress, Identity, IdentityError, LinkMessageType, NodeAddr,
140 PeerIdentity, encode_npub,
141};
142use rand::Rng;
143use std::collections::{HashMap, HashSet, VecDeque};
144use std::fmt;
145use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
146use std::sync::{Arc, Condvar, Mutex as StdMutex};
147use std::thread::JoinHandle;
148use thiserror::Error;
149use tracing::{debug, warn};
150
151const LOCAL_SEND_FAILURE_FAST_DEAD_WINDOW: std::time::Duration = std::time::Duration::from_secs(3);
152pub(crate) const ENDPOINT_EVENT_PRIORITY_MAX_LEN: usize = 512;
153const SESSION_DIRECT_DEGRADED_HOLD_MS: u64 = 20_000;
154const SESSION_DIRECT_DEGRADED_MIN_SAMPLE: u64 = 16;
155const SESSION_DIRECT_DEGRADED_LOSS_THRESHOLD: f64 = 0.08;
156const SESSION_DIRECT_RECOVERY_LOSS_THRESHOLD: f64 = 0.02;
157const ROUTING_FALLBACK_MIN_COST_ADVANTAGE: f64 = 0.25;
158const ENDPOINT_EVENT_BACKLOG_HIGH_WATER: usize = 4096;
159
160/// Half-range of the symmetric jitter applied to per-session rekey timers.
161///
162/// Each FMP/FSP session draws an offset uniformly from
163/// `[-REKEY_JITTER_SECS, +REKEY_JITTER_SECS]` seconds at construction and
164/// after each cutover. This preserves the configured mean interval while
165/// reducing dual-initiation bursts in symmetric-start meshes.
166pub(crate) const REKEY_JITTER_SECS: i64 = 15;
167
168/// A running FIPS node instance.
169///
170/// This is the top-level container holding all node state.
171///
172/// ## Peer Lifecycle
173///
174/// Peers go through two phases:
175/// 1. **Connection phase** (`connections`): Handshake in progress, indexed by LinkId
176/// 2. **Active phase** (`peers`): Authenticated, indexed by NodeAddr
177///
178/// The link registry dispatches incoming packets to the right connection before
179/// authentication completes.
180// Discovery lookup constants moved to config: node.discovery.attempt_timeouts_secs, node.discovery.ttl
181pub struct Node {
182 // === Identity ===
183 /// This node's cryptographic identity.
184 identity: Identity,
185
186 /// Random epoch generated at startup for peer restart detection.
187 /// Exchanged inside Noise handshake messages so peers can detect restarts.
188 startup_epoch: [u8; 8],
189
190 /// Instant when the node was created, for uptime reporting.
191 started_at: std::time::Instant,
192
193 // === Configuration ===
194 /// Loaded configuration.
195 config: Config,
196
197 // === State ===
198 /// Node operational state.
199 state: NodeState,
200
201 /// Whether this is a leaf-only node.
202 is_leaf_only: bool,
203
204 // === Spanning Tree ===
205 /// Local spanning tree state.
206 tree_state: TreeState,
207
208 // === Bloom Filter ===
209 /// Local Bloom filter state.
210 bloom_state: BloomState,
211
212 // === Routing ===
213 /// Address -> coordinates cache (from session setup and discovery).
214 coord_cache: CoordCache,
215 /// Locally learned reverse-path next-hop hints.
216 learned_routes: LearnedRouteTable,
217 /// Destinations whose direct first-hop path is temporarily suspect because
218 /// session-layer MMP observed sustained loss while using that direct path.
219 session_direct_degradation: SessionDirectDegradation,
220 /// Recent discovery requests for dedup and reverse-path forwarding.
221 recent_requests: RecentDiscoveryRequests,
222 /// Per-destination path MTU lookup, keyed by FipsAddress (mirrors
223 /// `coord_cache.entries[*].path_mtu`). Sync read-only access from
224 /// the TUN reader/writer threads at TCP MSS clamp time so the
225 /// SYN/SYN-ACK clamp can use the smaller of the local-egress floor
226 /// and the learned per-destination path MTU.
227 path_mtu_lookup: Arc<std::sync::RwLock<HashMap<crate::FipsAddress, u16>>>,
228
229 // === Transports & Links ===
230 /// Active transports (owned by Node).
231 transports: HashMap<TransportId, TransportHandle>,
232 /// Per-transport kernel drop tracking for congestion detection.
233 transport_drops: TransportDropTracker,
234 /// Per-transport wildcard socket-local drop tracking for observability.
235 transport_socket_drops: TransportDropTracker,
236 /// Per-transport Linux namespace receive-buffer error tracking for observability.
237 transport_namespace_drops: TransportDropTracker,
238 /// Active links plus reverse address dispatch index.
239 links: LinkRegistry,
240
241 // === Packet Channel ===
242 /// Packet sender for transports.
243 packet_tx: Option<PacketTx>,
244 /// Packet receiver (for event loop).
245 packet_rx: Option<PacketRx>,
246
247 // === Peer Lifecycle ===
248 /// Pending handshake connections plus authenticated peers.
249 peers: PeerLifecycleRegistry,
250
251 // === End-to-End Sessions ===
252 /// Session table for end-to-end encrypted sessions.
253 /// Keyed by remote NodeAddr.
254 sessions: SessionRegistry,
255
256 // === Identity Cache ===
257 /// Maps FipsAddress prefix bytes (bytes 1-15) to cached peer identity data.
258 /// Enables reverse lookup from IPv6 destination to session/routing identity.
259 identity_cache: IdentityCache,
260
261 // === Pending TUN Packets ===
262 /// TUN packets and endpoint payloads queued while waiting for session establishment.
263 pending_session_traffic: PendingSessionTrafficQueues,
264 // === Pending Discovery Lookups ===
265 /// Tracks in-flight discovery lookups and owns dedupe/cap admission.
266 pending_lookups: handlers::discovery::PendingDiscoveryLookups,
267
268 // === Resource Limits ===
269 /// Maximum connections (0 = unlimited).
270 max_connections: usize,
271 /// Maximum peers (0 = unlimited).
272 max_peers: usize,
273 /// Maximum links (0 = unlimited).
274 max_links: usize,
275
276 // === Counters ===
277 /// Next link ID to allocate.
278 next_link_id: u64,
279 /// Next transport ID to allocate.
280 next_transport_id: u32,
281
282 // === Node Statistics ===
283 /// Routing, forwarding, discovery, and error signal counters.
284 stats: stats::NodeStats,
285
286 /// Time-series history of node-level metrics (1s/1m rings).
287 stats_history: stats_history::StatsHistory,
288
289 // === TUN Interface ===
290 /// TUN device state.
291 tun_state: TunState,
292 /// TUN interface name (for cleanup).
293 tun_name: Option<String>,
294 /// TUN packet sender channel.
295 tun_tx: Option<TunTx>,
296 /// Receiver for outbound packets from the TUN reader.
297 tun_outbound_rx: Option<TunOutboundRx>,
298 /// App-owned packet sink used by embedded/no-TUN integrations.
299 external_packet_tx: Option<tokio::sync::mpsc::Sender<NodeDeliveredPacket>>,
300 /// Endpoint data command receiver used by embedded/no-daemon integrations.
301 endpoint_priority_command_rx: Option<tokio::sync::mpsc::Receiver<NodeEndpointCommand>>,
302 /// Bulk endpoint data command receiver used by embedded/no-daemon integrations.
303 endpoint_command_rx: Option<tokio::sync::mpsc::Receiver<NodeEndpointCommand>>,
304 /// Endpoint data event delivery runtime used by embedded/no-daemon integrations.
305 endpoint_events: EndpointEventRuntime,
306 /// Priority feedback from endpoint-side bulk-send leases. The endpoint
307 /// mover must report FMP/FSP send bookkeeping before it dispatches worker
308 /// jobs; rx_loop applies this lane ahead of bulk endpoint commands so
309 /// MMP/liveness/accounting do not starve behind bulk traffic.
310 endpoint_bulk_feedback_rx: Option<tokio::sync::mpsc::Receiver<EndpointBulkSendFeedback>>,
311 /// Shared lease publisher for endpoint-side bulk sends.
312 #[cfg(unix)]
313 endpoint_bulk_send_runtime: Option<EndpointBulkSendRuntime>,
314 /// Off-task FMP-encrypt + UDP-send worker pool. `None` if not yet
315 /// spawned (set up in `start()` once transports are running).
316 /// `Some(pool)` once available; the pool internally holds
317 /// per-worker mpsc senders and round-robins jobs across them.
318 /// See `node::encrypt_worker` for the rationale and layout.
319 encrypt_workers: Option<encrypt_worker::EncryptWorkerPool>,
320 /// Off-task FMP + FSP decrypt + delivery worker pool. Mirror of
321 /// `encrypt_workers` for the receive side.
322 decrypt_workers: Option<decrypt_worker::DecryptWorkerPool>,
323 /// Decrypt-worker return channel. Compact authenticated receive metadata,
324 /// direct local FSP completions, and fallback plaintext all return here so
325 /// rx_loop can apply node-owned bookkeeping and any remaining legacy link
326 /// dispatch. Drained with a bounded priority lane ahead of bounded
327 /// authenticated and fallback bulk lanes.
328 decrypt_fallback_rx: Option<decrypt_worker::DecryptWorkerFallbackReceivers>,
329 decrypt_fallback_tx: decrypt_worker::DecryptWorkerFallbackSender,
330 /// TUN reader thread handle.
331 tun_reader_handle: Option<JoinHandle<()>>,
332 /// TUN writer thread handle.
333 tun_writer_handle: Option<JoinHandle<()>>,
334 /// Shutdown pipe: writing to this fd unblocks the TUN reader thread on macOS.
335 /// On Linux, deleting the interface via netlink serves the same purpose.
336 #[cfg(target_os = "macos")]
337 tun_shutdown_fd: Option<std::os::unix::io::RawFd>,
338
339 // === DNS Responder ===
340 /// Receiver for resolved identities from the DNS responder.
341 dns_identity_rx: Option<crate::upper::dns::DnsIdentityRx>,
342 /// DNS responder task handle.
343 dns_task: Option<tokio::task::JoinHandle<()>>,
344
345 // === Index-Based Session Dispatch ===
346 /// Allocator for session indices.
347 index_allocator: IndexAllocator,
348 /// Pending outbound handshakes by our sender_idx.
349 /// Tracks which LinkId corresponds to which session index.
350 pending_outbound: PendingOutboundHandshakes,
351
352 // === Rate Limiting ===
353 /// Rate limiter for msg1 processing (DoS protection).
354 msg1_rate_limiter: HandshakeRateLimiter,
355 /// Rate limiter for ICMP Packet Too Big messages.
356 icmp_rate_limiter: IcmpRateLimiter,
357 /// Rate limiter for routing error signals (CoordsRequired / PathBroken).
358 routing_error_rate_limiter: RoutingErrorRateLimiter,
359 /// Rate limiter for source-side CoordsRequired/PathBroken responses.
360 coords_response_rate_limiter: RoutingErrorRateLimiter,
361 /// Backoff for failed discovery lookups (originator-side).
362 discovery_backoff: DiscoveryBackoff,
363 /// Rate limiter for forwarded discovery requests (transit-side).
364 discovery_forward_limiter: DiscoveryForwardRateLimiter,
365
366 // === Pending Transport Connects ===
367 /// Links waiting for transport-level connection establishment before
368 /// sending handshake msg1. For connection-oriented transports (TCP, Tor),
369 /// the transport connect runs in the background; the tick handler polls
370 /// connection_state() and initiates the handshake when connected.
371 pending_connects: Vec<PendingConnect>,
372
373 // === Connection Retry ===
374 /// Retry state for peers whose outbound connections have failed.
375 /// Keyed by NodeAddr. Entries are created when a handshake times out
376 /// or fails, and removed on successful promotion or when max retries
377 /// are exhausted.
378 retry_pending: retry::PendingRouteRetries,
379
380 /// Optional Nostr/STUN overlay discovery coordinator for `udp:nat` peers.
381 nostr_discovery: Option<Arc<crate::discovery::nostr::NostrDiscovery>>,
382 /// mDNS / DNS-SD responder + browser for local-link peer discovery.
383 /// Identity is unverified at this layer — the Noise XX handshake
384 /// initiated against an mDNS-observed endpoint is what proves the
385 /// peer holds the matching private key.
386 lan_discovery: Option<Arc<crate::discovery::lan::LanDiscovery>>,
387 /// Same-host JSON registry under `~/.fips/instances`. Records are
388 /// loopback routing hints only; peer identity is still verified by the
389 /// Noise handshake.
390 local_instance_registry: Option<crate::discovery::local::LocalInstanceRegistry>,
391 local_instance_started_at_ms: Option<u64>,
392 last_local_instance_publish_ms: Option<u64>,
393 last_local_instance_scan_ms: Option<u64>,
394 /// Wall-clock ms when Nostr discovery successfully started, used to
395 /// schedule the one-shot startup advert sweep after a settle delay.
396 /// `None` until discovery comes up; remains `None` if discovery is
397 /// disabled or failed to start.
398 nostr_discovery_started_at_ms: Option<u64>,
399 /// Whether the one-shot startup advert sweep has run. Set to true
400 /// after the first sweep fires (under `policy: open`); thereafter
401 /// only the per-tick `queue_open_discovery_retries` continues.
402 startup_open_discovery_sweep_done: bool,
403 /// Per-peer UDP transports adopted from NAT traversal handoff plus the
404 /// originating peer npub for protocol-mismatch cooldown bookkeeping.
405 bootstrap_transports: BootstrapTransports,
406 /// Peers that should not be used as reply-learned fallback transit for
407 /// other destinations. Direct lookups to the peer are still permitted.
408 discovery_fallback_transit: DiscoveryFallbackTransit,
409
410 // === Periodic Parent Re-evaluation ===
411 /// Timestamp of last periodic parent re-evaluation (for pacing).
412 last_parent_reeval: Option<crate::time::Instant>,
413
414 // === Congestion Logging ===
415 /// Timestamp of last congestion detection log (rate-limited to 5s).
416 last_congestion_log: Option<std::time::Instant>,
417
418 // === Mesh Size Estimate ===
419 /// Cached estimated mesh size (computed once per tick from bloom filters).
420 estimated_mesh_size: Option<u64>,
421 /// Timestamp of last mesh size log emission.
422 last_mesh_size_log: Option<std::time::Instant>,
423
424 // === Bloom Self-Plausibility ===
425 /// Rate-limit state for the self-plausibility WARN. Fires at most
426 /// once per 60s globally when our own outgoing FilterAnnounce has
427 /// an FPR above `node.bloom.max_inbound_fpr`, signalling either
428 /// aggregation drift or an ingress bypass.
429 last_self_warn: Option<std::time::Instant>,
430
431 // === Local Outbound Liveness ===
432 /// Set per peer when a `transport.send` returned a local-side io error
433 /// (`NetworkUnreachable` / `HostUnreachable` / `AddrNotAvailable`),
434 /// cleared on the next successful send to that peer. Used by
435 /// `check_link_heartbeats` to compress only that peer's dead-timeout to
436 /// `fast_link_dead_timeout_secs` while its outbound is observed broken.
437 local_send_failures: LocalSendFailures,
438 /// Set when the rx loop could not complete its 1s maintenance work
439 /// inside the watchdog timeout. Link-dead detection may be valid during
440 /// overload, but traversal cooldown should not punish a path just because
441 /// our own scheduler/worker queue was late.
442 last_rx_loop_maintenance_timeout_at: Option<std::time::Instant>,
443
444 // === Display Names ===
445 /// Human-readable names for configured peers (alias or short npub).
446 /// Populated at startup from peer config.
447 peer_aliases: HashMap<NodeAddr, String>,
448 /// Scheduler weight for explicitly configured peers. Built when config
449 /// changes so the packet hot path only does a NodeAddr hash lookup.
450 configured_peer_send_weights: ConfiguredPeerSendWeights,
451
452 /// Reloadable peer ACL state from standard allow/deny files.
453 peer_acl: acl::PeerAclReloader,
454
455 // === Host Map ===
456 /// Static hostname → npub mapping for DNS resolution.
457 /// Built at construction from peer aliases and /etc/fips/hosts.
458 host_map: Arc<HostMap>,
459}
460
461impl fmt::Debug for Node {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 f.debug_struct("Node")
464 .field("node_addr", self.node_addr())
465 .field("state", &self.state)
466 .field("is_leaf_only", &self.is_leaf_only)
467 .field("connections", &self.connection_count())
468 .field("peers", &self.peer_count())
469 .field("links", &self.link_count())
470 .field("transports", &self.transport_count())
471 .finish()
472 }
473}