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