Skip to main content

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