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