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(feature = "host-ble-transport")]
95use crate::transport::ble::host::HostBleIo;
96#[cfg(any(target_os = "linux", target_os = "macos"))]
97use crate::transport::ethernet::EthernetTransport;
98use crate::transport::tcp::TcpTransport;
99use crate::transport::tor::TorTransport;
100use crate::transport::udp::UdpTransport;
101#[cfg(feature = "webrtc-transport")]
102use crate::transport::webrtc::WebRtcTransport;
103use crate::transport::websocket::WebSocketTransport;
104use crate::transport::{
105 Link, LinkId, PacketRx, PacketTx, TransportAddr, TransportError, TransportHandle, TransportId,
106};
107use crate::tree::TreeState;
108use crate::upper::hosts::HostMap;
109use crate::upper::icmp_rate_limit::IcmpRateLimiter;
110use crate::upper::tun::{TunError, TunOutboundRx, TunState, TunTx};
111use crate::utils::index::{IndexAllocator, SessionIndex};
112use crate::{
113 Config, ConfigError, FipsAddress, Identity, IdentityError, LinkMessageType, NodeAddr,
114 PeerIdentity, encode_npub,
115};
116use rand::Rng;
117use std::collections::{HashMap, HashSet, VecDeque};
118use std::fmt;
119use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
120use std::sync::{Arc, Mutex as StdMutex};
121use std::thread::JoinHandle;
122use thiserror::Error;
123use tracing::{debug, warn};
124
125type DataplaneNode = DataplaneLiveNode;
126
127const LOCAL_SEND_FAILURE_FAST_DEAD_WINDOW: std::time::Duration = std::time::Duration::from_secs(3);
128#[cfg(test)]
129pub(crate) const ENDPOINT_EVENT_TEST_PAYLOAD_LEN: usize = 512;
130const SESSION_DIRECT_DEGRADED_HOLD_MS: u64 = 20_000;
131const SESSION_DIRECT_DEGRADED_MIN_SAMPLE: u64 = 16;
132const SESSION_DIRECT_DEGRADED_LOSS_THRESHOLD: f64 = 0.08;
133const SESSION_DIRECT_RECOVERY_LOSS_THRESHOLD: f64 = 0.02;
134const SESSION_DIRECT_MIN_EXCLUSIVE_TRUST_MS: u64 = 6_500;
135const ROUTING_FALLBACK_MIN_COST_ADVANTAGE: f64 = 0.25;
136const ENDPOINT_EVENT_BACKLOG_HIGH_WATER: usize = 4096;
137
138/// Half-range of the symmetric jitter applied to per-session rekey timers.
139///
140/// Each FMP/FSP session draws an offset uniformly from
141/// `[-REKEY_JITTER_SECS, +REKEY_JITTER_SECS]` seconds at construction and
142/// after each cutover. This preserves the configured mean interval while
143/// reducing dual-initiation bursts in symmetric-start meshes.
144pub(crate) const REKEY_JITTER_SECS: i64 = 15;
145
146/// A running FIPS node instance.
147///
148/// This is the top-level container holding all node state.
149///
150/// ## Peer Lifecycle
151///
152/// Peers go through two phases:
153/// 1. **Connection phase** (`connections`): Handshake in progress, indexed by LinkId
154/// 2. **Active phase** (`peers`): Authenticated, indexed by NodeAddr
155///
156/// The link registry dispatches incoming packets to the right connection before
157/// authentication completes.
158// Discovery lookup constants moved to config: node.discovery.attempt_timeouts_secs, node.discovery.ttl
159pub struct Node {
160 // === Identity ===
161 /// This node's cryptographic identity.
162 identity: Identity,
163
164 /// Random epoch generated at startup for peer restart detection.
165 /// Exchanged inside Noise handshake messages so peers can detect restarts.
166 startup_epoch: [u8; 8],
167
168 /// Instant when the node was created, for uptime reporting.
169 started_at: std::time::Instant,
170
171 // === Configuration ===
172 /// Loaded configuration.
173 config: Config,
174
175 // === State ===
176 /// Node operational state.
177 state: NodeState,
178
179 /// Whether this is a leaf-only node.
180 is_leaf_only: bool,
181
182 // === Spanning Tree ===
183 /// Local spanning tree state.
184 tree_state: TreeState,
185
186 // === Bloom Filter ===
187 /// Local Bloom filter state.
188 bloom_state: BloomState,
189
190 // === Routing ===
191 /// Address -> coordinates cache (from session setup and discovery).
192 coord_cache: CoordCache,
193 /// Locally learned reverse-path next-hop hints.
194 learned_routes: LearnedRouteTable,
195 /// Destinations whose direct first-hop path is temporarily suspect because
196 /// session-layer MMP observed sustained loss while using that direct path.
197 session_direct_degradation: SessionDirectDegradation,
198 /// Recent discovery requests for dedup and reverse-path forwarding.
199 recent_requests: RecentDiscoveryRequests,
200 /// Per-destination path MTU lookup, keyed by FipsAddress (mirrors
201 /// `coord_cache.entries[*].path_mtu`). Sync read-only access from
202 /// the TUN reader/writer threads at TCP MSS clamp time so the
203 /// SYN/SYN-ACK clamp can use the smaller of the local-egress floor
204 /// and the learned per-destination path MTU.
205 path_mtu_lookup: Arc<std::sync::RwLock<HashMap<crate::FipsAddress, u16>>>,
206
207 // === Transports & Links ===
208 /// Active transports (owned by Node).
209 transports: HashMap<TransportId, TransportHandle>,
210 /// Platform-command BLE transport supplied by an embedded host.
211 #[cfg(feature = "host-ble-transport")]
212 host_ble_io: Option<HostBleIo>,
213 /// Per-transport kernel drop tracking for congestion detection.
214 transport_drops: TransportDropTracker,
215 /// Per-transport wildcard socket-local drop tracking for observability.
216 transport_socket_drops: TransportDropTracker,
217 /// Per-transport Linux namespace receive-buffer error tracking for observability.
218 transport_namespace_drops: TransportDropTracker,
219 /// Active links plus reverse address dispatch index.
220 links: LinkRegistry,
221
222 // === Packet Channel ===
223 /// Packet sender for transports.
224 packet_tx: Option<PacketTx>,
225 /// Packet receiver (for event loop).
226 packet_rx: Option<PacketRx>,
227
228 // === Dataplane ===
229 /// Canonical dataplane state owned by the node.
230 dataplane: DataplaneNode,
231 /// Control ingress surfaced while a synchronous dataplane send is waiting.
232 deferred_dataplane_control_turns: VecDeque<DataplaneLiveNodeTurn>,
233 /// Transit sends admitted to dataplane whose terminal receipts may arrive
234 /// on a later receive-loop turn.
235 deferred_session_forwards: handlers::forwarding::DeferredSessionForwards,
236 /// Pre-routed established FMP packets accepted directly from UDP receive.
237 dataplane_fast_ingress_rx: Option<DataplaneFastIngressRx>,
238 /// Direct-FSP transport-address classifier published to packet ingress.
239 dataplane_direct_fsp_sources: DataplaneDirectFspSources,
240 /// True when peer path state changed since the classifier was built.
241 dataplane_direct_fsp_sources_dirty: bool,
242 /// Maximum same-destination UDP payloads sent in one dataplane batch.
243 dataplane_transport_send_batch_packets: usize,
244
245 // === Peer Lifecycle ===
246 /// Pending handshake connections plus authenticated peers.
247 peers: PeerLifecycleRegistry,
248
249 // === End-to-End Sessions ===
250 /// Session table for end-to-end encrypted sessions.
251 /// Keyed by remote NodeAddr.
252 sessions: SessionRegistry,
253
254 // === Identity Cache ===
255 /// Maps FipsAddress prefix bytes (bytes 1-15) to cached peer identity data.
256 /// Enables reverse lookup from IPv6 destination to session/routing identity.
257 identity_cache: IdentityCache,
258
259 // === Pending TUN Packets ===
260 /// TUN packets and endpoint payloads queued while waiting for session establishment.
261 pending_session_traffic: PendingSessionTrafficQueues,
262 // === Pending Discovery Lookups ===
263 /// Tracks in-flight discovery lookups and owns dedupe/cap admission.
264 pending_lookups: handlers::discovery::PendingDiscoveryLookups,
265
266 // === Resource Limits ===
267 /// Maximum connections (0 = unlimited).
268 max_connections: usize,
269 /// Maximum peers (0 = unlimited).
270 max_peers: usize,
271 /// Maximum links (0 = unlimited).
272 max_links: usize,
273
274 // === Counters ===
275 /// Next link ID to allocate.
276 next_link_id: u64,
277 /// Next transport ID to allocate.
278 next_transport_id: u32,
279
280 // === Node Statistics ===
281 /// Routing, forwarding, discovery, and error signal counters.
282 stats: stats::NodeStats,
283
284 /// Time-series history of node-level metrics (1s/1m rings).
285 stats_history: stats_history::StatsHistory,
286
287 // === TUN Interface ===
288 /// TUN device state.
289 tun_state: TunState,
290 /// TUN interface name (for cleanup).
291 tun_name: Option<String>,
292 /// TUN packet sender channel.
293 tun_tx: Option<TunTx>,
294 /// Receiver for outbound packets from the TUN reader.
295 tun_outbound_rx: Option<TunOutboundRx>,
296 /// App-owned packet sink used by embedded/no-TUN integrations.
297 external_packet_tx: Option<tokio::sync::mpsc::Sender<NodeDeliveredPacket>>,
298 /// Endpoint control receiver used by embedded/no-daemon integrations.
299 endpoint_control_rx: Option<tokio::sync::mpsc::Receiver<NodeEndpointControlCommand>>,
300 /// Endpoint data batch receiver used by embedded/no-daemon integrations.
301 endpoint_data_rx: Option<EndpointDataBatchRx>,
302 /// Endpoint data event delivery runtime used by embedded/no-daemon integrations.
303 endpoint_events: EndpointEventRuntime,
304 /// Registered FSP DataPacket services and their app delivery queue.
305 endpoint_services: EndpointServiceRuntime,
306 /// TUN reader thread handle.
307 tun_reader_handle: Option<JoinHandle<()>>,
308 /// TUN writer thread handle.
309 tun_writer_handle: Option<JoinHandle<()>>,
310 /// Shutdown pipe: writing to this fd unblocks the TUN reader thread on macOS.
311 /// On Linux, deleting the interface via netlink serves the same purpose.
312 #[cfg(target_os = "macos")]
313 tun_shutdown_fd: Option<std::os::unix::io::RawFd>,
314
315 // === DNS Responder ===
316 /// Receiver for resolved identities from the DNS responder.
317 dns_identity_rx: Option<crate::upper::dns::DnsIdentityRx>,
318 /// DNS responder task handle.
319 dns_task: Option<tokio::task::JoinHandle<()>>,
320
321 // === Index-Based Session Dispatch ===
322 /// Allocator for session indices.
323 index_allocator: IndexAllocator,
324 /// Pending outbound handshakes by our sender_idx.
325 /// Tracks which LinkId corresponds to which session index.
326 pending_outbound: PendingOutboundHandshakes,
327
328 // === Rate Limiting ===
329 /// Rate limiter for msg1 processing (DoS protection).
330 msg1_rate_limiter: HandshakeRateLimiter,
331 /// Rate limiter for ICMP Packet Too Big messages.
332 icmp_rate_limiter: IcmpRateLimiter,
333 /// Rate limiter for routing error signals (CoordsRequired / PathBroken).
334 routing_error_rate_limiter: RoutingErrorRateLimiter,
335 /// Rate limiter for source-side CoordsRequired/PathBroken responses.
336 coords_response_rate_limiter: RoutingErrorRateLimiter,
337 /// Backoff for failed discovery lookups (originator-side).
338 discovery_backoff: DiscoveryBackoff,
339 /// Rate limiter for forwarded discovery requests (transit-side).
340 discovery_forward_limiter: DiscoveryForwardRateLimiter,
341
342 // === Pending Transport Connects ===
343 /// Links waiting for transport-level connection establishment before
344 /// sending handshake msg1. For connection-oriented transports (TCP, Tor),
345 /// the transport connect runs in the background; the tick handler polls
346 /// connection_state() and initiates the handshake when connected.
347 pending_connects: Vec<PendingConnect>,
348
349 // === Connection Retry ===
350 /// Retry state for peers whose outbound connections have failed.
351 /// Keyed by NodeAddr. Entries are created when a handshake times out
352 /// or fails, and removed on successful promotion or when max retries
353 /// are exhausted.
354 retry_pending: retry::PendingRouteRetries,
355
356 /// Optional Nostr/STUN overlay discovery coordinator for `udp:nat` peers.
357 nostr_discovery: Option<Arc<crate::discovery::nostr::NostrDiscovery>>,
358 /// Parsed traversal signals waiting for their end-to-end session. Keeping
359 /// them here avoids requeueing and reparsing npubs on every maintenance tick.
360 pending_mesh_signals: HashMap<NodeAddr, Vec<lifecycle::PendingMeshSignal>>,
361 /// mDNS / DNS-SD responder + browser for local-link peer discovery.
362 /// Identity is unverified at this layer — the Noise IK handshake
363 /// initiated against an mDNS-observed endpoint is what proves the
364 /// peer holds the matching private key.
365 lan_discovery: Option<Arc<crate::discovery::lan::LanDiscovery>>,
366 /// Host-global fixed-UDP rendezvous and authenticated capability roster.
367 /// It never changes application-owned outbound connectivity.
368 local_rendezvous: local_rendezvous::LocalRendezvous,
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 /// Configured-peer lookup cache, rebuilt when the peer roster changes.
424 configured_peers: ConfiguredPeerLookup,
425
426 /// Reloadable peer ACL state from standard allow/deny files.
427 peer_acl: acl::PeerAclReloader,
428
429 // === Host Map ===
430 /// Static hostname → npub mapping for DNS resolution.
431 /// Built at construction from peer aliases and /etc/fips/hosts.
432 host_map: Arc<HostMap>,
433}
434
435impl fmt::Debug for Node {
436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437 f.debug_struct("Node")
438 .field("node_addr", self.node_addr())
439 .field("state", &self.state)
440 .field("is_leaf_only", &self.is_leaf_only)
441 .field("connections", &self.connection_count())
442 .field("peers", &self.peer_count())
443 .field("links", &self.link_count())
444 .field("transports", &self.transport_count())
445 .finish()
446 }
447}