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 acl;
8mod bloom;
9mod decrypt_worker;
10mod discovery_rate_limit;
11mod encrypt_worker;
12mod handlers;
13mod lifecycle;
14mod rate_limit;
15mod retry;
16mod routing;
17mod routing_error_rate_limit;
18pub(crate) mod session;
19pub(crate) mod session_wire;
20pub(crate) mod stats;
21pub(crate) mod stats_history;
22#[cfg(test)]
23mod tests;
24mod tree;
25pub(crate) mod wire;
26
27use self::discovery_rate_limit::{DiscoveryBackoff, DiscoveryForwardRateLimiter};
28use self::rate_limit::HandshakeRateLimiter;
29use self::routing::{LearnedRouteTable, LearnedRouteTableSnapshot};
30use self::routing_error_rate_limit::RoutingErrorRateLimiter;
31use self::wire::{
32    ESTABLISHED_HEADER_SIZE, FLAG_CE, FLAG_KEY_EPOCH, FLAG_SP, build_encrypted,
33    build_established_header, prepend_inner_header,
34};
35use crate::bloom::BloomState;
36use crate::cache::CoordCache;
37use crate::config::RoutingMode;
38use crate::node::session::SessionEntry;
39use crate::peer::{ActivePeer, PeerConnection};
40#[cfg(any(target_os = "linux", target_os = "macos"))]
41use crate::transport::ethernet::EthernetTransport;
42use crate::transport::tcp::TcpTransport;
43use crate::transport::tor::TorTransport;
44use crate::transport::udp::UdpTransport;
45#[cfg(feature = "webrtc-transport")]
46use crate::transport::webrtc::WebRtcTransport;
47use crate::transport::{
48    ConnectionState, Link, LinkId, PacketRx, PacketTx, TransportAddr, TransportError,
49    TransportHandle, TransportId,
50};
51use crate::tree::TreeState;
52use crate::upper::hosts::HostMap;
53use crate::upper::icmp_rate_limit::IcmpRateLimiter;
54use crate::upper::tun::{TunError, TunOutboundRx, TunState, TunTx};
55use crate::utils::index::IndexAllocator;
56use crate::{
57    Config, ConfigError, FipsAddress, Identity, IdentityError, NodeAddr, PeerIdentity,
58    SessionMessageType, encode_npub,
59};
60use rand::Rng;
61use std::collections::{HashMap, HashSet, VecDeque};
62use std::fmt;
63use std::sync::Arc;
64use std::thread::JoinHandle;
65use thiserror::Error;
66use tracing::{debug, warn};
67
68/// Half-range of the symmetric jitter applied to per-session rekey timers.
69///
70/// Each FMP/FSP session draws an offset uniformly from
71/// `[-REKEY_JITTER_SECS, +REKEY_JITTER_SECS]` seconds at construction and
72/// after each cutover. This preserves the configured mean interval while
73/// reducing dual-initiation bursts in symmetric-start meshes.
74pub(crate) const REKEY_JITTER_SECS: i64 = 15;
75
76/// Errors related to node operations.
77#[derive(Debug, Error)]
78pub enum NodeError {
79    #[error("node not started")]
80    NotStarted,
81
82    #[error("node already started")]
83    AlreadyStarted,
84
85    #[error("node already stopped")]
86    AlreadyStopped,
87
88    #[error("transport not found: {0}")]
89    TransportNotFound(TransportId),
90
91    #[error("no transport available for type: {0}")]
92    NoTransportForType(String),
93
94    #[error("link not found: {0}")]
95    LinkNotFound(LinkId),
96
97    #[error("connection not found: {0}")]
98    ConnectionNotFound(LinkId),
99
100    #[error("peer not found: {0:?}")]
101    PeerNotFound(NodeAddr),
102
103    #[error("peer already exists: {0:?}")]
104    PeerAlreadyExists(NodeAddr),
105
106    #[error("connection already exists for link: {0}")]
107    ConnectionAlreadyExists(LinkId),
108
109    #[error("invalid peer npub '{npub}': {reason}")]
110    InvalidPeerNpub { npub: String, reason: String },
111
112    #[error("discovery error: {0}")]
113    Discovery(String),
114
115    #[error("access denied: {0}")]
116    AccessDenied(String),
117
118    #[error("max connections exceeded: {max}")]
119    MaxConnectionsExceeded { max: usize },
120
121    #[error("max peers exceeded: {max}")]
122    MaxPeersExceeded { max: usize },
123
124    #[error("max links exceeded: {max}")]
125    MaxLinksExceeded { max: usize },
126
127    #[error("handshake incomplete for link {0}")]
128    HandshakeIncomplete(LinkId),
129
130    #[error("no session available for link {0}")]
131    NoSession(LinkId),
132
133    #[error("promotion failed for link {link_id}: {reason}")]
134    PromotionFailed { link_id: LinkId, reason: String },
135
136    #[error("send failed to {node_addr}: {reason}")]
137    SendFailed { node_addr: NodeAddr, reason: String },
138
139    #[error("mtu exceeded forwarding to {node_addr}: packet {packet_size} > mtu {mtu}")]
140    MtuExceeded {
141        node_addr: NodeAddr,
142        packet_size: usize,
143        mtu: u16,
144    },
145
146    #[error("config error: {0}")]
147    Config(#[from] ConfigError),
148
149    #[error("identity error: {0}")]
150    Identity(#[from] IdentityError),
151
152    #[error("TUN error: {0}")]
153    Tun(#[from] TunError),
154
155    #[error("index allocation failed: {0}")]
156    IndexAllocationFailed(String),
157
158    #[error("handshake failed: {0}")]
159    HandshakeFailed(String),
160
161    #[error("transport error: {0}")]
162    TransportError(String),
163
164    #[error("bootstrap handoff failed: {0}")]
165    BootstrapHandoff(String),
166}
167
168/// Source-attributed packet delivered by a node running without a system TUN.
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct NodeDeliveredPacket {
171    /// FIPS node address that originated the packet.
172    pub source_node_addr: NodeAddr,
173    /// Source Nostr public key when the node has learned it.
174    pub source_npub: Option<String>,
175    /// Destination FIPS address from the IPv6 packet.
176    pub destination: FipsAddress,
177    /// Full IPv6 packet after FIPS session decapsulation.
178    pub packet: Vec<u8>,
179}
180
181#[derive(Debug, Clone)]
182struct IdentityCacheEntry {
183    node_addr: NodeAddr,
184    pubkey: secp256k1::PublicKey,
185    npub: String,
186    last_seen_ms: u64,
187}
188
189impl IdentityCacheEntry {
190    fn new(
191        node_addr: NodeAddr,
192        pubkey: secp256k1::PublicKey,
193        npub: String,
194        last_seen_ms: u64,
195    ) -> Self {
196        Self {
197            node_addr,
198            pubkey,
199            npub,
200            last_seen_ms,
201        }
202    }
203}
204
205/// App-owned packet channels for embedding FIPS without a system TUN.
206#[derive(Debug)]
207pub struct ExternalPacketIo {
208    /// Send outbound IPv6 packets into the node.
209    pub outbound_tx: crate::upper::tun::TunOutboundTx,
210    /// Receive inbound IPv6 packets delivered by FIPS sessions.
211    pub inbound_rx: tokio::sync::mpsc::Receiver<NodeDeliveredPacket>,
212}
213
214/// App-owned endpoint data channels for embedding FIPS without a daemon.
215#[derive(Debug)]
216pub(crate) struct EndpointDataIo {
217    /// Send endpoint data commands into the node RX loop.
218    ///
219    /// Bounded with a generous default so normal sender bursts do not
220    /// stall on semaphore acquisition. macOS pacing happens at the UDP
221    /// egress thread where the real Wi-Fi/interface bottleneck is visible;
222    /// constraining this app queue instead caused the inner TCP flow to
223    /// collapse under iperf. `FIPS_ENDPOINT_DATA_QUEUE_CAP` overrides the
224    /// default for benches.
225    pub(crate) command_tx: tokio::sync::mpsc::Sender<NodeEndpointCommand>,
226    /// Receive endpoint data delivered by FIPS sessions.
227    ///
228    /// Unbounded so the rx_loop's send on inbound packet delivery is a
229    /// wait-free push (no semaphore acquire), and so we can drop the
230    /// per-packet cross-task relay that previously sat between the node
231    /// task and the `FipsEndpoint::recv()` consumer. Backpressure is
232    /// naturally bounded — the rx_loop both produces here and runs the
233    /// same runtime that schedules the consumer, so a stalled consumer
234    /// stalls production too.
235    pub(crate) event_rx: tokio::sync::mpsc::UnboundedReceiver<NodeEndpointEvent>,
236    /// Clone of the event_tx exposed for in-process loopback (e.g.
237    /// `FipsEndpoint::send` to self_npub). Lets the endpoint inject an
238    /// event into the same queue without going through the encrypt /
239    /// decrypt path, while keeping every consumer reading from a single
240    /// channel.
241    pub(crate) event_tx: tokio::sync::mpsc::UnboundedSender<NodeEndpointEvent>,
242}
243
244fn endpoint_data_command_capacity(requested: usize) -> usize {
245    if let Ok(raw) = std::env::var("FIPS_ENDPOINT_DATA_QUEUE_CAP")
246        && let Ok(value) = raw.trim().parse::<usize>()
247        && value > 0
248    {
249        return value;
250    }
251
252    requested.max(1).max(32_768)
253}
254
255/// Commands accepted by the node endpoint data service.
256#[derive(Debug)]
257pub(crate) enum NodeEndpointCommand {
258    /// Send with an explicit response channel — used by callers that
259    /// care whether the local-stack handoff succeeded (e.g.
260    /// `blocking_send` waits for the runtime to accept the send).
261    Send {
262        remote: PeerIdentity,
263        payload: Vec<u8>,
264        queued_at: Option<std::time::Instant>,
265        response_tx: tokio::sync::oneshot::Sender<Result<(), NodeError>>,
266    },
267    /// **Fire-and-forget** variant of `Send` — no oneshot allocation,
268    /// no per-packet result channel. Used by the data-plane fast path
269    /// (`FipsEndpoint::send`) where the caller already discards the
270    /// result. Saves one oneshot::channel() allocation per outbound
271    /// packet on the application's send hot path.
272    SendOneway {
273        remote: PeerIdentity,
274        payload: Vec<u8>,
275        queued_at: Option<std::time::Instant>,
276    },
277    PeerSnapshot {
278        response_tx: tokio::sync::oneshot::Sender<Vec<NodeEndpointPeer>>,
279    },
280    RelaySnapshot {
281        response_tx: tokio::sync::oneshot::Sender<Vec<NodeEndpointRelayStatus>>,
282    },
283    UpdateRelays {
284        advert_relays: Vec<String>,
285        dm_relays: Vec<String>,
286        response_tx: tokio::sync::oneshot::Sender<Result<(), NodeError>>,
287    },
288    /// Replace the runtime peer list. Newly added auto-connect peers get
289    /// `initiate_peer_connection` immediately; removed peers are dropped
290    /// from the retry queue (the regular liveness timeout reaps any active
291    /// session). Existing entries are kept and their `addresses` field is
292    /// refreshed so the next retry sees the latest hints.
293    UpdatePeers {
294        peers: Vec<crate::config::PeerConfig>,
295        response_tx: tokio::sync::oneshot::Sender<Result<UpdatePeersOutcome, NodeError>>,
296    },
297}
298
299/// Reports what changed in response to `UpdatePeers`.
300#[derive(Debug, Clone, Default, PartialEq, Eq)]
301pub(crate) struct UpdatePeersOutcome {
302    pub(crate) added: usize,
303    pub(crate) removed: usize,
304    pub(crate) updated: usize,
305    pub(crate) unchanged: usize,
306}
307
308/// Endpoint data events emitted by the node session receive path.
309#[derive(Debug)]
310pub(crate) enum NodeEndpointEvent {
311    Data {
312        source_node_addr: NodeAddr,
313        source_npub: Option<String>,
314        payload: Vec<u8>,
315        queued_at: Option<std::time::Instant>,
316    },
317}
318
319/// Authenticated peer state exposed to embedded endpoint callers.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub(crate) struct NodeEndpointPeer {
322    pub(crate) npub: String,
323    pub(crate) transport_addr: Option<String>,
324    pub(crate) transport_type: Option<String>,
325    pub(crate) link_id: u64,
326    pub(crate) srtt_ms: Option<u64>,
327    pub(crate) packets_sent: u64,
328    pub(crate) packets_recv: u64,
329    pub(crate) bytes_sent: u64,
330    pub(crate) bytes_recv: u64,
331}
332
333/// Live Nostr relay state exposed to embedded endpoint callers.
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub(crate) struct NodeEndpointRelayStatus {
336    pub(crate) url: String,
337    pub(crate) status: String,
338}
339
340/// Node operational state.
341#[derive(Clone, Copy, Debug, PartialEq, Eq)]
342pub enum NodeState {
343    /// Created but not started.
344    Created,
345    /// Starting up (initializing transports).
346    Starting,
347    /// Fully operational.
348    Running,
349    /// Shutting down.
350    Stopping,
351    /// Stopped.
352    Stopped,
353}
354
355impl NodeState {
356    /// Check if node is operational.
357    pub fn is_operational(&self) -> bool {
358        matches!(self, NodeState::Running)
359    }
360
361    /// Check if node can be started.
362    pub fn can_start(&self) -> bool {
363        matches!(self, NodeState::Created | NodeState::Stopped)
364    }
365
366    /// Check if node can be stopped.
367    pub fn can_stop(&self) -> bool {
368        matches!(self, NodeState::Running)
369    }
370}
371
372impl fmt::Display for NodeState {
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        let s = match self {
375            NodeState::Created => "created",
376            NodeState::Starting => "starting",
377            NodeState::Running => "running",
378            NodeState::Stopping => "stopping",
379            NodeState::Stopped => "stopped",
380        };
381        write!(f, "{}", s)
382    }
383}
384
385/// Recent request tracking for dedup and reverse-path forwarding.
386///
387/// When a LookupRequest is forwarded through a node, the node stores the
388/// request_id and which peer sent it. When the corresponding LookupResponse
389/// arrives, it's forwarded back to that peer (reverse-path forwarding).
390/// The `response_forwarded` flag prevents response routing loops.
391#[derive(Clone, Debug)]
392pub(crate) struct RecentRequest {
393    /// The peer who sent this request to us.
394    pub(crate) from_peer: NodeAddr,
395    /// When we received this request (Unix milliseconds).
396    pub(crate) timestamp_ms: u64,
397    /// Whether we've already forwarded a response for this request.
398    /// Prevents response routing loops when convergent request paths
399    /// create bidirectional entries in recent_requests.
400    pub(crate) response_forwarded: bool,
401}
402
403impl RecentRequest {
404    pub(crate) fn new(from_peer: NodeAddr, timestamp_ms: u64) -> Self {
405        Self {
406            from_peer,
407            timestamp_ms,
408            response_forwarded: false,
409        }
410    }
411
412    /// Check if this entry has expired (older than expiry_ms).
413    pub(crate) fn is_expired(&self, current_time_ms: u64, expiry_ms: u64) -> bool {
414        current_time_ms.saturating_sub(self.timestamp_ms) > expiry_ms
415    }
416}
417
418/// Key for addr_to_link reverse lookup.
419type AddrKey = (TransportId, TransportAddr);
420
421/// Per-transport kernel drop tracking for congestion detection.
422///
423/// Sampled every tick (1s). The `dropping` flag indicates whether new
424/// kernel drops were observed since the previous sample.
425#[derive(Debug, Default)]
426struct TransportDropState {
427    /// Previous `recv_drops` sample (cumulative counter).
428    prev_drops: u64,
429    /// True if drops increased since the last sample.
430    dropping: bool,
431}
432
433/// State for a link waiting for transport-level connection establishment.
434///
435/// For connection-oriented transports (TCP, Tor), the transport connect runs
436/// asynchronously. This struct holds the data needed to complete the handshake
437/// once the connection is ready.
438struct PendingConnect {
439    /// The link that was created for this connection.
440    link_id: LinkId,
441    /// Which transport is being used.
442    transport_id: TransportId,
443    /// The remote address being connected to.
444    remote_addr: TransportAddr,
445    /// The peer identity (for handshake initiation).
446    peer_identity: PeerIdentity,
447}
448
449/// A running FIPS node instance.
450///
451/// This is the top-level container holding all node state.
452///
453/// ## Peer Lifecycle
454///
455/// Peers go through two phases:
456/// 1. **Connection phase** (`connections`): Handshake in progress, indexed by LinkId
457/// 2. **Active phase** (`peers`): Authenticated, indexed by NodeAddr
458///
459/// The `addr_to_link` map enables dispatching incoming packets to the right
460/// connection before authentication completes.
461// Discovery lookup constants moved to config: node.discovery.attempt_timeouts_secs, node.discovery.ttl
462pub struct Node {
463    // === Identity ===
464    /// This node's cryptographic identity.
465    identity: Identity,
466
467    /// Random epoch generated at startup for peer restart detection.
468    /// Exchanged inside Noise handshake messages so peers can detect restarts.
469    startup_epoch: [u8; 8],
470
471    /// Instant when the node was created, for uptime reporting.
472    started_at: std::time::Instant,
473
474    // === Configuration ===
475    /// Loaded configuration.
476    config: Config,
477
478    // === State ===
479    /// Node operational state.
480    state: NodeState,
481
482    /// Whether this is a leaf-only node.
483    is_leaf_only: bool,
484
485    // === Spanning Tree ===
486    /// Local spanning tree state.
487    tree_state: TreeState,
488
489    // === Bloom Filter ===
490    /// Local Bloom filter state.
491    bloom_state: BloomState,
492
493    // === Routing ===
494    /// Address -> coordinates cache (from session setup and discovery).
495    coord_cache: CoordCache,
496    /// Locally learned reverse-path next-hop hints.
497    learned_routes: LearnedRouteTable,
498    /// Recent discovery requests (dedup + reverse-path forwarding).
499    /// Maps request_id → RecentRequest.
500    recent_requests: HashMap<u64, RecentRequest>,
501    /// Per-destination path MTU lookup, keyed by FipsAddress (mirrors
502    /// `coord_cache.entries[*].path_mtu`). Sync read-only access from
503    /// the TUN reader/writer threads at TCP MSS clamp time so the
504    /// SYN/SYN-ACK clamp can use the smaller of the local-egress floor
505    /// and the learned per-destination path MTU.
506    path_mtu_lookup: Arc<std::sync::RwLock<HashMap<crate::FipsAddress, u16>>>,
507
508    // === Transports & Links ===
509    /// Active transports (owned by Node).
510    transports: HashMap<TransportId, TransportHandle>,
511    /// Per-transport kernel drop tracking for congestion detection.
512    transport_drops: HashMap<TransportId, TransportDropState>,
513    /// Active links.
514    links: HashMap<LinkId, Link>,
515    /// Reverse lookup: (transport_id, remote_addr) -> link_id.
516    addr_to_link: HashMap<AddrKey, LinkId>,
517
518    // === Packet Channel ===
519    /// Packet sender for transports.
520    packet_tx: Option<PacketTx>,
521    /// Packet receiver (for event loop).
522    packet_rx: Option<PacketRx>,
523
524    // === Connections (Handshake Phase) ===
525    /// Pending connections (handshake in progress).
526    /// Indexed by LinkId since we don't know the peer's identity yet.
527    connections: HashMap<LinkId, PeerConnection>,
528
529    // === Peers (Active Phase) ===
530    /// Authenticated peers.
531    /// Indexed by NodeAddr (verified identity).
532    peers: HashMap<NodeAddr, ActivePeer>,
533
534    // === End-to-End Sessions ===
535    /// Session table for end-to-end encrypted sessions.
536    /// Keyed by remote NodeAddr.
537    sessions: HashMap<NodeAddr, SessionEntry>,
538
539    // === Identity Cache ===
540    /// Maps FipsAddress prefix bytes (bytes 1-15) to cached peer identity data.
541    /// Enables reverse lookup from IPv6 destination to session/routing identity.
542    identity_cache: HashMap<[u8; 15], IdentityCacheEntry>,
543
544    // === Pending TUN Packets ===
545    /// Packets queued while waiting for session establishment.
546    /// Keyed by destination NodeAddr, bounded per-dest and total.
547    pending_tun_packets: HashMap<NodeAddr, VecDeque<Vec<u8>>>,
548    /// Endpoint data payloads queued while waiting for session establishment.
549    pending_endpoint_data: HashMap<NodeAddr, VecDeque<Vec<u8>>>,
550    // === Pending Discovery Lookups ===
551    /// Tracks in-flight discovery lookups. Maps target NodeAddr to the
552    /// initiation timestamp (Unix ms). Prevents duplicate flood queries.
553    pending_lookups: HashMap<NodeAddr, handlers::discovery::PendingLookup>,
554
555    // === Resource Limits ===
556    /// Maximum connections (0 = unlimited).
557    max_connections: usize,
558    /// Maximum peers (0 = unlimited).
559    max_peers: usize,
560    /// Maximum links (0 = unlimited).
561    max_links: usize,
562
563    // === Counters ===
564    /// Next link ID to allocate.
565    next_link_id: u64,
566    /// Next transport ID to allocate.
567    next_transport_id: u32,
568
569    // === Node Statistics ===
570    /// Routing, forwarding, discovery, and error signal counters.
571    stats: stats::NodeStats,
572
573    /// Time-series history of node-level metrics (1s/1m rings).
574    stats_history: stats_history::StatsHistory,
575
576    // === TUN Interface ===
577    /// TUN device state.
578    tun_state: TunState,
579    /// TUN interface name (for cleanup).
580    tun_name: Option<String>,
581    /// TUN packet sender channel.
582    tun_tx: Option<TunTx>,
583    /// Receiver for outbound packets from the TUN reader.
584    tun_outbound_rx: Option<TunOutboundRx>,
585    /// App-owned packet sink used by embedded/no-TUN integrations.
586    external_packet_tx: Option<tokio::sync::mpsc::Sender<NodeDeliveredPacket>>,
587    /// Endpoint data command receiver used by embedded/no-daemon integrations.
588    endpoint_command_rx: Option<tokio::sync::mpsc::Receiver<NodeEndpointCommand>>,
589    /// Endpoint data event sink used by embedded/no-daemon integrations.
590    endpoint_event_tx: Option<tokio::sync::mpsc::UnboundedSender<NodeEndpointEvent>>,
591    /// Off-task FMP-encrypt + UDP-send worker pool. `None` if not yet
592    /// spawned (set up in `start()` once transports are running).
593    /// `Some(pool)` once available; the pool internally holds
594    /// per-worker mpsc senders and round-robins jobs across them.
595    /// See `node::encrypt_worker` for the rationale and layout.
596    encrypt_workers: Option<encrypt_worker::EncryptWorkerPool>,
597    /// Off-task FMP + FSP decrypt + delivery worker pool. Mirror of
598    /// `encrypt_workers` for the receive side.
599    decrypt_workers: Option<decrypt_worker::DecryptWorkerPool>,
600    /// Set of sessions that have been registered with the decrypt
601    /// shard worker pool. Used by rx_loop to decide between fast-path
602    /// dispatch (worker owns the session) and legacy in-place decrypt
603    /// (worker doesn't have it yet). Per the data-plane restructure,
604    /// the worker owns its session state directly — there's no shared
605    /// `Arc<RwLock<HashMap>>` of cipher / replay state anymore, only
606    /// this set tracks **whether** the worker has been told about a
607    /// given session.
608    decrypt_registered_sessions: std::collections::HashSet<(TransportId, u32)>,
609    /// Fallback channel: decrypt worker bounces non-fast-path packets
610    /// (anything that's not bulk EndpointData) back here for rx_loop
611    /// to handle via the legacy path. Drained by a new rx_loop arm.
612    decrypt_fallback_rx:
613        Option<tokio::sync::mpsc::UnboundedReceiver<decrypt_worker::DecryptWorkerEvent>>,
614    decrypt_fallback_tx: tokio::sync::mpsc::UnboundedSender<decrypt_worker::DecryptWorkerEvent>,
615    /// TUN reader thread handle.
616    tun_reader_handle: Option<JoinHandle<()>>,
617    /// TUN writer thread handle.
618    tun_writer_handle: Option<JoinHandle<()>>,
619    /// Shutdown pipe: writing to this fd unblocks the TUN reader thread on macOS.
620    /// On Linux, deleting the interface via netlink serves the same purpose.
621    #[cfg(target_os = "macos")]
622    tun_shutdown_fd: Option<std::os::unix::io::RawFd>,
623
624    // === DNS Responder ===
625    /// Receiver for resolved identities from the DNS responder.
626    dns_identity_rx: Option<crate::upper::dns::DnsIdentityRx>,
627    /// DNS responder task handle.
628    dns_task: Option<tokio::task::JoinHandle<()>>,
629
630    // === Index-Based Session Dispatch ===
631    /// Allocator for session indices.
632    index_allocator: IndexAllocator,
633    /// O(1) lookup: (transport_id, our_index) → NodeAddr.
634    /// This maps our session index to the peer that uses it.
635    peers_by_index: HashMap<(TransportId, u32), NodeAddr>,
636    /// Pending outbound handshakes by our sender_idx.
637    /// Tracks which LinkId corresponds to which session index.
638    pending_outbound: HashMap<(TransportId, u32), LinkId>,
639
640    // === Rate Limiting ===
641    /// Rate limiter for msg1 processing (DoS protection).
642    msg1_rate_limiter: HandshakeRateLimiter,
643    /// Rate limiter for ICMP Packet Too Big messages.
644    icmp_rate_limiter: IcmpRateLimiter,
645    /// Rate limiter for routing error signals (CoordsRequired / PathBroken).
646    routing_error_rate_limiter: RoutingErrorRateLimiter,
647    /// Rate limiter for source-side CoordsRequired/PathBroken responses.
648    coords_response_rate_limiter: RoutingErrorRateLimiter,
649    /// Backoff for failed discovery lookups (originator-side).
650    discovery_backoff: DiscoveryBackoff,
651    /// Rate limiter for forwarded discovery requests (transit-side).
652    discovery_forward_limiter: DiscoveryForwardRateLimiter,
653
654    // === Pending Transport Connects ===
655    /// Links waiting for transport-level connection establishment before
656    /// sending handshake msg1. For connection-oriented transports (TCP, Tor),
657    /// the transport connect runs in the background; the tick handler polls
658    /// connection_state() and initiates the handshake when connected.
659    pending_connects: Vec<PendingConnect>,
660
661    // === Connection Retry ===
662    /// Retry state for peers whose outbound connections have failed.
663    /// Keyed by NodeAddr. Entries are created when a handshake times out
664    /// or fails, and removed on successful promotion or when max retries
665    /// are exhausted.
666    retry_pending: HashMap<NodeAddr, retry::RetryState>,
667
668    /// Optional Nostr/STUN overlay discovery coordinator for `udp:nat` peers.
669    nostr_discovery: Option<Arc<crate::discovery::nostr::NostrDiscovery>>,
670    /// mDNS / DNS-SD responder + browser for local-link peer discovery.
671    /// Identity is unverified at this layer — the Noise XX handshake
672    /// initiated against an mDNS-observed endpoint is what proves the
673    /// peer holds the matching private key.
674    lan_discovery: Option<Arc<crate::discovery::lan::LanDiscovery>>,
675    /// Same-host JSON registry under `~/.fips/instances`. Records are
676    /// loopback routing hints only; peer identity is still verified by the
677    /// Noise handshake.
678    local_instance_registry: Option<crate::discovery::local::LocalInstanceRegistry>,
679    local_instance_started_at_ms: Option<u64>,
680    last_local_instance_publish_ms: Option<u64>,
681    last_local_instance_scan_ms: Option<u64>,
682    /// Wall-clock ms when Nostr discovery successfully started, used to
683    /// schedule the one-shot startup advert sweep after a settle delay.
684    /// `None` until discovery comes up; remains `None` if discovery is
685    /// disabled or failed to start.
686    nostr_discovery_started_at_ms: Option<u64>,
687    /// Whether the one-shot startup advert sweep has run. Set to true
688    /// after the first sweep fires (under `policy: open`); thereafter
689    /// only the per-tick `queue_open_discovery_retries` continues.
690    startup_open_discovery_sweep_done: bool,
691    /// Per-peer UDP transports adopted from NAT traversal handoff.
692    bootstrap_transports: HashSet<TransportId>,
693    /// Originating peer npub (bech32) for each adopted bootstrap
694    /// transport, captured at `adopt_established_traversal` time.
695    /// Populated alongside `bootstrap_transports`; cleared in
696    /// `cleanup_bootstrap_transport_if_unused`. Used by the rx loop to
697    /// route fatal-protocol-mismatch observations back to the
698    /// Nostr-discovery `failure_state` for long cooldown application.
699    bootstrap_transport_npubs: HashMap<TransportId, String>,
700    /// Peers that should not be used as reply-learned fallback transit for
701    /// other destinations. Direct lookups to the peer are still permitted.
702    discovery_fallback_transit_blocked_peers: HashSet<NodeAddr>,
703
704    // === Periodic Parent Re-evaluation ===
705    /// Timestamp of last periodic parent re-evaluation (for pacing).
706    last_parent_reeval: Option<crate::time::Instant>,
707
708    // === Congestion Logging ===
709    /// Timestamp of last congestion detection log (rate-limited to 5s).
710    last_congestion_log: Option<std::time::Instant>,
711
712    // === Mesh Size Estimate ===
713    /// Cached estimated mesh size (computed once per tick from bloom filters).
714    estimated_mesh_size: Option<u64>,
715    /// Timestamp of last mesh size log emission.
716    last_mesh_size_log: Option<std::time::Instant>,
717
718    // === Bloom Self-Plausibility ===
719    /// Rate-limit state for the self-plausibility WARN. Fires at most
720    /// once per 60s globally when our own outgoing FilterAnnounce has
721    /// an FPR above `node.bloom.max_inbound_fpr`, signalling either
722    /// aggregation drift or an ingress bypass.
723    last_self_warn: Option<std::time::Instant>,
724
725    // === Local Outbound Liveness ===
726    /// Set when a `transport.send` returned a local-side io error
727    /// (`NetworkUnreachable` / `HostUnreachable` / `AddrNotAvailable`),
728    /// cleared on the next successful send. Used by
729    /// `check_link_heartbeats` to compress the dead-timeout to
730    /// `fast_link_dead_timeout_secs` while our outbound is observed
731    /// broken — direct kernel evidence beats waiting on receive-silence.
732    last_local_send_failure_at: Option<std::time::Instant>,
733
734    // === Display Names ===
735    /// Human-readable names for configured peers (alias or short npub).
736    /// Populated at startup from peer config.
737    peer_aliases: HashMap<NodeAddr, String>,
738
739    /// Reloadable peer ACL state from standard allow/deny files.
740    peer_acl: acl::PeerAclReloader,
741
742    // === Host Map ===
743    /// Static hostname → npub mapping for DNS resolution.
744    /// Built at construction from peer aliases and /etc/fips/hosts.
745    host_map: Arc<HostMap>,
746}
747
748impl Node {
749    /// Create a new node from configuration.
750    pub fn new(config: Config) -> Result<Self, NodeError> {
751        config.validate()?;
752        let identity = config.create_identity()?;
753        let node_addr = *identity.node_addr();
754        let is_leaf_only = config.is_leaf_only();
755
756        let (decrypt_fallback_tx, decrypt_fallback_rx) = tokio::sync::mpsc::unbounded_channel();
757        let decrypt_fallback_rx = Some(decrypt_fallback_rx);
758
759        let mut startup_epoch = [0u8; 8];
760        rand::rng().fill_bytes(&mut startup_epoch);
761
762        let mut bloom_state = if is_leaf_only {
763            BloomState::leaf_only(node_addr)
764        } else {
765            BloomState::new(node_addr)
766        };
767        bloom_state.set_update_debounce_ms(config.node.bloom.update_debounce_ms);
768
769        let tun_state = if config.tun.enabled {
770            TunState::Configured
771        } else {
772            TunState::Disabled
773        };
774
775        // Initialize tree state with signed self-declaration
776        let mut tree_state = TreeState::new(node_addr);
777        tree_state.set_parent_hysteresis(config.node.tree.parent_hysteresis);
778        tree_state.set_hold_down(config.node.tree.hold_down_secs);
779        tree_state.set_flap_dampening(
780            config.node.tree.flap_threshold,
781            config.node.tree.flap_window_secs,
782            config.node.tree.flap_dampening_secs,
783        );
784        tree_state
785            .sign_declaration(&identity)
786            .expect("signing own declaration should never fail");
787
788        let coord_cache = CoordCache::new(
789            config.node.cache.coord_size,
790            config.node.cache.coord_ttl_secs * 1000,
791        );
792        let rl = &config.node.rate_limit;
793        let msg1_rate_limiter = HandshakeRateLimiter::with_params(
794            rate_limit::TokenBucket::with_params(rl.handshake_burst, rl.handshake_rate),
795            config.node.limits.max_pending_inbound,
796        );
797
798        let max_connections = config.node.limits.max_connections;
799        let max_peers = config.node.limits.max_peers;
800        let max_links = config.node.limits.max_links;
801        let coords_response_interval_ms = config.node.session.coords_response_interval_ms;
802        let backoff_base_secs = config.node.discovery.backoff_base_secs;
803        let backoff_max_secs = config.node.discovery.backoff_max_secs;
804        let forward_min_interval_secs = config.node.discovery.forward_min_interval_secs;
805
806        let (host_map, peer_acl) = Self::host_map_and_peer_acl(&config);
807
808        Ok(Self {
809            identity,
810            startup_epoch,
811            started_at: std::time::Instant::now(),
812            config,
813            state: NodeState::Created,
814            is_leaf_only,
815            tree_state,
816            bloom_state,
817            coord_cache,
818            learned_routes: LearnedRouteTable::default(),
819            recent_requests: HashMap::new(),
820            transports: HashMap::new(),
821            transport_drops: HashMap::new(),
822            links: HashMap::new(),
823            addr_to_link: HashMap::new(),
824            packet_tx: None,
825            packet_rx: None,
826            connections: HashMap::new(),
827            peers: HashMap::new(),
828            sessions: HashMap::new(),
829            identity_cache: HashMap::new(),
830            pending_tun_packets: HashMap::new(),
831            pending_endpoint_data: HashMap::new(),
832            pending_lookups: HashMap::new(),
833            max_connections,
834            max_peers,
835            max_links,
836            next_link_id: 1,
837            next_transport_id: 1,
838            stats: stats::NodeStats::new(),
839            stats_history: stats_history::StatsHistory::new(),
840            tun_state,
841            tun_name: None,
842            tun_tx: None,
843            tun_outbound_rx: None,
844            external_packet_tx: None,
845            endpoint_command_rx: None,
846            endpoint_event_tx: None,
847            encrypt_workers: None,
848            decrypt_workers: None,
849            decrypt_registered_sessions: std::collections::HashSet::new(),
850            decrypt_fallback_tx,
851            decrypt_fallback_rx,
852            tun_reader_handle: None,
853            tun_writer_handle: None,
854            #[cfg(target_os = "macos")]
855            tun_shutdown_fd: None,
856            dns_identity_rx: None,
857            dns_task: None,
858            index_allocator: IndexAllocator::new(),
859            peers_by_index: HashMap::new(),
860            pending_outbound: HashMap::new(),
861            msg1_rate_limiter,
862            icmp_rate_limiter: IcmpRateLimiter::new(),
863            routing_error_rate_limiter: RoutingErrorRateLimiter::new(),
864            coords_response_rate_limiter: RoutingErrorRateLimiter::with_interval(
865                std::time::Duration::from_millis(coords_response_interval_ms),
866            ),
867            discovery_backoff: DiscoveryBackoff::with_params(backoff_base_secs, backoff_max_secs),
868            discovery_forward_limiter: DiscoveryForwardRateLimiter::with_interval(
869                std::time::Duration::from_secs(forward_min_interval_secs),
870            ),
871            pending_connects: Vec::new(),
872            retry_pending: HashMap::new(),
873            nostr_discovery: None,
874            nostr_discovery_started_at_ms: None,
875            lan_discovery: None,
876            local_instance_registry: None,
877            local_instance_started_at_ms: None,
878            last_local_instance_publish_ms: None,
879            last_local_instance_scan_ms: None,
880            startup_open_discovery_sweep_done: false,
881            bootstrap_transports: HashSet::new(),
882            bootstrap_transport_npubs: HashMap::new(),
883            discovery_fallback_transit_blocked_peers: HashSet::new(),
884            last_parent_reeval: None,
885            last_congestion_log: None,
886            estimated_mesh_size: None,
887            last_mesh_size_log: None,
888            last_self_warn: None,
889            last_local_send_failure_at: None,
890            peer_aliases: HashMap::new(),
891            peer_acl,
892            host_map,
893            path_mtu_lookup: Arc::new(std::sync::RwLock::new(HashMap::new())),
894        })
895    }
896
897    /// Create a node with a specific identity.
898    ///
899    /// This constructor validates cross-field config invariants before
900    /// constructing the node, same as [`Node::new`].
901    pub fn with_identity(identity: Identity, config: Config) -> Result<Self, NodeError> {
902        config.validate()?;
903        let node_addr = *identity.node_addr();
904
905        let (decrypt_fallback_tx, decrypt_fallback_rx) = tokio::sync::mpsc::unbounded_channel();
906        let decrypt_fallback_rx = Some(decrypt_fallback_rx);
907
908        let mut startup_epoch = [0u8; 8];
909        rand::rng().fill_bytes(&mut startup_epoch);
910
911        let tun_state = if config.tun.enabled {
912            TunState::Configured
913        } else {
914            TunState::Disabled
915        };
916
917        // Initialize tree state with signed self-declaration
918        let mut tree_state = TreeState::new(node_addr);
919        tree_state.set_parent_hysteresis(config.node.tree.parent_hysteresis);
920        tree_state.set_hold_down(config.node.tree.hold_down_secs);
921        tree_state.set_flap_dampening(
922            config.node.tree.flap_threshold,
923            config.node.tree.flap_window_secs,
924            config.node.tree.flap_dampening_secs,
925        );
926        tree_state
927            .sign_declaration(&identity)
928            .expect("signing own declaration should never fail");
929
930        let mut bloom_state = BloomState::new(node_addr);
931        bloom_state.set_update_debounce_ms(config.node.bloom.update_debounce_ms);
932
933        let coord_cache = CoordCache::new(
934            config.node.cache.coord_size,
935            config.node.cache.coord_ttl_secs * 1000,
936        );
937        let rl = &config.node.rate_limit;
938        let msg1_rate_limiter = HandshakeRateLimiter::with_params(
939            rate_limit::TokenBucket::with_params(rl.handshake_burst, rl.handshake_rate),
940            config.node.limits.max_pending_inbound,
941        );
942
943        let max_connections = config.node.limits.max_connections;
944        let max_peers = config.node.limits.max_peers;
945        let max_links = config.node.limits.max_links;
946        let coords_response_interval_ms = config.node.session.coords_response_interval_ms;
947
948        let (host_map, peer_acl) = Self::host_map_and_peer_acl(&config);
949
950        Ok(Self {
951            identity,
952            startup_epoch,
953            started_at: std::time::Instant::now(),
954            config,
955            state: NodeState::Created,
956            is_leaf_only: false,
957            tree_state,
958            bloom_state,
959            coord_cache,
960            learned_routes: LearnedRouteTable::default(),
961            recent_requests: HashMap::new(),
962            transports: HashMap::new(),
963            transport_drops: HashMap::new(),
964            links: HashMap::new(),
965            addr_to_link: HashMap::new(),
966            packet_tx: None,
967            packet_rx: None,
968            connections: HashMap::new(),
969            peers: HashMap::new(),
970            sessions: HashMap::new(),
971            identity_cache: HashMap::new(),
972            pending_tun_packets: HashMap::new(),
973            pending_endpoint_data: HashMap::new(),
974            pending_lookups: HashMap::new(),
975            max_connections,
976            max_peers,
977            max_links,
978            next_link_id: 1,
979            next_transport_id: 1,
980            stats: stats::NodeStats::new(),
981            stats_history: stats_history::StatsHistory::new(),
982            tun_state,
983            tun_name: None,
984            tun_tx: None,
985            tun_outbound_rx: None,
986            external_packet_tx: None,
987            endpoint_command_rx: None,
988            endpoint_event_tx: None,
989            encrypt_workers: None,
990            decrypt_workers: None,
991            decrypt_registered_sessions: std::collections::HashSet::new(),
992            decrypt_fallback_tx,
993            decrypt_fallback_rx,
994            tun_reader_handle: None,
995            tun_writer_handle: None,
996            #[cfg(target_os = "macos")]
997            tun_shutdown_fd: None,
998            dns_identity_rx: None,
999            dns_task: None,
1000            index_allocator: IndexAllocator::new(),
1001            peers_by_index: HashMap::new(),
1002            pending_outbound: HashMap::new(),
1003            msg1_rate_limiter,
1004            icmp_rate_limiter: IcmpRateLimiter::new(),
1005            routing_error_rate_limiter: RoutingErrorRateLimiter::new(),
1006            coords_response_rate_limiter: RoutingErrorRateLimiter::with_interval(
1007                std::time::Duration::from_millis(coords_response_interval_ms),
1008            ),
1009            discovery_backoff: DiscoveryBackoff::new(),
1010            discovery_forward_limiter: DiscoveryForwardRateLimiter::new(),
1011            pending_connects: Vec::new(),
1012            retry_pending: HashMap::new(),
1013            nostr_discovery: None,
1014            nostr_discovery_started_at_ms: None,
1015            lan_discovery: None,
1016            local_instance_registry: None,
1017            local_instance_started_at_ms: None,
1018            last_local_instance_publish_ms: None,
1019            last_local_instance_scan_ms: None,
1020            startup_open_discovery_sweep_done: false,
1021            bootstrap_transports: HashSet::new(),
1022            bootstrap_transport_npubs: HashMap::new(),
1023            discovery_fallback_transit_blocked_peers: HashSet::new(),
1024            last_parent_reeval: None,
1025            last_congestion_log: None,
1026            estimated_mesh_size: None,
1027            last_mesh_size_log: None,
1028            last_self_warn: None,
1029            last_local_send_failure_at: None,
1030            peer_aliases: HashMap::new(),
1031            peer_acl,
1032            host_map,
1033            path_mtu_lookup: Arc::new(std::sync::RwLock::new(HashMap::new())),
1034        })
1035    }
1036
1037    /// Create a leaf-only node (simplified state).
1038    pub fn leaf_only(config: Config) -> Result<Self, NodeError> {
1039        let mut node = Self::new(config)?;
1040        node.is_leaf_only = true;
1041        node.bloom_state = BloomState::leaf_only(*node.identity.node_addr());
1042        Ok(node)
1043    }
1044
1045    fn host_map_and_peer_acl(config: &Config) -> (Arc<HostMap>, acl::PeerAclReloader) {
1046        let base_host_map = HostMap::from_peer_configs(config.peers());
1047        if !config.node.system_files_enabled {
1048            return (
1049                Arc::new(base_host_map.clone()),
1050                acl::PeerAclReloader::memory_only(base_host_map),
1051            );
1052        }
1053
1054        let mut host_map = base_host_map.clone();
1055        let hosts_path = std::path::PathBuf::from(crate::upper::hosts::DEFAULT_HOSTS_PATH);
1056        let hosts_file = HostMap::load_hosts_file(std::path::Path::new(
1057            crate::upper::hosts::DEFAULT_HOSTS_PATH,
1058        ));
1059        host_map.merge(hosts_file);
1060        let peer_acl = acl::PeerAclReloader::with_alias_sources(
1061            std::path::PathBuf::from(acl::DEFAULT_PEERS_ALLOW_PATH),
1062            std::path::PathBuf::from(acl::DEFAULT_PEERS_DENY_PATH),
1063            base_host_map,
1064            hosts_path,
1065        );
1066        (Arc::new(host_map), peer_acl)
1067    }
1068
1069    /// Create transport instances from configuration.
1070    ///
1071    /// Returns a vector of TransportHandles for all configured transports.
1072    async fn create_transports(&mut self, packet_tx: &PacketTx) -> Vec<TransportHandle> {
1073        let mut transports = Vec::new();
1074
1075        // Collect UDP configs with optional names to avoid borrow conflicts
1076        let udp_instances: Vec<_> = self
1077            .config
1078            .transports
1079            .udp
1080            .iter()
1081            .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1082            .collect();
1083
1084        // Create UDP transport instances
1085        for (name, udp_config) in udp_instances {
1086            let transport_id = self.allocate_transport_id();
1087            let udp = UdpTransport::new(transport_id, name, udp_config, packet_tx.clone());
1088            transports.push(TransportHandle::Udp(udp));
1089        }
1090
1091        #[cfg(feature = "sim-transport")]
1092        {
1093            let sim_instances: Vec<_> = self
1094                .config
1095                .transports
1096                .sim
1097                .iter()
1098                .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1099                .collect();
1100
1101            for (name, sim_config) in sim_instances {
1102                let transport_id = self.allocate_transport_id();
1103                let sim = crate::transport::sim::SimTransport::new(
1104                    transport_id,
1105                    name,
1106                    sim_config,
1107                    packet_tx.clone(),
1108                );
1109                transports.push(TransportHandle::Sim(sim));
1110            }
1111        }
1112
1113        // Create Ethernet transport instances where raw-socket support exists.
1114        #[cfg(any(target_os = "linux", target_os = "macos"))]
1115        {
1116            let eth_instances: Vec<_> = self
1117                .config
1118                .transports
1119                .ethernet
1120                .iter()
1121                .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1122                .collect();
1123            let xonly = self.identity.pubkey();
1124            for (name, eth_config) in eth_instances {
1125                let mut eth_config = eth_config;
1126                if eth_config.discovery_scope.is_none() {
1127                    eth_config.discovery_scope = self.lan_discovery_scope();
1128                }
1129                let transport_id = self.allocate_transport_id();
1130                let mut eth =
1131                    EthernetTransport::new(transport_id, name, eth_config, packet_tx.clone());
1132                eth.set_local_pubkey(xonly);
1133                transports.push(TransportHandle::Ethernet(eth));
1134            }
1135        }
1136
1137        // Create TCP transport instances
1138        let tcp_instances: Vec<_> = self
1139            .config
1140            .transports
1141            .tcp
1142            .iter()
1143            .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1144            .collect();
1145
1146        for (name, tcp_config) in tcp_instances {
1147            let transport_id = self.allocate_transport_id();
1148            let tcp = TcpTransport::new(transport_id, name, tcp_config, packet_tx.clone());
1149            transports.push(TransportHandle::Tcp(tcp));
1150        }
1151
1152        // Create Tor transport instances
1153        let tor_instances: Vec<_> = self
1154            .config
1155            .transports
1156            .tor
1157            .iter()
1158            .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1159            .collect();
1160
1161        for (name, tor_config) in tor_instances {
1162            let transport_id = self.allocate_transport_id();
1163            let tor = TorTransport::new(transport_id, name, tor_config, packet_tx.clone());
1164            transports.push(TransportHandle::Tor(tor));
1165        }
1166
1167        let webrtc_instances: Vec<_> = self
1168            .config
1169            .transports
1170            .webrtc
1171            .iter()
1172            .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1173            .collect();
1174
1175        #[cfg(feature = "webrtc-transport")]
1176        {
1177            for (name, webrtc_config) in webrtc_instances {
1178                let transport_id = self.allocate_transport_id();
1179                match WebRtcTransport::new(
1180                    transport_id,
1181                    name,
1182                    webrtc_config,
1183                    packet_tx.clone(),
1184                    &self.identity,
1185                    &self.config.node.discovery.nostr,
1186                ) {
1187                    Ok(webrtc) => transports.push(TransportHandle::WebRtc(Box::new(webrtc))),
1188                    Err(err) => {
1189                        warn!(
1190                            transport_id = %transport_id,
1191                            error = %err,
1192                            "failed to initialize WebRTC transport"
1193                        );
1194                    }
1195                }
1196            }
1197        }
1198        #[cfg(not(feature = "webrtc-transport"))]
1199        if !webrtc_instances.is_empty() {
1200            warn!("WebRTC transport configured but this build lacks WebRTC transport support");
1201        }
1202
1203        // Create BLE transport instances
1204        #[cfg(bluer_available)]
1205        {
1206            let ble_instances: Vec<_> = self
1207                .config
1208                .transports
1209                .ble
1210                .iter()
1211                .map(|(name, config)| (name.map(|s| s.to_string()), config.clone()))
1212                .collect();
1213
1214            #[cfg(all(bluer_available, not(test)))]
1215            for (name, ble_config) in ble_instances {
1216                let transport_id = self.allocate_transport_id();
1217                let adapter = ble_config.adapter().to_string();
1218                let mtu = ble_config.mtu();
1219                match crate::transport::ble::io::BluerIo::new(&adapter, mtu).await {
1220                    Ok(io) => {
1221                        let mut ble = crate::transport::ble::BleTransport::new(
1222                            transport_id,
1223                            name,
1224                            ble_config,
1225                            io,
1226                            packet_tx.clone(),
1227                        );
1228                        ble.set_local_pubkey(self.identity.pubkey().serialize());
1229                        transports.push(TransportHandle::Ble(ble));
1230                    }
1231                    Err(e) => {
1232                        tracing::warn!(adapter = %adapter, error = %e, "failed to initialize BLE adapter");
1233                    }
1234                }
1235            }
1236
1237            #[cfg(any(not(bluer_available), test))]
1238            if !ble_instances.is_empty() {
1239                #[cfg(not(test))]
1240                tracing::warn!("BLE transport configured but this build lacks BlueZ support");
1241            }
1242        }
1243
1244        transports
1245    }
1246
1247    /// Find an operational transport that matches the given transport type name.
1248    ///
1249    /// Adopted UDP bootstrap transports are point-to-point sockets handed off
1250    /// from Nostr/STUN traversal. They must not be reused for ordinary
1251    /// `udp host:port` dials discovered through static config, mDNS, or overlay
1252    /// adverts: on macOS a `send_to` through the wrong adopted socket can fail
1253    /// with `EINVAL`, and even on platforms that allow it the packet would use
1254    /// the wrong 5-tuple/NAT mapping. Prefer configured transports and make the
1255    /// choice deterministic by lowest transport id instead of HashMap order.
1256    fn find_transport_for_type(&self, transport_type: &str) -> Option<TransportId> {
1257        self.transports
1258            .iter()
1259            .filter(|(id, handle)| {
1260                handle.transport_type().name == transport_type
1261                    && handle.is_operational()
1262                    && !self.bootstrap_transports.contains(id)
1263            })
1264            .min_by_key(|(id, _)| id.as_u32())
1265            .map(|(id, _)| *id)
1266    }
1267
1268    /// Resolve an Ethernet peer address ("interface/mac") to a transport ID
1269    /// and binary TransportAddr.
1270    ///
1271    /// Finds the Ethernet transport instance bound to the named interface
1272    /// and parses the MAC portion into a 6-byte TransportAddr.
1273    #[allow(unused_variables)]
1274    fn resolve_ethernet_addr(
1275        &self,
1276        addr_str: &str,
1277    ) -> Result<(TransportId, TransportAddr), NodeError> {
1278        #[cfg(any(target_os = "linux", target_os = "macos"))]
1279        {
1280            let (iface, mac_str) = addr_str.split_once('/').ok_or_else(|| {
1281                NodeError::NoTransportForType(format!(
1282                    "invalid Ethernet address format '{}': expected 'interface/mac'",
1283                    addr_str
1284                ))
1285            })?;
1286
1287            // Find the Ethernet transport bound to this interface
1288            let transport_id = self
1289                .transports
1290                .iter()
1291                .find(|(_, handle)| {
1292                    handle.transport_type().name == "ethernet"
1293                        && handle.is_operational()
1294                        && handle.interface_name() == Some(iface)
1295                })
1296                .map(|(id, _)| *id)
1297                .ok_or_else(|| {
1298                    NodeError::NoTransportForType(format!(
1299                        "no operational Ethernet transport for interface '{}'",
1300                        iface
1301                    ))
1302                })?;
1303
1304            let mac = crate::transport::ethernet::parse_mac_string(mac_str).map_err(|e| {
1305                NodeError::NoTransportForType(format!("invalid MAC in '{}': {}", addr_str, e))
1306            })?;
1307
1308            Ok((transport_id, TransportAddr::from_bytes(&mac)))
1309        }
1310        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
1311        {
1312            Err(NodeError::NoTransportForType(
1313                "Ethernet transport is not supported on this platform".to_string(),
1314            ))
1315        }
1316    }
1317
1318    /// Resolve a BLE address string (`"adapter/AA:BB:CC:DD:EE:FF"`) to a
1319    /// (TransportId, TransportAddr) pair by finding the BLE transport
1320    /// instance matching the adapter name.
1321    #[cfg(bluer_available)]
1322    fn resolve_ble_addr(&self, addr_str: &str) -> Result<(TransportId, TransportAddr), NodeError> {
1323        let ta = TransportAddr::from_string(addr_str);
1324        let adapter = crate::transport::ble::addr::adapter_from_addr(&ta).ok_or_else(|| {
1325            NodeError::NoTransportForType(format!(
1326                "invalid BLE address format '{}': expected 'adapter/mac'",
1327                addr_str
1328            ))
1329        })?;
1330
1331        // Find the BLE transport for this adapter
1332        let transport_id = self
1333            .transports
1334            .iter()
1335            .find(|(_, handle)| handle.transport_type().name == "ble" && handle.is_operational())
1336            .map(|(id, _)| *id)
1337            .ok_or_else(|| {
1338                NodeError::NoTransportForType(format!(
1339                    "no operational BLE transport for adapter '{}'",
1340                    adapter
1341                ))
1342            })?;
1343
1344        // Validate the address format
1345        crate::transport::ble::addr::BleAddr::parse(addr_str).map_err(|e| {
1346            NodeError::NoTransportForType(format!("invalid BLE address '{}': {}", addr_str, e))
1347        })?;
1348
1349        Ok((transport_id, TransportAddr::from_string(addr_str)))
1350    }
1351
1352    // === Identity Accessors ===
1353
1354    /// Get this node's identity.
1355    pub fn identity(&self) -> &Identity {
1356        &self.identity
1357    }
1358
1359    /// Get this node's NodeAddr.
1360    pub fn node_addr(&self) -> &NodeAddr {
1361        self.identity.node_addr()
1362    }
1363
1364    /// Get this node's npub.
1365    pub fn npub(&self) -> String {
1366        self.identity.npub()
1367    }
1368
1369    /// Return a human-readable display name for a NodeAddr.
1370    ///
1371    /// Lookup order:
1372    /// 1. Host map hostname (from peer aliases + /etc/fips/hosts)
1373    /// 2. Configured peer alias or short npub (from startup map)
1374    /// 3. Active peer's short npub (e.g., inbound peer not in config)
1375    /// 4. Session endpoint's short npub (end-to-end, may not be direct peer)
1376    /// 5. Truncated NodeAddr hex (unknown address)
1377    pub(crate) fn peer_display_name(&self, addr: &NodeAddr) -> String {
1378        if let Some(hostname) = self.host_map.lookup_hostname(addr) {
1379            return hostname.to_string();
1380        }
1381        if let Some(name) = self.peer_aliases.get(addr) {
1382            return name.clone();
1383        }
1384        if let Some(peer) = self.peers.get(addr) {
1385            return peer.identity().short_npub();
1386        }
1387        if let Some(entry) = self.sessions.get(addr) {
1388            let (xonly, _) = entry.remote_pubkey().x_only_public_key();
1389            return PeerIdentity::from_pubkey(xonly).short_npub();
1390        }
1391        addr.short_hex()
1392    }
1393
1394    /// Tear down a `peers_by_index` entry **and** keep the shard-owned
1395    /// decrypt-worker state coherent: removes the same `cache_key`
1396    /// from the registered-sessions tracking set and tells the
1397    /// assigned shard worker to drop its `OwnedSessionState` entry.
1398    ///
1399    /// Use this instead of a bare `self.peers_by_index.remove(&key)`
1400    /// at every session-lifecycle teardown site (rekey cross-connection
1401    /// swap, peer disconnect, dispatch session-rotation) so the worker
1402    /// doesn't keep stale ciphers / replay windows around. The
1403    /// follow-up `RegisterSession` for the NEW key (if any) will then
1404    /// install the fresh state on the same shard.
1405    pub(in crate::node) fn deregister_session_index(&mut self, cache_key: (TransportId, u32)) {
1406        // Find the peer that owns this index BEFORE removing it from
1407        // the index map, so we can decide whether the deregistration
1408        // also tears down the peer's connected UDP socket.
1409        let owning_peer = self.peers_by_index.get(&cache_key).copied();
1410        self.peers_by_index.remove(&cache_key);
1411        if self.decrypt_registered_sessions.remove(&cache_key)
1412            && let Some(workers) = self.decrypt_workers.as_ref()
1413        {
1414            workers.unregister_session(cache_key);
1415        }
1416        // Tear down the per-peer connected UDP socket *only* if no
1417        // other peers_by_index entry still resolves to this peer.
1418        // Rekey drain calls into this helper with the OLD session
1419        // index while the NEW index is already installed and points
1420        // at the same peer — there the connect()-ed 5-tuple is
1421        // still valid for the new session and we must not close it.
1422        // Peer-teardown sites (CrossConnection swap, stale-index
1423        // fall-through in encrypted.rs, disconnect handler) call
1424        // here when this is the peer's last index, so the connected
1425        // socket goes away with the peer.
1426        if let Some(peer_addr) = owning_peer {
1427            let peer_has_other_index = self
1428                .peers_by_index
1429                .values()
1430                .any(|other| *other == peer_addr);
1431            if !peer_has_other_index {
1432                self.clear_connected_udp_for_peer(&peer_addr);
1433            }
1434        }
1435    }
1436
1437    /// Ensure the current FMP receive index resolves to this peer.
1438    ///
1439    /// Rekey msg1/msg2 handlers pre-register the pending index before
1440    /// cutover, but losing that registration in a debug build used to
1441    /// panic in the cutover path. Repairing the map here is safe: the
1442    /// peer has already promoted the pending session, and the decrypt
1443    /// worker registration immediately after cutover depends on the
1444    /// same `(transport_id, our_index)` key.
1445    pub(in crate::node) fn ensure_current_session_index_registered(
1446        &mut self,
1447        node_addr: &NodeAddr,
1448        context: &'static str,
1449    ) -> bool {
1450        let Some(peer) = self.peers.get(node_addr) else {
1451            return false;
1452        };
1453        let Some(transport_id) = peer.transport_id() else {
1454            warn!(
1455                peer = %self.peer_display_name(node_addr),
1456                context,
1457                "Cannot register current session index without transport id"
1458            );
1459            return false;
1460        };
1461        let Some(our_index) = peer.our_index() else {
1462            warn!(
1463                peer = %self.peer_display_name(node_addr),
1464                context,
1465                "Cannot register current session index without local index"
1466            );
1467            return false;
1468        };
1469
1470        let cache_key = (transport_id, our_index.as_u32());
1471        match self.peers_by_index.get(&cache_key).copied() {
1472            Some(existing) if existing == *node_addr => true,
1473            Some(existing) => {
1474                warn!(
1475                    peer = %self.peer_display_name(node_addr),
1476                    previous_owner = %self.peer_display_name(&existing),
1477                    transport_id = %transport_id,
1478                    our_index = %our_index,
1479                    context,
1480                    "Repairing current session index with stale owner"
1481                );
1482                self.peers_by_index.insert(cache_key, *node_addr);
1483                true
1484            }
1485            None => {
1486                warn!(
1487                    peer = %self.peer_display_name(node_addr),
1488                    transport_id = %transport_id,
1489                    our_index = %our_index,
1490                    context,
1491                    "Repairing missing current session index"
1492                );
1493                self.peers_by_index.insert(cache_key, *node_addr);
1494                true
1495            }
1496        }
1497    }
1498
1499    // === Configuration ===
1500
1501    /// Get the configuration.
1502    pub fn config(&self) -> &Config {
1503        &self.config
1504    }
1505
1506    /// Calculate the effective IPv6 MTU that can be sent over FIPS.
1507    ///
1508    /// Delegates to `upper::icmp::effective_ipv6_mtu()` with this node's
1509    /// transport MTU. Returns the maximum IPv6 packet size (including
1510    /// IPv6 header) that can be transmitted through the FIPS mesh.
1511    pub fn effective_ipv6_mtu(&self) -> u16 {
1512        crate::upper::icmp::effective_ipv6_mtu(self.transport_mtu())
1513    }
1514
1515    /// Get the transport MTU governing the global TUN-boundary MSS clamp.
1516    ///
1517    /// Returns the **minimum** MTU across all operational transports, or
1518    /// 1280 (IPv6 minimum) as fallback. Used for initial TUN configuration
1519    /// where a specific egress transport isn't yet known: the resulting
1520    /// `effective_ipv6_mtu` (transport_mtu - 77) and `max_mss`
1521    /// (effective_mtu - 60) form a conservative ceiling that fits ANY
1522    /// configured-transport's egress, eliminating PMTU-D black holes that
1523    /// would otherwise occur when a flow's actual egress is smaller than
1524    /// the clamp ceiling assumed at TUN init.
1525    ///
1526    /// Returning the smallest (rather than the first-iterated, which used
1527    /// to vary across HashMap iteration order + async-startup race) makes
1528    /// the clamp deterministic across daemon restarts.
1529    ///
1530    /// See `ISSUE-2026-0011` for the empirical investigation.
1531    pub fn transport_mtu(&self) -> u16 {
1532        let min_operational = self
1533            .transports
1534            .values()
1535            .filter(|h| h.is_operational())
1536            .map(|h| h.mtu())
1537            .min();
1538        if let Some(mtu) = min_operational {
1539            return mtu;
1540        }
1541        // Fallback to config: try UDP first, then Ethernet
1542        if let Some((_, cfg)) = self.config.transports.udp.iter().next() {
1543            return cfg.mtu();
1544        }
1545        1280
1546    }
1547
1548    // === State ===
1549
1550    /// Get the node state.
1551    pub fn state(&self) -> NodeState {
1552        self.state
1553    }
1554
1555    /// Get the node uptime.
1556    pub fn uptime(&self) -> std::time::Duration {
1557        self.started_at.elapsed()
1558    }
1559
1560    /// Check if node is operational.
1561    pub fn is_running(&self) -> bool {
1562        self.state.is_operational()
1563    }
1564
1565    /// Check if this is a leaf-only node.
1566    pub fn is_leaf_only(&self) -> bool {
1567        self.is_leaf_only
1568    }
1569
1570    // === Tree State ===
1571
1572    /// Get the tree state.
1573    pub fn tree_state(&self) -> &TreeState {
1574        &self.tree_state
1575    }
1576
1577    /// Get mutable tree state.
1578    pub fn tree_state_mut(&mut self) -> &mut TreeState {
1579        &mut self.tree_state
1580    }
1581
1582    // === Bloom State ===
1583
1584    /// Get the Bloom filter state.
1585    pub fn bloom_state(&self) -> &BloomState {
1586        &self.bloom_state
1587    }
1588
1589    /// Get mutable Bloom filter state.
1590    pub fn bloom_state_mut(&mut self) -> &mut BloomState {
1591        &mut self.bloom_state
1592    }
1593
1594    // === Mesh Size Estimate ===
1595
1596    /// Get the cached estimated mesh size.
1597    pub fn estimated_mesh_size(&self) -> Option<u64> {
1598        self.estimated_mesh_size
1599    }
1600
1601    /// Compute and cache the estimated mesh size from bloom filters.
1602    ///
1603    /// Uses the spanning tree partition: parent's filter covers nodes reachable
1604    /// upward, children's filters cover disjoint subtrees downward. The sum
1605    /// of estimated entry counts plus one (self) approximates total network size.
1606    pub(crate) fn compute_mesh_size(&mut self) {
1607        let my_addr = *self.tree_state.my_node_addr();
1608        let parent_id = *self.tree_state.my_declaration().parent_id();
1609        let is_root = self.tree_state.is_root();
1610
1611        let max_fpr = self.config.node.bloom.max_inbound_fpr;
1612        let mut total: f64 = 1.0; // count self
1613        let mut child_count: u32 = 0;
1614        let mut has_data = false;
1615
1616        // Parent's filter: nodes reachable upward through the tree.
1617        // If any contributing filter is above the FPR cap, we refuse to
1618        // estimate rather than substitute a partial/biased aggregate —
1619        // Node.estimated_mesh_size is already Option<u64> and consumers
1620        // (control socket, fipstop, periodic debug log) handle None.
1621        if !is_root
1622            && let Some(parent) = self.peers.get(&parent_id)
1623            && let Some(filter) = parent.inbound_filter()
1624        {
1625            match filter.estimated_count(max_fpr) {
1626                Some(n) => {
1627                    total += n;
1628                    has_data = true;
1629                }
1630                None => {
1631                    self.estimated_mesh_size = None;
1632                    return;
1633                }
1634            }
1635        }
1636
1637        // Children's filters: each child's subtree is disjoint
1638        for (peer_addr, peer) in &self.peers {
1639            if let Some(decl) = self.tree_state.peer_declaration(peer_addr)
1640                && *decl.parent_id() == my_addr
1641            {
1642                child_count += 1;
1643                if let Some(filter) = peer.inbound_filter() {
1644                    match filter.estimated_count(max_fpr) {
1645                        Some(n) => {
1646                            total += n;
1647                            has_data = true;
1648                        }
1649                        None => {
1650                            self.estimated_mesh_size = None;
1651                            return;
1652                        }
1653                    }
1654                }
1655            }
1656        }
1657
1658        if !has_data {
1659            self.estimated_mesh_size = None;
1660            return;
1661        }
1662
1663        let size = total.round() as u64;
1664        self.estimated_mesh_size = Some(size);
1665
1666        // Periodic logging (reuse MMP default interval: 30s)
1667        let now = std::time::Instant::now();
1668        let should_log = match self.last_mesh_size_log {
1669            None => true,
1670            Some(last) => {
1671                now.duration_since(last)
1672                    >= std::time::Duration::from_secs(self.config.node.mmp.log_interval_secs)
1673            }
1674        };
1675        if should_log {
1676            tracing::debug!(
1677                estimated_mesh_size = size,
1678                peers = self.peers.len(),
1679                children = child_count,
1680                "Mesh size estimate"
1681            );
1682            self.last_mesh_size_log = Some(now);
1683        }
1684    }
1685
1686    // === Coord Cache ===
1687
1688    /// Get the coordinate cache.
1689    pub fn coord_cache(&self) -> &CoordCache {
1690        &self.coord_cache
1691    }
1692
1693    /// Get mutable coordinate cache.
1694    pub fn coord_cache_mut(&mut self) -> &mut CoordCache {
1695        &mut self.coord_cache
1696    }
1697
1698    // === Node Statistics ===
1699
1700    /// Get the node statistics.
1701    pub fn stats(&self) -> &stats::NodeStats {
1702        &self.stats
1703    }
1704
1705    /// Get mutable node statistics.
1706    pub(crate) fn stats_mut(&mut self) -> &mut stats::NodeStats {
1707        &mut self.stats
1708    }
1709
1710    /// Get the stats history collector.
1711    pub fn stats_history(&self) -> &stats_history::StatsHistory {
1712        &self.stats_history
1713    }
1714
1715    /// Sample the current node state into the stats history ring.
1716    /// Called once per tick from the RX loop.
1717    pub(crate) fn record_stats_history(&mut self) {
1718        let fwd = &self.stats.forwarding;
1719        let peers_with_mmp: Vec<f64> = self
1720            .peers
1721            .values()
1722            .filter_map(|p| p.mmp().map(|m| m.metrics.loss_rate()))
1723            .collect();
1724        let loss_rate = if peers_with_mmp.is_empty() {
1725            0.0
1726        } else {
1727            peers_with_mmp.iter().sum::<f64>() / peers_with_mmp.len() as f64
1728        };
1729
1730        let snap = stats_history::Snapshot {
1731            mesh_size: self.estimated_mesh_size,
1732            tree_depth: self.tree_state.my_coords().depth() as u32,
1733            peer_count: self.peers.len() as u64,
1734            parent_switches_total: self.stats.tree.parent_switches,
1735            bytes_in_total: fwd.received_bytes,
1736            bytes_out_total: fwd.forwarded_bytes + fwd.originated_bytes,
1737            packets_in_total: fwd.received_packets,
1738            packets_out_total: fwd.forwarded_packets + fwd.originated_packets,
1739            loss_rate,
1740            active_sessions: self.sessions.len() as u64,
1741        };
1742
1743        let now = std::time::Instant::now();
1744        let peer_snaps: Vec<stats_history::PeerSnapshot> = self
1745            .peers
1746            .values()
1747            .map(|p| {
1748                let stats = p.link_stats();
1749                let (srtt_ms, loss_rate, ecn_ce) = match p.mmp() {
1750                    Some(m) => (
1751                        m.metrics.srtt_ms(),
1752                        Some(m.metrics.loss_rate()),
1753                        m.receiver.ecn_ce_count() as u64,
1754                    ),
1755                    None => (None, None, 0),
1756                };
1757                stats_history::PeerSnapshot {
1758                    node_addr: *p.node_addr(),
1759                    last_seen: now,
1760                    srtt_ms,
1761                    loss_rate,
1762                    bytes_in_total: stats.bytes_recv,
1763                    bytes_out_total: stats.bytes_sent,
1764                    packets_in_total: stats.packets_recv,
1765                    packets_out_total: stats.packets_sent,
1766                    ecn_ce_total: ecn_ce,
1767                }
1768            })
1769            .collect();
1770
1771        self.stats_history.tick(now, &snap, &peer_snaps);
1772    }
1773
1774    // === TUN Interface ===
1775
1776    /// Get the TUN state.
1777    pub fn tun_state(&self) -> TunState {
1778        self.tun_state
1779    }
1780
1781    /// Get the TUN interface name, if active.
1782    pub fn tun_name(&self) -> Option<&str> {
1783        self.tun_name.as_deref()
1784    }
1785
1786    // === Resource Limits ===
1787
1788    /// Set the maximum number of connections (handshake phase).
1789    pub fn set_max_connections(&mut self, max: usize) {
1790        self.max_connections = max;
1791    }
1792
1793    /// Set the maximum number of peers (authenticated).
1794    pub fn set_max_peers(&mut self, max: usize) {
1795        self.max_peers = max;
1796    }
1797
1798    /// Set the maximum number of links.
1799    pub fn set_max_links(&mut self, max: usize) {
1800        self.max_links = max;
1801    }
1802
1803    // === Counts ===
1804
1805    /// Number of pending connections (handshake in progress).
1806    pub fn connection_count(&self) -> usize {
1807        self.connections.len()
1808    }
1809
1810    /// Number of authenticated peers.
1811    pub fn peer_count(&self) -> usize {
1812        self.peers.len()
1813    }
1814
1815    /// Number of active links.
1816    pub fn link_count(&self) -> usize {
1817        self.links.len()
1818    }
1819
1820    /// Number of active transports.
1821    pub fn transport_count(&self) -> usize {
1822        self.transports.len()
1823    }
1824
1825    // === Transport Management ===
1826
1827    /// Allocate a new transport ID.
1828    pub fn allocate_transport_id(&mut self) -> TransportId {
1829        let id = TransportId::new(self.next_transport_id);
1830        self.next_transport_id += 1;
1831        id
1832    }
1833
1834    /// Get a transport by ID.
1835    pub fn get_transport(&self, id: &TransportId) -> Option<&TransportHandle> {
1836        self.transports.get(id)
1837    }
1838
1839    /// Get mutable transport by ID.
1840    pub fn get_transport_mut(&mut self, id: &TransportId) -> Option<&mut TransportHandle> {
1841        self.transports.get_mut(id)
1842    }
1843
1844    /// Iterate over transport IDs.
1845    pub fn transport_ids(&self) -> impl Iterator<Item = &TransportId> {
1846        self.transports.keys()
1847    }
1848
1849    /// Get the packet receiver for the event loop.
1850    pub fn packet_rx(&mut self) -> Option<&mut PacketRx> {
1851        self.packet_rx.as_mut()
1852    }
1853
1854    // === Link Management ===
1855
1856    /// Allocate a new link ID.
1857    pub fn allocate_link_id(&mut self) -> LinkId {
1858        let id = LinkId::new(self.next_link_id);
1859        self.next_link_id += 1;
1860        id
1861    }
1862
1863    /// Add a link.
1864    pub fn add_link(&mut self, link: Link) -> Result<(), NodeError> {
1865        if self.max_links > 0 && self.links.len() >= self.max_links {
1866            return Err(NodeError::MaxLinksExceeded {
1867                max: self.max_links,
1868            });
1869        }
1870        let link_id = link.link_id();
1871        let transport_id = link.transport_id();
1872        let remote_addr = link.remote_addr().clone();
1873
1874        self.links.insert(link_id, link);
1875        self.addr_to_link
1876            .insert((transport_id, remote_addr), link_id);
1877        Ok(())
1878    }
1879
1880    /// Get a link by ID.
1881    pub fn get_link(&self, link_id: &LinkId) -> Option<&Link> {
1882        self.links.get(link_id)
1883    }
1884
1885    /// Get a mutable link by ID.
1886    pub fn get_link_mut(&mut self, link_id: &LinkId) -> Option<&mut Link> {
1887        self.links.get_mut(link_id)
1888    }
1889
1890    /// Find link ID by transport address.
1891    pub fn find_link_by_addr(
1892        &self,
1893        transport_id: TransportId,
1894        addr: &TransportAddr,
1895    ) -> Option<LinkId> {
1896        self.addr_to_link
1897            .get(&(transport_id, addr.clone()))
1898            .copied()
1899    }
1900
1901    /// Remove a link.
1902    ///
1903    /// Only removes the addr_to_link reverse lookup if it still points to this
1904    /// link. In cross-connection scenarios, a newer link may have replaced the
1905    /// entry for the same address.
1906    pub fn remove_link(&mut self, link_id: &LinkId) -> Option<Link> {
1907        if let Some(link) = self.links.remove(link_id) {
1908            // Clean up reverse lookup only if it still maps to this link
1909            let key = (link.transport_id(), link.remote_addr().clone());
1910            if self.addr_to_link.get(&key) == Some(link_id) {
1911                self.addr_to_link.remove(&key);
1912            }
1913            Some(link)
1914        } else {
1915            None
1916        }
1917    }
1918
1919    pub(crate) fn cleanup_bootstrap_transport_if_unused(&mut self, transport_id: TransportId) {
1920        if !self.bootstrap_transports.contains(&transport_id) {
1921            return;
1922        }
1923
1924        let transport_in_use = self
1925            .links
1926            .values()
1927            .any(|link| link.transport_id() == transport_id)
1928            || self
1929                .connections
1930                .values()
1931                .any(|conn| conn.transport_id() == Some(transport_id))
1932            || self
1933                .peers
1934                .values()
1935                .any(|peer| peer.transport_id() == Some(transport_id))
1936            || self
1937                .pending_connects
1938                .iter()
1939                .any(|pending| pending.transport_id == transport_id);
1940
1941        if transport_in_use {
1942            return;
1943        }
1944
1945        tracing::debug!(
1946            transport_id = %transport_id,
1947            "bootstrap transport has no remaining references; dropping"
1948        );
1949
1950        self.bootstrap_transports.remove(&transport_id);
1951        self.bootstrap_transport_npubs.remove(&transport_id);
1952        self.transport_drops.remove(&transport_id);
1953        self.transports.remove(&transport_id);
1954    }
1955
1956    /// Iterate over all links.
1957    pub fn links(&self) -> impl Iterator<Item = &Link> {
1958        self.links.values()
1959    }
1960
1961    // === Connection Management (Handshake Phase) ===
1962
1963    /// Add a pending connection.
1964    pub fn add_connection(&mut self, connection: PeerConnection) -> Result<(), NodeError> {
1965        let link_id = connection.link_id();
1966
1967        if self.connections.contains_key(&link_id) {
1968            return Err(NodeError::ConnectionAlreadyExists(link_id));
1969        }
1970
1971        if self.max_connections > 0 && self.connections.len() >= self.max_connections {
1972            return Err(NodeError::MaxConnectionsExceeded {
1973                max: self.max_connections,
1974            });
1975        }
1976
1977        self.connections.insert(link_id, connection);
1978        Ok(())
1979    }
1980
1981    /// Get a connection by LinkId.
1982    pub fn get_connection(&self, link_id: &LinkId) -> Option<&PeerConnection> {
1983        self.connections.get(link_id)
1984    }
1985
1986    /// Get a mutable connection by LinkId.
1987    pub fn get_connection_mut(&mut self, link_id: &LinkId) -> Option<&mut PeerConnection> {
1988        self.connections.get_mut(link_id)
1989    }
1990
1991    /// Remove a connection.
1992    pub fn remove_connection(&mut self, link_id: &LinkId) -> Option<PeerConnection> {
1993        self.connections.remove(link_id)
1994    }
1995
1996    /// Iterate over all connections.
1997    pub fn connections(&self) -> impl Iterator<Item = &PeerConnection> {
1998        self.connections.values()
1999    }
2000
2001    // === Peer Management (Active Phase) ===
2002
2003    /// Get a peer by NodeAddr.
2004    pub fn get_peer(&self, node_addr: &NodeAddr) -> Option<&ActivePeer> {
2005        self.peers.get(node_addr)
2006    }
2007
2008    /// Get a mutable peer by NodeAddr.
2009    pub fn get_peer_mut(&mut self, node_addr: &NodeAddr) -> Option<&mut ActivePeer> {
2010        self.peers.get_mut(node_addr)
2011    }
2012
2013    /// Remove a peer.
2014    pub fn remove_peer(&mut self, node_addr: &NodeAddr) -> Option<ActivePeer> {
2015        self.peers.remove(node_addr)
2016    }
2017
2018    /// Iterate over all peers.
2019    pub fn peers(&self) -> impl Iterator<Item = &ActivePeer> {
2020        self.peers.values()
2021    }
2022
2023    /// Reference to the Nostr discovery handle if discovery is enabled.
2024    /// Used by control queries (`show_peers` per-peer Nostr-traversal
2025    /// state) to read failure-state without taking shared ownership.
2026    pub fn nostr_discovery_handle(&self) -> Option<&crate::discovery::nostr::NostrDiscovery> {
2027        self.nostr_discovery.as_deref()
2028    }
2029
2030    /// Iterate over all peer node IDs.
2031    pub fn peer_ids(&self) -> impl Iterator<Item = &NodeAddr> {
2032        self.peers.keys()
2033    }
2034
2035    /// Iterate over peers that can send traffic.
2036    pub fn sendable_peers(&self) -> impl Iterator<Item = &ActivePeer> {
2037        self.peers.values().filter(|p| p.can_send())
2038    }
2039
2040    /// Number of peers that can send traffic.
2041    pub fn sendable_peer_count(&self) -> usize {
2042        self.peers.values().filter(|p| p.can_send()).count()
2043    }
2044
2045    pub(crate) fn set_discovery_fallback_transit_allowed(
2046        &mut self,
2047        peer_addr: NodeAddr,
2048        allowed: bool,
2049    ) {
2050        if allowed {
2051            self.discovery_fallback_transit_blocked_peers
2052                .remove(&peer_addr);
2053        } else {
2054            self.discovery_fallback_transit_blocked_peers
2055                .insert(peer_addr);
2056        }
2057    }
2058
2059    pub(crate) fn configured_discovery_fallback_transit(
2060        &self,
2061        peer_addr: &NodeAddr,
2062    ) -> Option<bool> {
2063        self.config.peers().iter().find_map(|peer| {
2064            PeerIdentity::from_npub(&peer.npub)
2065                .ok()
2066                .filter(|identity| identity.node_addr() == peer_addr)
2067                .map(|_| peer.discovery_fallback_transit)
2068        })
2069    }
2070
2071    pub(crate) fn discovery_fallback_transit_for_promotion(&self, peer_addr: &NodeAddr) -> bool {
2072        if let Some(retry_state) = self.retry_pending.get(peer_addr) {
2073            return retry_state.peer_config.discovery_fallback_transit;
2074        }
2075
2076        if let Some(allowed) = self.configured_discovery_fallback_transit(peer_addr) {
2077            return allowed;
2078        }
2079
2080        self.config.node.discovery.nostr.policy != crate::config::NostrDiscoveryPolicy::Open
2081    }
2082
2083    // === End-to-End Sessions ===
2084
2085    /// Get a session by remote NodeAddr.
2086    /// Disable the discovery forward rate limiter (for tests).
2087    #[cfg(test)]
2088    pub(crate) fn disable_discovery_forward_rate_limit(&mut self) {
2089        self.discovery_forward_limiter
2090            .set_interval(std::time::Duration::ZERO);
2091    }
2092
2093    #[cfg(test)]
2094    pub(crate) fn get_session(&self, remote: &NodeAddr) -> Option<&SessionEntry> {
2095        self.sessions.get(remote)
2096    }
2097
2098    /// Get a mutable session by remote NodeAddr.
2099    #[cfg(test)]
2100    pub(crate) fn get_session_mut(&mut self, remote: &NodeAddr) -> Option<&mut SessionEntry> {
2101        self.sessions.get_mut(remote)
2102    }
2103
2104    /// Remove a session.
2105    #[cfg(test)]
2106    pub(crate) fn remove_session(&mut self, remote: &NodeAddr) -> Option<SessionEntry> {
2107        self.sessions.remove(remote)
2108    }
2109
2110    /// Read the path_mtu_lookup entry for a destination FipsAddress.
2111    #[cfg(test)]
2112    pub(crate) fn path_mtu_lookup_get(&self, fips_addr: &crate::FipsAddress) -> Option<u16> {
2113        self.path_mtu_lookup
2114            .read()
2115            .ok()
2116            .and_then(|map| map.get(fips_addr).copied())
2117    }
2118
2119    /// Write a path_mtu_lookup entry directly (for tests that pre-seed the map).
2120    #[cfg(test)]
2121    pub(crate) fn path_mtu_lookup_insert(&self, fips_addr: crate::FipsAddress, mtu: u16) {
2122        if let Ok(mut map) = self.path_mtu_lookup.write() {
2123            map.insert(fips_addr, mtu);
2124        }
2125    }
2126
2127    /// Number of end-to-end sessions.
2128    pub fn session_count(&self) -> usize {
2129        self.sessions.len()
2130    }
2131
2132    /// Iterate over all session entries (for control queries).
2133    pub(crate) fn session_entries(&self) -> impl Iterator<Item = (&NodeAddr, &SessionEntry)> {
2134        self.sessions.iter()
2135    }
2136
2137    // === Identity Cache ===
2138
2139    /// Register a node in the identity cache for FipsAddress → NodeAddr lookup.
2140    pub(crate) fn register_identity(
2141        &mut self,
2142        node_addr: NodeAddr,
2143        pubkey: secp256k1::PublicKey,
2144    ) -> bool {
2145        let mut prefix = [0u8; 15];
2146        prefix.copy_from_slice(&node_addr.as_bytes()[0..15]);
2147        if let Some(entry) = self.identity_cache.get(&prefix)
2148            && entry.node_addr == node_addr
2149            && entry.pubkey == pubkey
2150        {
2151            // Endpoint sends pass the same PeerIdentity on every packet. Once
2152            // validated, avoid re-deriving NodeAddr from the public key in the
2153            // data path; that hash showed up in macOS sender profiles.
2154            return true;
2155        }
2156
2157        let (xonly, _) = pubkey.x_only_public_key();
2158        let derived_node_addr = NodeAddr::from_pubkey(&xonly);
2159        if derived_node_addr != node_addr {
2160            debug!(
2161                claimed_node_addr = %node_addr,
2162                derived_node_addr = %derived_node_addr,
2163                "Rejected identity cache entry with mismatched public key"
2164            );
2165            return false;
2166        }
2167
2168        let now_ms = Self::now_ms();
2169        if let Some(entry) = self.identity_cache.get_mut(&prefix)
2170            && entry.node_addr == node_addr
2171        {
2172            entry.pubkey = pubkey;
2173            entry.last_seen_ms = now_ms;
2174            return true;
2175        }
2176
2177        let npub = encode_npub(&xonly);
2178        self.identity_cache.insert(
2179            prefix,
2180            IdentityCacheEntry::new(node_addr, pubkey, npub, now_ms),
2181        );
2182        // LRU eviction
2183        let max = self.config.node.cache.identity_size;
2184        if self.identity_cache.len() > max
2185            && let Some(oldest_key) = self
2186                .identity_cache
2187                .iter()
2188                .min_by_key(|(_, entry)| entry.last_seen_ms)
2189                .map(|(k, _)| *k)
2190        {
2191            self.identity_cache.remove(&oldest_key);
2192        }
2193        true
2194    }
2195
2196    /// Look up a destination by FipsAddress prefix (bytes 1-15 of the IPv6 address).
2197    pub(crate) fn lookup_by_fips_prefix(
2198        &mut self,
2199        prefix: &[u8; 15],
2200    ) -> Option<(NodeAddr, secp256k1::PublicKey)> {
2201        if let Some(entry) = self.identity_cache.get_mut(prefix) {
2202            entry.last_seen_ms = Self::now_ms(); // LRU touch
2203            Some((entry.node_addr, entry.pubkey))
2204        } else {
2205            None
2206        }
2207    }
2208
2209    /// Check if a node's identity is in the cache (without LRU touch).
2210    pub(crate) fn has_cached_identity(&self, addr: &NodeAddr) -> bool {
2211        let mut prefix = [0u8; 15];
2212        prefix.copy_from_slice(&addr.as_bytes()[0..15]);
2213        self.identity_cache.contains_key(&prefix)
2214    }
2215
2216    /// Number of identity cache entries.
2217    pub fn identity_cache_len(&self) -> usize {
2218        self.identity_cache.len()
2219    }
2220
2221    /// Iterate over identity cache entries.
2222    ///
2223    /// Returns `(NodeAddr, PublicKey, last_seen_ms)` for each cached identity.
2224    /// Used by the `show_identity_cache` control query.
2225    pub fn identity_cache_iter(
2226        &self,
2227    ) -> impl Iterator<Item = (&NodeAddr, &secp256k1::PublicKey, u64)> {
2228        self.identity_cache
2229            .values()
2230            .map(|entry| (&entry.node_addr, &entry.pubkey, entry.last_seen_ms))
2231    }
2232
2233    /// Configured maximum identity cache size.
2234    pub fn identity_cache_max(&self) -> usize {
2235        self.config.node.cache.identity_size
2236    }
2237
2238    /// Number of pending discovery lookups.
2239    pub fn pending_lookup_count(&self) -> usize {
2240        self.pending_lookups.len()
2241    }
2242
2243    /// Iterate over pending discovery lookups for diagnostics.
2244    pub fn pending_lookups_iter(
2245        &self,
2246    ) -> impl Iterator<Item = (&NodeAddr, &handlers::discovery::PendingLookup)> {
2247        self.pending_lookups.iter()
2248    }
2249
2250    /// Number of recent discovery requests tracked.
2251    pub fn recent_request_count(&self) -> usize {
2252        self.recent_requests.len()
2253    }
2254
2255    /// Count of destinations with queued TUN packets awaiting session setup.
2256    pub fn pending_tun_destinations(&self) -> usize {
2257        self.pending_tun_packets.len()
2258    }
2259
2260    /// Total TUN packets queued across all destinations.
2261    pub fn pending_tun_total_packets(&self) -> usize {
2262        self.pending_tun_packets.values().map(|q| q.len()).sum()
2263    }
2264
2265    /// Iterate over retry state for diagnostics.
2266    pub fn retry_state_iter(&self) -> impl Iterator<Item = (&NodeAddr, &retry::RetryState)> {
2267        self.retry_pending.iter()
2268    }
2269
2270    // === Routing ===
2271
2272    /// Check if a peer is a tree neighbor (parent or child in the spanning tree).
2273    ///
2274    /// Returns true if the peer is our current tree parent, or if the peer
2275    /// has declared us as their parent (making them our child).
2276    pub(crate) fn is_tree_peer(&self, peer_addr: &NodeAddr) -> bool {
2277        // Peer is our parent
2278        if !self.tree_state.is_root() && self.tree_state.my_declaration().parent_id() == peer_addr {
2279            return true;
2280        }
2281        // Peer is our child (their declaration names us as parent)
2282        if let Some(decl) = self.tree_state.peer_declaration(peer_addr)
2283            && decl.parent_id() == self.node_addr()
2284        {
2285            return true;
2286        }
2287        false
2288    }
2289
2290    /// Find next hop for a destination node address.
2291    ///
2292    /// Routing priority:
2293    /// 1. Destination is self → `None` (local delivery)
2294    /// 2. Destination is a direct peer → that peer
2295    /// 3. Reply-learned routes in `reply_learned` mode. These are locally
2296    ///    observed reverse paths, selected with weighted multipath plus
2297    ///    periodic coordinate/tree exploration.
2298    /// 4. Bloom filter candidates with cached dest coords → among peers whose
2299    ///    bloom filter contains the destination, pick the one that minimizes
2300    ///    tree distance to the destination, with
2301    ///    `(link_cost, tree_distance_to_dest, node_addr)` tie-breaking.
2302    ///    The self-distance check ensures only peers strictly closer to the
2303    ///    destination than us are considered (prevents routing loops).
2304    /// 5. Greedy tree routing fallback (requires cached dest coords)
2305    /// 6. No route → `None`
2306    ///
2307    /// Both the bloom filter and tree routing paths require cached destination
2308    /// coordinates (checked in `coord_cache`). Without coordinates, the node
2309    /// cannot make loop-free forwarding decisions. The caller should signal
2310    /// `CoordsRequired` back to the source when `None` is returned for a
2311    /// non-local destination.
2312    pub fn find_next_hop(&mut self, dest_node_addr: &NodeAddr) -> Option<&ActivePeer> {
2313        // 1. Local delivery
2314        if dest_node_addr == self.node_addr() {
2315            return None;
2316        }
2317
2318        // 2. Healthy direct peer. Stale direct links remain usable, but in
2319        // reply-learned mode they must not hide a live mesh route learned from
2320        // recent traffic or discovery.
2321        let direct_peer_can_send = self
2322            .peers
2323            .get(dest_node_addr)
2324            .is_some_and(|peer| peer.can_send());
2325        if let Some(peer) = self.peers.get(dest_node_addr)
2326            && peer.is_healthy()
2327        {
2328            return Some(peer);
2329        }
2330
2331        let now_ms = Self::now_ms();
2332
2333        let sendable_learned_peers = if self.config.node.routing.mode == RoutingMode::ReplyLearned {
2334            Some(
2335                self.peers
2336                    .iter()
2337                    .filter(|(_, peer)| peer.can_send())
2338                    .map(|(addr, _)| *addr)
2339                    .collect::<HashSet<_>>(),
2340            )
2341        } else {
2342            None
2343        };
2344
2345        // 3. Optional reply-learned routing. These entries are not peer
2346        // claims; they are local observations of which peer carried traffic
2347        // or a verified lookup response back from the destination. Most
2348        // packets use weighted multipath over learned routes, but periodic
2349        // fallback exploration lets coord/bloom/tree routes discover better
2350        // candidates.
2351        let explore_fallback = sendable_learned_peers.as_ref().is_some_and(|sendable| {
2352            self.learned_routes.should_explore_fallback(
2353                dest_node_addr,
2354                now_ms,
2355                self.config.node.routing.learned_fallback_explore_interval,
2356                |addr| sendable.contains(addr),
2357            )
2358        });
2359        if let Some(sendable) = &sendable_learned_peers
2360            && !explore_fallback
2361            && let Some(next_hop_addr) =
2362                self.learned_routes
2363                    .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
2364        {
2365            return self.peers.get(&next_hop_addr);
2366        }
2367
2368        // Look up cached destination coordinates (required by both bloom and tree paths).
2369        let Some(dest_coords) = self
2370            .coord_cache
2371            .get_and_touch(dest_node_addr, now_ms)
2372            .cloned()
2373        else {
2374            if let Some(sendable) = &sendable_learned_peers
2375                && let Some(next_hop_addr) =
2376                    self.learned_routes
2377                        .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
2378            {
2379                return self.peers.get(&next_hop_addr);
2380            }
2381            if direct_peer_can_send {
2382                return self.peers.get(dest_node_addr);
2383            }
2384            return None;
2385        };
2386
2387        // 4. Bloom filter candidates — requires dest_coords for loop-free selection.
2388        //    If no candidate is strictly closer, fall through to tree routing.
2389        let coordinate_route_addr = {
2390            let candidates: Vec<&ActivePeer> = self.destination_in_filters(dest_node_addr);
2391            if !candidates.is_empty() {
2392                self.select_best_candidate(&candidates, &dest_coords)
2393                    .map(|peer| *peer.node_addr())
2394            } else {
2395                None
2396            }
2397        };
2398        if let Some(next_hop_addr) = coordinate_route_addr {
2399            return self.peers.get(&next_hop_addr);
2400        }
2401
2402        // 5. Greedy tree routing fallback
2403        let tree_route_addr = self
2404            .tree_state
2405            .find_next_hop(&dest_coords)
2406            .filter(|next_hop_id| {
2407                self.peers
2408                    .get(next_hop_id)
2409                    .is_some_and(|peer| peer.can_send())
2410            });
2411        if let Some(next_hop_addr) = tree_route_addr {
2412            return self.peers.get(&next_hop_addr);
2413        }
2414        if explore_fallback {
2415            return sendable_learned_peers.as_ref().and_then(|sendable| {
2416                self.learned_routes
2417                    .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
2418                    .and_then(|next_hop_addr| self.peers.get(&next_hop_addr))
2419            });
2420        }
2421
2422        if let Some(sendable) = &sendable_learned_peers
2423            && let Some(next_hop_addr) =
2424                self.learned_routes
2425                    .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
2426        {
2427            return self.peers.get(&next_hop_addr);
2428        }
2429
2430        if direct_peer_can_send {
2431            return self.peers.get(dest_node_addr);
2432        }
2433
2434        None
2435    }
2436
2437    pub(in crate::node) fn learn_reverse_route(
2438        &mut self,
2439        destination: NodeAddr,
2440        next_hop: NodeAddr,
2441    ) {
2442        if self.config.node.routing.mode != RoutingMode::ReplyLearned
2443            || destination == *self.node_addr()
2444        {
2445            return;
2446        }
2447        let now_ms = Self::now_ms();
2448        self.learned_routes.learn(
2449            destination,
2450            next_hop,
2451            now_ms,
2452            self.config.node.routing.learned_ttl_secs,
2453            self.config.node.routing.max_learned_routes_per_dest,
2454        );
2455    }
2456
2457    pub(in crate::node) fn record_route_failure(
2458        &mut self,
2459        destination: NodeAddr,
2460        next_hop: NodeAddr,
2461    ) {
2462        if self.config.node.routing.mode != RoutingMode::ReplyLearned {
2463            return;
2464        }
2465        self.learned_routes.record_failure(&destination, &next_hop);
2466    }
2467
2468    pub(crate) fn learned_route_table_snapshot(&self, now_ms: u64) -> LearnedRouteTableSnapshot {
2469        self.learned_routes.snapshot(now_ms)
2470    }
2471
2472    pub(in crate::node) fn purge_learned_routes(&mut self, now_ms: u64) {
2473        self.learned_routes.purge_expired(now_ms);
2474    }
2475
2476    /// Select the best peer from a set of bloom filter candidates.
2477    ///
2478    /// Uses distance from each candidate's tree coordinates to the destination
2479    /// as the primary metric (after link_cost). Only selects peers that are
2480    /// strictly closer to the destination than we are (self-distance check
2481    /// prevents routing loops).
2482    ///
2483    /// Ordering: `(link_cost, distance_to_dest, node_addr)`.
2484    fn select_best_candidate<'a>(
2485        &'a self,
2486        candidates: &[&'a ActivePeer],
2487        dest_coords: &crate::tree::TreeCoordinate,
2488    ) -> Option<&'a ActivePeer> {
2489        let my_distance = self.tree_state.my_coords().distance_to(dest_coords);
2490
2491        let mut best: Option<(&ActivePeer, f64, usize)> = None;
2492
2493        for &candidate in candidates {
2494            if !candidate.can_send() {
2495                continue;
2496            }
2497
2498            let cost = candidate.link_cost();
2499
2500            let dist = self
2501                .tree_state
2502                .peer_coords(candidate.node_addr())
2503                .map(|pc| pc.distance_to(dest_coords))
2504                .unwrap_or(usize::MAX);
2505
2506            // Self-distance check: only consider peers strictly closer
2507            // to the destination than we are (prevents routing loops)
2508            if dist >= my_distance {
2509                continue;
2510            }
2511
2512            let dominated = match &best {
2513                None => true,
2514                Some((_, best_cost, best_dist)) => {
2515                    cost < *best_cost
2516                        || (cost == *best_cost && dist < *best_dist)
2517                        || (cost == *best_cost
2518                            && dist == *best_dist
2519                            && candidate.node_addr() < best.as_ref().unwrap().0.node_addr())
2520                }
2521            };
2522
2523            if dominated {
2524                best = Some((candidate, cost, dist));
2525            }
2526        }
2527
2528        best.map(|(peer, _, _)| peer)
2529    }
2530
2531    /// Check if a destination is in any peer's bloom filter.
2532    pub fn destination_in_filters(&self, dest: &NodeAddr) -> Vec<&ActivePeer> {
2533        self.peers.values().filter(|p| p.may_reach(dest)).collect()
2534    }
2535
2536    /// Get the TUN packet sender channel.
2537    ///
2538    /// Returns None if TUN is not active or the node hasn't been started.
2539    pub fn tun_tx(&self) -> Option<&TunTx> {
2540        self.tun_tx.as_ref()
2541    }
2542
2543    /// Attach app-owned packet I/O for embedded operation without a system TUN.
2544    ///
2545    /// This must be called before [`Node::start`] and requires `tun.enabled =
2546    /// false`. Outbound packets sent to the returned sender are processed by the
2547    /// normal session pipeline. Inbound packets delivered by FIPS sessions are
2548    /// sent to the returned receiver with source attribution.
2549    pub fn attach_external_packet_io(
2550        &mut self,
2551        capacity: usize,
2552    ) -> Result<ExternalPacketIo, NodeError> {
2553        if self.state != NodeState::Created {
2554            return Err(NodeError::Config(ConfigError::Validation(
2555                "external packet I/O must be attached before node start".to_string(),
2556            )));
2557        }
2558        if self.config.tun.enabled {
2559            return Err(NodeError::Config(ConfigError::Validation(
2560                "external packet I/O requires tun.enabled=false".to_string(),
2561            )));
2562        }
2563
2564        let capacity = capacity.max(1);
2565        let (outbound_tx, outbound_rx) = tokio::sync::mpsc::channel(capacity);
2566        let (inbound_tx, inbound_rx) = tokio::sync::mpsc::channel(capacity);
2567        self.tun_outbound_rx = Some(outbound_rx);
2568        self.external_packet_tx = Some(inbound_tx);
2569
2570        Ok(ExternalPacketIo {
2571            outbound_tx,
2572            inbound_rx,
2573        })
2574    }
2575
2576    /// Attach app-owned endpoint data I/O for embedded operation.
2577    ///
2578    /// Commands sent to the returned sender are processed by the node RX loop.
2579    /// Incoming endpoint data is emitted as source-attributed events.
2580    pub(crate) fn attach_endpoint_data_io(
2581        &mut self,
2582        capacity: usize,
2583    ) -> Result<EndpointDataIo, NodeError> {
2584        if self.state != NodeState::Created {
2585            return Err(NodeError::Config(ConfigError::Validation(
2586                "endpoint data I/O must be attached before node start".to_string(),
2587            )));
2588        }
2589
2590        let command_capacity = endpoint_data_command_capacity(capacity);
2591        let (command_tx, command_rx) = tokio::sync::mpsc::channel(command_capacity);
2592        // Inbound endpoint-data events use an unbounded channel — see
2593        // `EndpointDataIo::event_rx` docs for the rationale (kills the
2594        // per-packet semaphore + the cross-task relay task that used to
2595        // sit on top of this channel).
2596        let (event_tx, event_rx) = tokio::sync::mpsc::unbounded_channel();
2597        self.endpoint_command_rx = Some(command_rx);
2598        self.endpoint_event_tx = Some(event_tx.clone());
2599
2600        Ok(EndpointDataIo {
2601            command_tx,
2602            event_rx,
2603            event_tx,
2604        })
2605    }
2606
2607    pub(crate) fn pubkey_for_node_addr(&self, addr: &NodeAddr) -> Option<secp256k1::PublicKey> {
2608        let mut prefix = [0u8; 15];
2609        prefix.copy_from_slice(&addr.as_bytes()[0..15]);
2610        self.identity_cache
2611            .get(&prefix)
2612            .filter(|entry| &entry.node_addr == addr)
2613            .map(|entry| entry.pubkey)
2614    }
2615
2616    pub(crate) fn npub_for_node_addr(&self, addr: &NodeAddr) -> Option<String> {
2617        let mut prefix = [0u8; 15];
2618        prefix.copy_from_slice(&addr.as_bytes()[0..15]);
2619        self.identity_cache
2620            .get(&prefix)
2621            .filter(|entry| &entry.node_addr == addr)
2622            .map(|entry| entry.npub.clone())
2623    }
2624
2625    pub(in crate::node) fn deliver_external_ipv6_packet(
2626        &self,
2627        src_addr: &NodeAddr,
2628        packet: Vec<u8>,
2629    ) {
2630        let Some(external_packet_tx) = &self.external_packet_tx else {
2631            return;
2632        };
2633        if packet.len() < 40 {
2634            return;
2635        }
2636        let Ok(destination) = FipsAddress::from_slice(&packet[24..40]) else {
2637            return;
2638        };
2639        let delivered = NodeDeliveredPacket {
2640            source_node_addr: *src_addr,
2641            source_npub: self.npub_for_node_addr(src_addr),
2642            destination,
2643            packet,
2644        };
2645        if let Err(error) = external_packet_tx.try_send(delivered) {
2646            debug!(error = %error, "Failed to deliver packet to external app sink");
2647        }
2648    }
2649
2650    // === Sending ===
2651
2652    /// Encrypt and send a link-layer message to an authenticated peer.
2653    ///
2654    /// The plaintext should include the message type byte followed by the
2655    /// message-specific payload (e.g., `[0x50, reason]` for Disconnect).
2656    ///
2657    /// The send path prepends a 4-byte session-relative timestamp (inner
2658    /// header) before encryption. The full 16-byte outer header is used
2659    /// as AAD for the AEAD construction.
2660    ///
2661    /// This is the standard path for sending any link-layer control message
2662    /// to a peer over their encrypted Noise session.
2663    pub(super) async fn send_encrypted_link_message(
2664        &mut self,
2665        node_addr: &NodeAddr,
2666        plaintext: &[u8],
2667    ) -> Result<(), NodeError> {
2668        self.send_encrypted_link_message_with_ce(node_addr, plaintext, false)
2669            .await
2670    }
2671
2672    /// Update the local-outbound-broken signal from a `transport.send`
2673    /// outcome. Sets `last_local_send_failure_at` on local-side io
2674    /// errors (NetworkUnreachable / HostUnreachable / AddrNotAvailable);
2675    /// clears it on success. The reaper consults this in
2676    /// `check_link_heartbeats` to switch to `fast_link_dead_timeout_secs`.
2677    pub(in crate::node) fn note_local_send_outcome(
2678        &mut self,
2679        result: &Result<usize, TransportError>,
2680    ) {
2681        match result {
2682            Ok(_) => {
2683                if self.last_local_send_failure_at.is_some() {
2684                    self.last_local_send_failure_at = None;
2685                }
2686            }
2687            Err(TransportError::Io(e))
2688                if matches!(
2689                    e.kind(),
2690                    std::io::ErrorKind::NetworkUnreachable
2691                        | std::io::ErrorKind::HostUnreachable
2692                        | std::io::ErrorKind::AddrNotAvailable
2693                ) =>
2694            {
2695                self.last_local_send_failure_at = Some(std::time::Instant::now());
2696            }
2697            Err(_) => {}
2698        }
2699    }
2700
2701    /// Returns the wall-clock instant of the most recent observed local
2702    /// outbound failure, if any. Used by the link-dead reaper.
2703    pub(in crate::node) fn last_local_send_failure_at(&self) -> Option<std::time::Instant> {
2704        self.last_local_send_failure_at
2705    }
2706
2707    /// Like `send_encrypted_link_message` but allows setting the FMP CE flag.
2708    ///
2709    /// Used by the forwarding path to relay congestion signals hop-by-hop.
2710    pub(super) async fn send_encrypted_link_message_with_ce(
2711        &mut self,
2712        node_addr: &NodeAddr,
2713        plaintext: &[u8],
2714        ce_flag: bool,
2715    ) -> Result<(), NodeError> {
2716        let peer = self
2717            .peers
2718            .get_mut(node_addr)
2719            .ok_or(NodeError::PeerNotFound(*node_addr))?;
2720
2721        let their_index = peer.their_index().ok_or_else(|| NodeError::SendFailed {
2722            node_addr: *node_addr,
2723            reason: "no their_index".into(),
2724        })?;
2725        let transport_id = peer.transport_id().ok_or_else(|| NodeError::SendFailed {
2726            node_addr: *node_addr,
2727            reason: "no transport_id".into(),
2728        })?;
2729        let remote_addr = peer
2730            .current_addr()
2731            .cloned()
2732            .ok_or_else(|| NodeError::SendFailed {
2733                node_addr: *node_addr,
2734                reason: "no current_addr".into(),
2735            })?;
2736        #[cfg(any(target_os = "linux", target_os = "macos"))]
2737        let connected_socket = peer.connected_udp();
2738
2739        // Prepend 4-byte session-relative timestamp (inner header)
2740        let timestamp_ms = peer.session_elapsed_ms();
2741
2742        // MMP: read spin bit value before entering session borrow
2743        let sp_flag = peer.mmp().map(|mmp| mmp.spin_bit.tx_bit()).unwrap_or(false);
2744        let mut flags = if sp_flag { FLAG_SP } else { 0 };
2745        if ce_flag {
2746            flags |= FLAG_CE;
2747        }
2748        if peer.current_k_bit() {
2749            flags |= FLAG_KEY_EPOCH;
2750        }
2751
2752        let session = peer
2753            .noise_session_mut()
2754            .ok_or_else(|| NodeError::SendFailed {
2755                node_addr: *node_addr,
2756                reason: "no noise session".into(),
2757            })?;
2758
2759        // Build 16-byte outer header upfront. The inner-plaintext
2760        // layout is `[ts:4 LE][plaintext...]`, so its length is exactly
2761        // `INNER_TS_LEN + plaintext.len()` — no need to build the Vec
2762        // just to measure it. The worker path uses this length to size
2763        // the wire buffer directly; the legacy path below still
2764        // materialises a separate `inner_plaintext` Vec for the inline
2765        // encrypt-and-send call.
2766        const INNER_TS_LEN: usize = 4;
2767        let counter = session.current_send_counter();
2768        let inner_len = INNER_TS_LEN + plaintext.len();
2769        let payload_len = inner_len as u16;
2770        let header = build_established_header(their_index, counter, flags, payload_len);
2771
2772        // **UDP send fast path.** The encrypt-worker pool is always
2773        // spawned at lifecycle start (workers = num_cpus) in
2774        // production, so this branch is taken for every authentic
2775        // send on every UDP-transported established session. The
2776        // AEAD work + sendmsg syscall run on a dedicated OS thread;
2777        // the rx_loop only builds the wire buffer + reserves the
2778        // counter inline.
2779        //
2780        // Other transport kinds (BLE, TCP, sim, ethernet) fall
2781        // through to the inline encrypt + transport.send path
2782        // below — those don't have raw-fd / sendmmsg / UDP_GSO
2783        // benefits to expose through the worker pool, so the simpler
2784        // synchronous send is the right shape for them.
2785        //
2786        // The `encrypt_workers.is_some()` check below is true in
2787        // production (lifecycle::start spawns the pool); it stays
2788        // checked rather than `expect()`-ed because unit tests
2789        // construct `Node` without calling `start()`.
2790        let transport_for_send = self
2791            .transports
2792            .get(&transport_id)
2793            .ok_or(NodeError::TransportNotFound(transport_id))?;
2794        match transport_for_send.connection_state(&remote_addr) {
2795            ConnectionState::Connected => {}
2796            other => {
2797                if matches!(other, ConnectionState::None) {
2798                    let _ = transport_for_send.connect(&remote_addr).await;
2799                }
2800                return Err(NodeError::SendFailed {
2801                    node_addr: *node_addr,
2802                    reason: format!("transport connection not ready: {:?}", other),
2803                });
2804            }
2805        }
2806        let is_udp = matches!(transport_for_send, TransportHandle::Udp(_));
2807        if let Some(workers) = self.encrypt_workers.as_ref().cloned()
2808            && is_udp
2809            && let Some(cipher_clone) = session.send_cipher_clone()
2810        {
2811            {
2812                // Reserve the counter on the session so subsequent
2813                // sends don't reuse it. `current_send_counter` only
2814                // peeks; we advance via `take_send_counter`.
2815                let reserved_counter =
2816                    session
2817                        .take_send_counter()
2818                        .map_err(|e| NodeError::SendFailed {
2819                            node_addr: *node_addr,
2820                            reason: format!("counter reservation failed: {}", e),
2821                        })?;
2822                debug_assert_eq!(reserved_counter, counter);
2823                // Re-derive the header with the now-locked-in counter
2824                // value (same value, but the call sequence is more
2825                // explicit).
2826                let header =
2827                    build_established_header(their_index, reserved_counter, flags, payload_len);
2828                let transport = transport_for_send;
2829                // Snapshot the per-peer connected UDP socket before
2830                // resolving the fallback address. On the established
2831                // steady-state path this socket already carries the
2832                // kernel peer address, so re-parsing the configured
2833                // transport address and touching the DNS cache on every
2834                // packet is pure overhead on the sender hot path.
2835                let send_target = {
2836                    if let TransportHandle::Udp(udp) = transport {
2837                        let socket_addr = {
2838                            #[cfg(any(target_os = "linux", target_os = "macos"))]
2839                            {
2840                                match connected_socket.as_ref() {
2841                                    Some(socket) => Some(socket.peer_addr()),
2842                                    None => udp.resolve_for_off_task(&remote_addr).await.ok(),
2843                                }
2844                            }
2845                            #[cfg(not(any(target_os = "linux", target_os = "macos")))]
2846                            {
2847                                udp.resolve_for_off_task(&remote_addr).await.ok()
2848                            }
2849                        };
2850                        match (udp.async_socket(), socket_addr) {
2851                            (Some(socket), Some(socket_addr)) => Some((socket, socket_addr)),
2852                            _ => None,
2853                        }
2854                    } else {
2855                        None
2856                    }
2857                };
2858                if let Some((socket, socket_addr)) = send_target {
2859                    // Build the wire buffer **directly** from
2860                    // `plaintext` with a single allocation:
2861                    //   `[16 header][4 ts][plaintext...]` with
2862                    // +16 trailing capacity for the AEAD tag.
2863                    // The worker seals `wire_buf[16..]` in
2864                    // place and appends the tag — no second
2865                    // alloc, no second memcpy.
2866                    //
2867                    // Previous design built `inner_plaintext`
2868                    // via `prepend_inner_header` (1 alloc + 1
2869                    // copy) and then let the worker memcpy
2870                    // header + plaintext into a fresh Vec
2871                    // (another alloc + copy). At ~100 kpps the
2872                    // saved alloc/copy is ~150 MB/sec of memory
2873                    // bandwidth on the hot rx_loop + worker.
2874                    let wire_capacity = ESTABLISHED_HEADER_SIZE + inner_len + 16;
2875                    let mut wire_buf = Vec::with_capacity(wire_capacity);
2876                    wire_buf.extend_from_slice(&header);
2877                    wire_buf.extend_from_slice(&timestamp_ms.to_le_bytes());
2878                    wire_buf.extend_from_slice(plaintext);
2879                    let predicted_bytes = wire_capacity;
2880                    // Stats / MMP update inline — predicted size
2881                    // is exact for ChaCha20-Poly1305 (tag is
2882                    // constant 16 bytes). When `connected_socket` is
2883                    // `Some`, the worker sends on it without a
2884                    // destination sockaddr — the kernel skips the
2885                    // per-packet sockaddr + route + neighbor resolve.
2886                    if let Some(peer) = self.peers.get_mut(node_addr) {
2887                        peer.link_stats_mut().record_sent(predicted_bytes);
2888                        if let Some(mmp) = peer.mmp_mut() {
2889                            mmp.sender
2890                                .record_sent(reserved_counter, timestamp_ms, predicted_bytes);
2891                        }
2892                    }
2893                    workers.dispatch(self::encrypt_worker::FmpSendJob {
2894                        cipher: cipher_clone,
2895                        counter: reserved_counter,
2896                        wire_buf,
2897                        fsp_seal: None,
2898                        socket,
2899                        dest_addr: socket_addr,
2900                        #[cfg(any(target_os = "linux", target_os = "macos"))]
2901                        connected_socket,
2902                        drop_on_backpressure: plaintext
2903                            .first()
2904                            .is_some_and(|ty| *ty == SessionMessageType::EndpointData.to_byte()),
2905                        queued_at: crate::perf_profile::stamp(),
2906                    });
2907                    return Ok(());
2908                }
2909            }
2910        }
2911
2912        // Inline (legacy) path: encrypt + send on the rx_loop.
2913        // Build the inner plaintext lazily here — the worker path
2914        // above never reaches this point, so the prepend_inner_header
2915        // alloc is avoided in the fast path.
2916        let inner_plaintext = prepend_inner_header(timestamp_ms, plaintext);
2917        // Encrypt with AAD binding to the outer header
2918        let ciphertext = {
2919            let _t = crate::perf_profile::Timer::start(crate::perf_profile::Stage::FmpEncrypt);
2920            session
2921                .encrypt_with_aad(&inner_plaintext, &header)
2922                .map_err(|e| NodeError::SendFailed {
2923                    node_addr: *node_addr,
2924                    reason: format!("encryption failed: {}", e),
2925                })?
2926        };
2927
2928        let wire_packet = build_encrypted(&header, &ciphertext);
2929
2930        // Re-borrow peer for stats update after sending
2931        let send_result = {
2932            let _t = crate::perf_profile::Timer::start(crate::perf_profile::Stage::UdpSend);
2933            let transport = self
2934                .transports
2935                .get(&transport_id)
2936                .ok_or(NodeError::TransportNotFound(transport_id))?;
2937            transport.send(&remote_addr, &wire_packet).await
2938        };
2939        self.note_local_send_outcome(&send_result);
2940        let bytes_sent = send_result.map_err(|e| match e {
2941            TransportError::MtuExceeded { packet_size, mtu } => NodeError::MtuExceeded {
2942                node_addr: *node_addr,
2943                packet_size,
2944                mtu,
2945            },
2946            other => NodeError::SendFailed {
2947                node_addr: *node_addr,
2948                reason: format!("transport send: {}", other),
2949            },
2950        })?;
2951
2952        // Update send statistics
2953        if let Some(peer) = self.peers.get_mut(node_addr) {
2954            peer.link_stats_mut().record_sent(bytes_sent);
2955            // MMP: record sent frame for sender report generation
2956            if let Some(mmp) = peer.mmp_mut() {
2957                mmp.sender.record_sent(counter, timestamp_ms, bytes_sent);
2958            }
2959        }
2960
2961        Ok(())
2962    }
2963}
2964
2965impl fmt::Debug for Node {
2966    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2967        f.debug_struct("Node")
2968            .field("node_addr", self.node_addr())
2969            .field("state", &self.state)
2970            .field("is_leaf_only", &self.is_leaf_only)
2971            .field("connections", &self.connection_count())
2972            .field("peers", &self.peer_count())
2973            .field("links", &self.link_count())
2974            .field("transports", &self.transport_count())
2975            .finish()
2976    }
2977}