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