Skip to main content

weirdnet_net/
node.rs

1//! The libp2p node: TCP and QUIC (or an in-memory transport for tests) with Noise and
2//! Yamux; mDNS on the local network; Kademlia, identify and ping; relay client and
3//! (opt-in) relay server with DCUtR hole punching; AutoNAT; and request-response on
4//! the profile's protocol id, carrying the application's own request and response types
5//! (CBOR).
6//!
7//! The swarm runs on its own thread with a small Tokio runtime. [`Node`] is a blocking
8//! handle (the CLI and TUI are synchronous): requests wait for their answer. Requests
9//! that come in are answered by a [`Handler`] on Tokio's blocking pool.
10use crate::addr::{addr_peer, circuit_relay, reach_rank, routable, shareable};
11use crate::app::{AppError, AppHandler, AppRequest, AppResponse};
12use crate::error::{NetError, Result};
13use crate::events::{Event, Events, Hub, StatusWatch};
14use crate::names::{Entry, Lookup, Names, NamesRequest, NamesResponse};
15use crate::peers::{DiscoveryMode, PeerHint};
16use crate::profile::Profile;
17use crate::stream::transport::Control;
18use crate::stream::{Incoming, Limits, Path, Stream};
19use crate::wss::WssTls;
20use futures::StreamExt;
21use libp2p::core::muxing::StreamMuxerBox;
22use libp2p::core::transport::{Boxed, MemoryTransport, Transport};
23use libp2p::core::upgrade::Version;
24use libp2p::identity::Keypair;
25use libp2p::kad::{self, store::MemoryStore, store::RecordStore};
26use libp2p::multiaddr::Protocol;
27use libp2p::request_response::{self, OutboundRequestId, ProtocolSupport};
28use libp2p::swarm::behaviour::toggle::Toggle;
29use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
30use libp2p::{Multiaddr, PeerId, StreamProtocol, Swarm, autonat, dcutr, identify, mdns, noise, ping, relay, yamux};
31use serde::de::DeserializeOwned;
32use serde::{Deserialize, Serialize};
33use std::collections::{HashMap, HashSet};
34use std::sync::{Arc, Mutex};
35use std::time::Duration;
36use tokio::sync::{mpsc, oneshot};
37
38/// Request-response defaults ([`NodeConfig::request_max`] and the rest, when left at zero).
39pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
40pub const REQUEST_MAX: u64 = 8 * 1024 * 1024;
41pub const RESPONSE_MAX: u64 = 256 * 1024 * 1024;
42
43/// How a node runs.
44#[derive(Debug, Clone, Default)]
45pub struct NodeConfig {
46    /// Addresses to listen on (none: only dial out).
47    pub listen: Vec<Multiaddr>,
48    /// Find and announce peers on the local network (only when [`NodeConfig::discovery`] is
49    /// enabled, and never on the in-memory transport).
50    pub mdns: bool,
51    /// Peer discovery (mDNS when [`NodeConfig::mdns`] is set, and Kademlia). Enabled by
52    /// default. Disabled: no LAN announcements or DHT; configured relays, [`NodeConfig::peers`]
53    /// and explicit dials (including serving apps and content) still work.
54    pub discovery: DiscoveryMode,
55    /// Peers to dial without discovering them (addresses plus a peer id). Adding a peer
56    /// does not grant trust; certificates do. The application persists this list.
57    pub peers: Vec<PeerHint>,
58    /// Relay traffic for other nodes (and say so).
59    pub relay_server: bool,
60    /// Kademlia bootstrap nodes (`/ip4/…/tcp/…/p2p/…`).
61    pub bootstrap: Vec<Multiaddr>,
62    /// Relays to reserve a slot on (`/…/p2p/RELAY`); reachable through them behind NAT.
63    pub relays: Vec<Multiaddr>,
64    /// The in-memory transport (tests) instead of TCP and QUIC.
65    pub memory: bool,
66    /// This node's label (in identify; empty: none).
67    pub label: String,
68    /// Addresses others reach us at from outside (a DNS name or public IP forwarded to
69    /// this node), announced and put in invites before the local ones.
70    pub external: Vec<Multiaddr>,
71    /// The application's version, in the identify agent (`NAME/VERSION`); empty: this
72    /// crate's version.
73    pub version: String,
74    /// What the relay server (`relay_server`) allows; the default is libp2p's.
75    pub relay_limits: RelayLimits,
76    /// Serve the names protocol (rendezvous for signed peer records) from this store.
77    pub names_server: Option<Names>,
78    /// Names servers to register with and look users up on (`…/p2p/ID`), besides the
79    /// relays this node holds a reservation on.
80    pub names_servers: Vec<Multiaddr>,
81    /// Largest request on the profile's request-response protocol (0: [`REQUEST_MAX`]).
82    /// Bulk data belongs on a [stream](crate::stream) instead.
83    pub request_max: u64,
84    /// Largest response (0: [`RESPONSE_MAX`]).
85    pub response_max: u64,
86    /// How long a request waits for its response (zero: [`REQUEST_TIMEOUT`]).
87    pub request_timeout: Duration,
88    /// WebSocket over TLS: the certificate to listen with (put `/…/tcp/443/tls/ws` in
89    /// `listen`) and extra roots to trust when dialing. Without it the node still dials WSS.
90    pub wss: Option<WssTls>,
91    /// DNS servers for `/dns` and `/dnsaddr` addresses (empty: the system's, or public
92    /// resolvers where the system has none to read, as on Android).
93    pub dns_servers: Vec<std::net::SocketAddr>,
94    /// App calls: the cap on a request or response head, in bytes (0: 16 KiB).
95    pub app_header_max: usize,
96    /// App calls: the cap on one body, in bytes (0: none, the default).
97    pub app_body_max: u64,
98    /// App calls: how long a call may go without a byte either way (zero: 60 seconds).
99    pub app_idle_timeout: Duration,
100}
101
102impl NodeConfig {
103    fn req_max(&self) -> u64 {
104        if self.request_max == 0 { REQUEST_MAX } else { self.request_max }
105    }
106
107    fn resp_max(&self) -> u64 {
108        if self.response_max == 0 { RESPONSE_MAX } else { self.response_max }
109    }
110
111    fn req_timeout(&self) -> Duration {
112        if self.request_timeout.is_zero() { REQUEST_TIMEOUT } else { self.request_timeout }
113    }
114
115    pub(crate) fn app_limits(&self) -> crate::app::AppLimits {
116        crate::app::AppLimits {
117            header_max: if self.app_header_max == 0 { crate::app::DEFAULT_HEADER_MAX } else { self.app_header_max },
118            body_max: self.app_body_max,
119            idle: if self.app_idle_timeout.is_zero() { crate::app::DEFAULT_IDLE_TIMEOUT } else { self.app_idle_timeout },
120        }
121    }
122}
123
124/// Limits of the relay server: how many reservations and circuits it holds, and how long
125/// and how much one circuit may carry. [`RelayLimits::default`] keeps libp2p's defaults
126/// (circuits for hole punching and small requests: 2 minutes, 128 KiB);
127/// [`RelayLimits::unlimited`] caps nothing, so circuits carry data.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub struct RelayLimits {
130    /// Reservations held at once, and per peer.
131    pub max_reservations: usize,
132    pub max_reservations_per_peer: usize,
133    /// How long a reservation lasts before the client renews it.
134    pub reservation_duration: Duration,
135    /// Circuits open at once, and per peer.
136    pub max_circuits: usize,
137    pub max_circuits_per_peer: usize,
138    /// How long one circuit may stay open (at most `u32::MAX` seconds).
139    pub max_circuit_duration: Duration,
140    /// How many bytes one circuit may carry in each direction; 0: no limit.
141    pub max_circuit_bytes: u64,
142    /// libp2p's rate limiters on new reservations and circuits (per peer and per IP).
143    pub rate_limits: bool,
144}
145
146impl Default for RelayLimits {
147    /// libp2p's defaults.
148    fn default() -> Self {
149        let c = relay::Config::default();
150        RelayLimits {
151            max_reservations: c.max_reservations,
152            max_reservations_per_peer: c.max_reservations_per_peer,
153            reservation_duration: c.reservation_duration,
154            max_circuits: c.max_circuits,
155            max_circuits_per_peer: c.max_circuits_per_peer,
156            max_circuit_duration: c.max_circuit_duration,
157            max_circuit_bytes: c.max_circuit_bytes,
158            rate_limits: true,
159        }
160    }
161}
162
163impl RelayLimits {
164    /// Longest circuit duration libp2p accepts.
165    pub const MAX_CIRCUIT_DURATION: Duration = Duration::from_secs(u32::MAX as u64);
166
167    /// No caps: as many reservations and circuits as clients ask for, no byte limit, the
168    /// longest circuit libp2p accepts, and no rate limiters. Reservations still last an hour
169    /// before the client renews them.
170    pub fn unlimited() -> Self {
171        RelayLimits {
172            max_reservations: usize::MAX,
173            max_reservations_per_peer: usize::MAX,
174            max_circuits: usize::MAX,
175            max_circuits_per_peer: usize::MAX,
176            max_circuit_duration: Self::MAX_CIRCUIT_DURATION,
177            max_circuit_bytes: 0,
178            rate_limits: false,
179            ..Self::default()
180        }
181    }
182
183    /// Whether nothing is capped (see [`RelayLimits::unlimited`]).
184    pub fn is_unlimited(&self) -> bool {
185        *self == Self::unlimited()
186    }
187
188    /// Refuse limits libp2p cannot apply (a zero count or duration, or a circuit duration
189    /// over `u32::MAX` seconds).
190    pub fn check(&self) -> Result<()> {
191        if self.max_reservations == 0 || self.max_reservations_per_peer == 0 || self.max_circuits == 0 || self.max_circuits_per_peer == 0 {
192            return Err(NetError::invalid("relay limits", "reservation and circuit counts must be at least 1"));
193        }
194        if self.reservation_duration.is_zero() || self.max_circuit_duration.is_zero() {
195            return Err(NetError::invalid("relay limits", "durations must be longer than zero"));
196        }
197        if self.max_circuit_duration > Self::MAX_CIRCUIT_DURATION {
198            return Err(NetError::invalid("relay limits", "a circuit may last at most u32::MAX seconds"));
199        }
200        Ok(())
201    }
202
203    fn config(&self) -> relay::Config {
204        let mut c = relay::Config {
205            max_reservations: self.max_reservations,
206            max_reservations_per_peer: self.max_reservations_per_peer,
207            reservation_duration: self.reservation_duration,
208            max_circuits: self.max_circuits,
209            max_circuits_per_peer: self.max_circuits_per_peer,
210            max_circuit_duration: self.max_circuit_duration,
211            max_circuit_bytes: self.max_circuit_bytes,
212            ..relay::Config::default()
213        };
214        if !self.rate_limits {
215            c.reservation_rate_limiters.clear();
216            c.circuit_src_rate_limiters.clear();
217        }
218        c
219    }
220}
221
222impl NodeConfig {
223    /// TCP and QUIC on every interface, IPv4 and IPv6, on `port`.
224    pub fn default_listen(port: u16) -> Vec<Multiaddr> {
225        [
226            format!("/ip4/0.0.0.0/tcp/{port}"),
227            format!("/ip4/0.0.0.0/udp/{port}/quic-v1"),
228            format!("/ip6/::/tcp/{port}"),
229            format!("/ip6/::/udp/{port}/quic-v1"),
230        ]
231        .iter()
232        .filter_map(|a| a.parse().ok())
233        .collect()
234    }
235}
236
237/// A peer seen by the node, for the handler to remember.
238#[derive(Debug, Clone)]
239pub struct Sighting {
240    pub peer: PeerId,
241    pub addrs: Vec<String>,
242    pub caps: Option<Vec<String>>,
243    pub agent: Option<String>,
244    pub source: &'static str,
245}
246
247/// What a node carries: the application's request and response types (sent as CBOR).
248pub trait Message: Serialize + DeserializeOwned + std::fmt::Debug + Clone + Send + 'static {}
249impl<T: Serialize + DeserializeOwned + std::fmt::Debug + Clone + Send + 'static> Message for T {}
250
251/// Answers requests from peers. The peer id is the one Noise authenticated.
252pub trait Handler<Q, R>: Send + Sync + 'static {
253    fn request(&self, from: &PeerId, req: Q) -> R;
254    /// A peer was discovered or identified.
255    fn seen(&self, _s: Sighting) {}
256}
257
258/// What the node is doing.
259#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
260pub struct Status {
261    pub peer_id: String,
262    pub listening: Vec<String>,
263    pub external: Vec<String>,
264    pub connected: Vec<String>,
265    /// AutoNAT: `public`, `private` or `unknown`.
266    pub nat: String,
267    /// Relays holding a reservation for us.
268    pub reservations: Vec<String>,
269    pub relay_server: bool,
270    pub mdns: bool,
271    /// Whether peer discovery (mDNS, Kademlia) is on.
272    #[serde(default)]
273    pub discovery: bool,
274    pub started_at: i64,
275    /// Paused by the app ([`Node::pause`]).
276    #[serde(default)]
277    pub paused: bool,
278}
279
280// rustc 1.100 flags code the `NetworkBehaviour` derive generates (matches on
281// uninhabited events) as unreachable; the allow has to sit on a module to reach it.
282#[allow(unreachable_code)]
283mod wire {
284    use super::*;
285
286    #[derive(NetworkBehaviour)]
287    pub(super) struct Behaviour<Q: Message, R: Message> {
288        pub(super) rr: request_response::Behaviour<crate::wire::Codec<Q, R>>,
289        pub(super) names: request_response::Behaviour<crate::wire::Codec<NamesRequest, NamesResponse>>,
290        pub(super) identify: identify::Behaviour,
291        pub(super) ping: ping::Behaviour,
292        pub(super) kad: kad::Behaviour<MemoryStore>,
293        pub(super) mdns: Toggle<mdns::tokio::Behaviour>,
294        pub(super) relay_client: relay::client::Behaviour,
295        pub(super) relay_server: Toggle<relay::Behaviour>,
296        pub(super) dcutr: dcutr::Behaviour,
297        pub(super) autonat: autonat::Behaviour,
298        pub(super) streams: crate::stream::transport::Behaviour,
299    }
300}
301use wire::{Behaviour, BehaviourEvent};
302
303enum Cmd<Q, R> {
304    Request { peer: PeerId, addrs: Vec<Multiaddr>, wire: Q, reply: oneshot::Sender<Result<R>> },
305    Names { peer: PeerId, addrs: Vec<Multiaddr>, req: NamesRequest, reply: oneshot::Sender<Result<NamesResponse>> },
306    PutEntry { entry: Entry, reply: oneshot::Sender<Result<()>> },
307    GetEntries { user: String, reply: oneshot::Sender<Result<Vec<Entry>>> },
308    FindPeer { peer: PeerId, reply: oneshot::Sender<Result<Vec<Multiaddr>>> },
309    KnownAddrs { reply: oneshot::Sender<Result<Vec<(PeerId, Multiaddr)>>> },
310    PeerApps { peer: PeerId, reply: oneshot::Sender<Result<Option<Vec<String>>>> },
311    Dial { addr: Multiaddr, reply: oneshot::Sender<Result<PeerId>> },
312    Connect { peer: PeerId, addrs: Vec<Multiaddr>, reply: oneshot::Sender<Result<PeerId>> },
313    DropPath { peer: PeerId, path: Path, reply: oneshot::Sender<Result<usize>> },
314    Paths { peer: PeerId, reply: oneshot::Sender<Result<Vec<Path>>> },
315    Pause { reply: oneshot::Sender<Result<()>> },
316    Resume { reply: oneshot::Sender<Result<()>> },
317    NetworkChanged { reply: oneshot::Sender<Result<()>> },
318    Listen { addr: Multiaddr, reply: oneshot::Sender<Result<Multiaddr>> },
319    AddRelay { addr: Multiaddr },
320    AddPeer { hint: PeerHint, reply: oneshot::Sender<Result<()>> },
321    RemovePeer { peer: PeerId, reply: oneshot::Sender<Result<()>> },
322    ListPeers { reply: oneshot::Sender<Result<Vec<PeerHint>>> },
323    Provide { key: Vec<u8>, reply: oneshot::Sender<Result<()>> },
324    PutLocator { rec: crate::locator::LocatorRecord, reply: oneshot::Sender<Result<()>> },
325    GetLocators { key: Vec<u8>, reply: oneshot::Sender<Result<Vec<crate::locator::LocatorRecord>>> },
326    StopProviding { key: Vec<u8> },
327    Providers { key: Vec<u8>, reply: oneshot::Sender<Result<Vec<PeerId>>> },
328    Stop,
329}
330
331type Providing = (Vec<PeerId>, oneshot::Sender<Result<Vec<PeerId>>>);
332
333/// A running node.
334pub struct Node<Q: Message, R: Message> {
335    peer_id: PeerId,
336    profile: &'static Profile,
337    names_list: Vec<Multiaddr>,
338    tx: mpsc::UnboundedSender<Cmd<Q, R>>,
339    status: Arc<Mutex<Status>>,
340    request_timeout: Duration,
341    streams: (tokio::runtime::Handle, Control),
342    hub: Hub,
343    status_rx: tokio::sync::watch::Receiver<Status>,
344    thread: Option<std::thread::JoinHandle<()>>,
345    apps: Arc<crate::app::Server>,
346    app_limits: crate::app::AppLimits,
347    /// Where peers found by [`Node::resolve_app`] are.
348    app_addrs: Mutex<HashMap<PeerId, Vec<Multiaddr>>>,
349    dns_servers: Vec<std::net::SocketAddr>,
350}
351
352fn net_err(e: impl std::fmt::Display) -> NetError {
353    NetError::net(e)
354}
355
356fn stopped() -> NetError {
357    NetError::Network("the node has stopped".into())
358}
359
360fn behaviour<Q: Message, R: Message>(
361    p: &Profile,
362    key: &Keypair,
363    relay_client: relay::client::Behaviour,
364    cfg: &NodeConfig,
365) -> Result<Behaviour<Q, R>> {
366    let peer = key.public().to_peer_id();
367    // byte fields go as CBOR byte strings (crate::wire), not arrays of integers
368    let rr = request_response::Behaviour::with_codec(
369        crate::wire::Codec::new(cfg.req_max(), cfg.resp_max()),
370        [(StreamProtocol::new(p.protocol), ProtocolSupport::Full)],
371        request_response::Config::default().with_request_timeout(cfg.req_timeout()),
372    );
373    let version = if cfg.version.is_empty() { env!("CARGO_PKG_VERSION") } else { cfg.version.as_str() };
374    let agent = p.agent(version, &cfg.label);
375    // A relay with explicit external addresses announces only those, not every
376    // interface it listens on (private VPC and loopback ones are useless to clients).
377    let hide = cfg.relay_server && !cfg.external.is_empty();
378    let identify =
379        identify::Behaviour::new(identify::Config::new(p.identify.into(), key.public()).with_agent_version(agent).with_hide_listen_addrs(hide));
380    let mut kcfg = kad::Config::new(StreamProtocol::new(p.kad));
381    kcfg.set_query_timeout(Duration::from_secs(30));
382    // every record and provider a peer puts is checked first (peer records, relay keys)
383    kcfg.set_record_filtering(kad::StoreInserts::FilterBoth);
384    let names = request_response::Behaviour::with_codec(
385        crate::wire::Codec::new(64 * 1024, 64 * 1024),
386        [(StreamProtocol::new(p.names), if cfg.names_server.is_some() { ProtocolSupport::Full } else { ProtocolSupport::Outbound })],
387        request_response::Config::default().with_request_timeout(Duration::from_secs(20)),
388    );
389    let kad = kad::Behaviour::with_config(peer, MemoryStore::new(peer), kcfg);
390    let mdns = if cfg.discovery.is_enabled() && cfg.mdns && !cfg.memory {
391        Some(mdns::tokio::Behaviour::new(mdns::Config::default(), peer).map_err(net_err)?)
392    } else {
393        None
394    };
395    let relay_server = cfg.relay_server.then(|| relay::Behaviour::new(peer, cfg.relay_limits.config()));
396    let autonat = autonat::Behaviour::new(peer, autonat::Config { only_global_ips: !cfg.memory, ..Default::default() });
397    Ok(Behaviour {
398        rr,
399        names,
400        identify,
401        ping: ping::Behaviour::new(ping::Config::new()),
402        kad,
403        mdns: mdns.into(),
404        relay_client,
405        relay_server: relay_server.into(),
406        dcutr: dcutr::Behaviour::new(peer),
407        autonat,
408        streams: crate::stream::transport::Behaviour::new(),
409    })
410}
411
412type BoxErr = Box<dyn std::error::Error + Send + Sync>;
413
414fn memory_transport(key: &Keypair) -> std::result::Result<Boxed<(PeerId, StreamMuxerBox)>, BoxErr> {
415    Ok(MemoryTransport::default()
416        .upgrade(Version::V1)
417        .authenticate(noise::Config::new(key).map_err(|e| Box::new(e) as BoxErr)?)
418        .multiplex(yamux::Config::default())
419        .timeout(Duration::from_secs(20))
420        .boxed())
421}
422
423fn build_swarm<Q: Message, R: Message>(p: &'static Profile, key: Keypair, cfg: &NodeConfig) -> Result<Swarm<Behaviour<Q, R>>> {
424    let idle = |c: libp2p::swarm::Config| c.with_idle_connection_timeout(Duration::from_secs(120));
425    let swarm = if cfg.memory {
426        let cfg2 = cfg.clone();
427        libp2p::SwarmBuilder::with_existing_identity(key)
428            .with_tokio()
429            .with_other_transport(memory_transport)
430            .map_err(net_err)?
431            .with_relay_client(noise::Config::new, yamux::Config::default)
432            .map_err(net_err)?
433            .with_behaviour(move |key, relay| behaviour(p, key, relay, &cfg2).map_err(|e| Box::new(e) as BoxErr))
434            .map_err(net_err)?
435            .with_swarm_config(idle)
436            .build()
437    } else {
438        let cfg2 = cfg.clone();
439        let wss_tls = cfg.wss.clone().unwrap_or_default();
440        let dns = dns_config(&cfg.dns_servers);
441        wss_tls.config()?;
442        libp2p::SwarmBuilder::with_existing_identity(key)
443            .with_tokio()
444            .with_other_transport(|key| crate::wss::transport(key, &wss_tls, dns))
445            .map_err(net_err)?
446            .with_relay_client(noise::Config::new, yamux::Config::default)
447            .map_err(net_err)?
448            .with_behaviour(move |key, relay| behaviour(p, key, relay, &cfg2).map_err(|e| Box::new(e) as BoxErr))
449            .map_err(net_err)?
450            .with_swarm_config(idle)
451            .build()
452    };
453    Ok(swarm)
454}
455
456impl<Q: Message, R: Message> Node<Q, R> {
457    /// Start a node speaking `profile`; returns once its listeners are up (or failed).
458    pub fn start(profile: &'static Profile, key: Keypair, cfg: NodeConfig, handler: Arc<dyn Handler<Q, R>>) -> Result<Self> {
459        if cfg.relay_server {
460            cfg.relay_limits.check()?;
461        }
462        let peer_id = key.public().to_peer_id();
463        let status = Arc::new(Mutex::new(Status {
464            peer_id: peer_id.to_string(),
465            nat: "unknown".into(),
466            relay_server: cfg.relay_server,
467            mdns: cfg.discovery.is_enabled() && cfg.mdns && !cfg.memory,
468            discovery: cfg.discovery.is_enabled(),
469            started_at: crate::now_ms(),
470            ..Default::default()
471        }));
472        let (tx, rx) = mpsc::unbounded_channel();
473        let (ready_tx, ready_rx) = std::sync::mpsc::channel::<Result<()>>();
474        let st = status.clone();
475        let names_list = cfg.names_servers.clone();
476        let request_timeout = cfg.req_timeout();
477        let app_limits = cfg.app_limits();
478        let dns_servers = cfg.dns_servers.clone();
479        let serving = Arc::new(std::sync::atomic::AtomicBool::new(false));
480        let serving2 = serving.clone();
481        let (streams_tx, streams_rx) = std::sync::mpsc::channel::<(tokio::runtime::Handle, Control)>();
482        let hub = Hub::default();
483        let (status_tx, status_rx) = tokio::sync::watch::channel(status.lock().map(|s| s.clone()).unwrap_or_default());
484        let hub2 = hub.clone();
485        let thread = std::thread::Builder::new()
486            .name(profile.thread.into())
487            .spawn(move || {
488                let rt = match tokio::runtime::Builder::new_multi_thread()
489                    .worker_threads(2)
490                    .enable_all()
491                    .thread_name(format!("{}-rt", profile.thread))
492                    .build()
493                {
494                    Ok(rt) => rt,
495                    Err(e) => {
496                        let _ = ready_tx.send(Err(net_err(e)));
497                        return;
498                    }
499                };
500                rt.block_on(async move {
501                    let swarm = match build_swarm(profile, key, &cfg) {
502                        Ok(mut s) => {
503                            for a in &cfg.external {
504                                s.add_external_address(a.clone());
505                            }
506                            let _ = streams_tx.send((tokio::runtime::Handle::current(), s.behaviour().streams.control()));
507                            s
508                        }
509                        Err(e) => {
510                            let _ = ready_tx.send(Err(e));
511                            return;
512                        }
513                    };
514                    let mut l = Loop::new(profile, swarm, cfg, handler, st);
515                    l.hub = hub2;
516                    l.serving = serving2;
517                    l.status_tx = Some(status_tx);
518                    l.run(rx, ready_tx).await;
519                });
520                rt.shutdown_timeout(Duration::from_secs(2));
521            })
522            .map_err(net_err)?;
523        match ready_rx.recv_timeout(Duration::from_secs(20)) {
524            Ok(Ok(())) => {
525                let streams = streams_rx.recv().map_err(|_| stopped())?;
526                Ok(Node {
527                    peer_id,
528                    profile,
529                    names_list,
530                    tx,
531                    status,
532                    request_timeout,
533                    streams,
534                    hub,
535                    status_rx,
536                    thread: Some(thread),
537                    apps: Arc::new(crate::app::Server::new(serving)),
538                    app_limits,
539                    app_addrs: Mutex::new(HashMap::new()),
540                    dns_servers,
541                })
542            }
543            Ok(Err(e)) => {
544                let _ = thread.join();
545                Err(e)
546            }
547            Err(_) => Err(NetError::Network("the node did not start in time".into())),
548        }
549    }
550
551    /// The identifier profile the node speaks.
552    pub fn profile(&self) -> &'static Profile {
553        self.profile
554    }
555
556    pub fn peer_id(&self) -> PeerId {
557        self.peer_id
558    }
559
560    pub fn status(&self) -> Status {
561        self.status.lock().map(|s| s.clone()).unwrap_or_default()
562    }
563
564    /// Addresses others can use to reach this node (with `/p2p/ID`).
565    pub fn reachable_addrs(&self) -> Vec<String> {
566        let s = self.status();
567        let mut v: Vec<String> = vec![];
568        for a in s.external.iter().chain(s.listening.iter()) {
569            // a circuit through a relay is only useful if the relay's own address is routable
570            if let Ok(m) = a.parse::<Multiaddr>()
571                && shareable(&m)
572                && (!m.iter().any(|p| p == Protocol::P2pCircuit) || routable(&m))
573            {
574                let full = if addr_peer(&m).is_some() { m } else { m.with(Protocol::P2p(self.peer_id)) };
575                let t = full.to_string();
576                if !v.contains(&t) {
577                    v.push(t);
578                }
579            }
580        }
581        v
582    }
583
584    fn call<T>(&self, make: impl FnOnce(oneshot::Sender<Result<T>>) -> Cmd<Q, R>, wait: Duration) -> Result<T> {
585        let (tx, rx) = oneshot::channel();
586        self.tx.send(make(tx)).map_err(|_| stopped())?;
587        let deadline = std::time::Instant::now() + wait;
588        let mut rx = rx;
589        loop {
590            match rx.try_recv() {
591                Ok(r) => return r,
592                Err(oneshot::error::TryRecvError::Closed) => return Err(stopped()),
593                Err(oneshot::error::TryRecvError::Empty) => {
594                    if std::time::Instant::now() > deadline {
595                        return Err(NetError::Network("timed out".into()));
596                    }
597                    std::thread::sleep(Duration::from_millis(5));
598                }
599            }
600        }
601    }
602
603    /// Send a request and wait for the answer. `addrs` are tried if not connected yet.
604    pub fn request(&self, peer: PeerId, addrs: &[Multiaddr], wire: Q) -> Result<R> {
605        let addrs = addrs.to_vec();
606        self.call(|reply| Cmd::Request { peer, addrs, wire, reply }, self.request_timeout + Duration::from_secs(5))
607    }
608
609    /// Ask a names server (a relay, usually) something; `addrs` are tried if not connected.
610    pub fn names_request(&self, server: PeerId, addrs: &[Multiaddr], req: NamesRequest) -> Result<NamesResponse> {
611        let addrs = addrs.to_vec();
612        self.call(|reply| Cmd::Names { peer: server, addrs, req, reply }, Duration::from_secs(30))
613    }
614
615    /// Register a record or withdrawal on a names server.
616    pub fn register(&self, server: PeerId, addrs: &[Multiaddr], entry: Entry) -> Result<()> {
617        match self.names_request(server, addrs, NamesRequest::Register(Box::new(entry)))? {
618            NamesResponse::Registered => Ok(()),
619            NamesResponse::Refused(why) => Err(NetError::Network(format!("the names server refused: {why}"))),
620            NamesResponse::Found(_) => Err(NetError::Network("unexpected answer from the names server".into())),
621        }
622    }
623
624    /// A user's entry on one names server.
625    pub fn discover(&self, server: PeerId, addrs: &[Multiaddr], user: &str) -> Result<Option<Entry>> {
626        match self.names_request(server, addrs, NamesRequest::Discover { user_id: user.into() })? {
627            NamesResponse::Found(e) => Ok(e.map(|e| *e)),
628            NamesResponse::Refused(why) => Err(NetError::Network(format!("the names server refused: {why}"))),
629            NamesResponse::Registered => Err(NetError::Network("unexpected answer from the names server".into())),
630        }
631    }
632
633    /// Put a record or withdrawal in the DHT (checked first, like every storing node does).
634    /// Records belong in the DHT only while the device hosts something public or private.
635    pub fn put_entry(&self, entry: Entry) -> Result<()> {
636        self.call(|reply| Cmd::PutEntry { entry, reply }, Duration::from_secs(40))
637    }
638
639    /// Put a private site's locator record in the DHT (checked first, as storing nodes do).
640    pub fn put_locator(&self, rec: crate::locator::LocatorRecord) -> Result<()> {
641        self.call(|reply| Cmd::PutLocator { rec, reply }, Duration::from_secs(40))
642    }
643
644    /// The locator records the DHT holds for `locator` today and yesterday (checked but not
645    /// opened; see [`LocatorKeys::open`](crate::locator::LocatorKeys::open)).
646    pub fn get_locators(&self, locator: &crate::PublicKey) -> Result<Vec<crate::locator::LocatorRecord>> {
647        let mut out = vec![];
648        for key in crate::locator::lookup_keys(locator, crate::now_ms()) {
649            out.extend(self.call(|reply| Cmd::GetLocators { key, reply }, Duration::from_secs(40))?);
650        }
651        Ok(out)
652    }
653
654    /// Every entry the DHT returns for a user (unchecked; see [`Profile::newest`]).
655    pub fn get_entries(&self, user: &str) -> Result<Vec<Entry>> {
656        let user = user.to_string();
657        self.call(|reply| Cmd::GetEntries { user, reply }, Duration::from_secs(40))
658    }
659
660    /// Where a peer is, by its key alone: what the DHT knows of it.
661    pub fn find_peer(&self, peer: PeerId) -> Result<Vec<Multiaddr>> {
662        self.call(|reply| Cmd::FindPeer { peer, reply }, Duration::from_secs(40))
663    }
664
665    /// Announce in the DHT that this node provides `key` (see
666    /// [`content::provider_key`](crate::content::provider_key)); kept and re-announced until
667    /// [`stop_providing`](Self::stop_providing) or the node stops.
668    pub fn provide(&self, key: &[u8]) -> Result<()> {
669        let key = key.to_vec();
670        self.call(|reply| Cmd::Provide { key, reply }, Duration::from_secs(5))
671    }
672
673    pub fn stop_providing(&self, key: &[u8]) -> Result<()> {
674        self.tx.send(Cmd::StopProviding { key: key.to_vec() }).map_err(|_| stopped())
675    }
676
677    /// The peers the DHT knows to provide `key` (this node excluded).
678    pub fn providers(&self, key: &[u8]) -> Result<Vec<PeerId>> {
679        let key = key.to_vec();
680        self.call(|reply| Cmd::Providers { key, reply }, Duration::from_secs(40))
681    }
682
683    /// Names servers to ask: the configured ones and the relays holding our reservation.
684    fn names_servers(&self) -> Vec<(PeerId, Vec<Multiaddr>)> {
685        let known = self.call(|reply| Cmd::KnownAddrs { reply }, Duration::from_secs(5)).unwrap_or_default();
686        let mut out: Vec<(PeerId, Vec<Multiaddr>)> = vec![];
687        let reserved: Vec<PeerId> = self.status().reservations.iter().filter_map(|r| r.parse().ok()).collect();
688        for (p, a) in known.into_iter() {
689            if reserved.contains(&p) || self.names_list.iter().any(|n| addr_peer(n) == Some(p)) {
690                match out.iter_mut().find(|(q, _)| *q == p) {
691                    Some((_, v)) => v.push(a),
692                    None => out.push((p, vec![a])),
693                }
694            }
695        }
696        for n in &self.names_list {
697            if let Some(p) = addr_peer(n)
698                && !out.iter().any(|(q, _)| *q == p)
699            {
700                out.push((p, vec![n.clone()]));
701            }
702        }
703        out
704    }
705
706    /// Register an entry with every names server this node uses (its relays and the
707    /// configured ones); returns how many took it.
708    pub fn register_everywhere(&self, entry: &Entry) -> usize {
709        self.names_servers().into_iter().filter(|(p, a)| self.register(*p, a, entry.clone()).is_ok()).count()
710    }
711
712    /// Find a user's freshest valid record: on this node's names servers, then in the DHT.
713    pub fn lookup(&self, user: &str) -> Lookup {
714        let mut found: Vec<Entry> = vec![];
715        for (p, a) in self.names_servers() {
716            if let Ok(Some(e)) = self.discover(p, &a, user) {
717                found.push(e);
718            }
719        }
720        if let Ok(v) = self.get_entries(user) {
721            found.extend(v);
722        }
723        self.profile.newest(user, &found, crate::now_ms())
724    }
725
726    /// Send a request to a peer known only by its key: when not connected, find its
727    /// addresses in the DHT and try circuits through this node's relays and names servers.
728    pub fn request_key(&self, peer: PeerId, wire: Q) -> Result<R> {
729        if self.status().connected.contains(&peer.to_string()) {
730            return self.request(peer, &[], wire);
731        }
732        let mut addrs = self.find_peer(peer).unwrap_or_default();
733        for (_, a) in self.names_servers() {
734            for base in a {
735                let base: Multiaddr = base.iter().take_while(|p| *p != Protocol::P2pCircuit).collect();
736                addrs.push(base.with(Protocol::P2pCircuit).with(Protocol::P2p(peer)));
737            }
738        }
739        self.request(peer, &addrs, wire)
740    }
741
742    /// Send a request to a user's node: look up its record and dial its addresses
743    /// (circuits and direct ones together). Returns the node that answered.
744    pub fn request_user(&self, user: &str, wire: Q) -> Result<(PeerId, R)> {
745        match self.lookup(user) {
746            Lookup::Found(r) => {
747                let peer: PeerId = r.cert.peer_id.parse().map_err(|_| NetError::invalid("peer record", "bad peer id"))?;
748                let addrs = crate::addr::parse_addrs(&r.addrs);
749                Ok((peer, self.request(peer, &addrs, wire)?))
750            }
751            Lookup::Withdrawn(_) => Err(NetError::Network(format!("{user} withdrew its record"))),
752            Lookup::NotFound => Err(NetError::Network(format!("no record for {user}"))),
753        }
754    }
755
756    /// Connect to an address; returns the peer there.
757    pub fn dial(&self, addr: Multiaddr) -> Result<PeerId> {
758        self.call(|reply| Cmd::Dial { addr, reply }, Duration::from_secs(30))
759    }
760
761    /// Connect to `peer` if not connected yet, trying `addrs` (or the addresses the node knows).
762    pub fn connect(&self, peer: PeerId, addrs: &[Multiaddr]) -> Result<()> {
763        let addrs = addrs.to_vec();
764        self.call(|reply| Cmd::Connect { peer, addrs, reply }, Duration::from_secs(30)).map(|_| ())
765    }
766
767    /// Remember `hint` and dial it. This does not certify the peer.
768    pub fn add_peer(&self, hint: PeerHint) -> Result<()> {
769        self.call(|reply| Cmd::AddPeer { hint, reply }, Duration::from_secs(30))
770    }
771
772    /// Forget a manual peer (open connections stay until dropped).
773    pub fn remove_peer(&self, peer: PeerId) -> Result<()> {
774        self.call(|reply| Cmd::RemovePeer { peer, reply }, Duration::from_secs(5))
775    }
776
777    /// The manual peer list (from config and [`Node::add_peer`]).
778    pub fn peers(&self) -> Result<Vec<PeerHint>> {
779        self.call(|reply| Cmd::ListPeers { reply }, Duration::from_secs(5))
780    }
781
782    /// Close this node's direct or relayed connections to `peer`; returns how many. Streams on
783    /// them move to another path (or wait for one to come back).
784    pub fn drop_path(&self, peer: PeerId, path: Path) -> Result<usize> {
785        self.call(|reply| Cmd::DropPath { peer, path, reply }, Duration::from_secs(5))
786    }
787
788    /// Events from now on (connections, listeners, reservations, NAT, lifecycle).
789    pub fn events(&self) -> Events {
790        self.hub.subscribe()
791    }
792
793    /// The status, and a way to wait for it to change.
794    pub fn watch_status(&self) -> StatusWatch {
795        StatusWatch { rx: self.status_rx.clone() }
796    }
797
798    /// The app goes to the background: close every connection and listener and give up relay
799    /// reservations. Requests and streams opened while paused still dial out.
800    pub fn pause(&self) -> Result<()> {
801        self.call(|reply| Cmd::Pause { reply }, Duration::from_secs(5))
802    }
803
804    /// Back in the foreground: listen again, reserve on the relays again, rejoin the DHT.
805    pub fn resume(&self) -> Result<()> {
806        self.call(|reply| Cmd::Resume { reply }, Duration::from_secs(5))
807    }
808
809    /// The device moved to another network (Wi-Fi to cellular, a new address): drop the
810    /// connections made on the old one and make them again. Streams carry on once a path is back.
811    pub fn network_changed(&self) -> Result<()> {
812        self.call(|reply| Cmd::NetworkChanged { reply }, Duration::from_secs(5))
813    }
814
815    /// [`Node::request`] for async callers (any executor).
816    pub async fn request_async(&self, peer: PeerId, addrs: &[Multiaddr], wire: Q) -> Result<R> {
817        let addrs = addrs.to_vec();
818        self.call_async(|reply| Cmd::Request { peer, addrs, wire, reply }, self.request_timeout + Duration::from_secs(5)).await
819    }
820
821    /// [`Node::connect`] for async callers.
822    pub async fn connect_async(&self, peer: PeerId, addrs: &[Multiaddr]) -> Result<()> {
823        let addrs = addrs.to_vec();
824        self.call_async(|reply| Cmd::Connect { peer, addrs, reply }, Duration::from_secs(30)).await.map(|_| ())
825    }
826
827    /// [`Node::dial`] for async callers.
828    pub async fn dial_async(&self, addr: Multiaddr) -> Result<PeerId> {
829        self.call_async(|reply| Cmd::Dial { addr, reply }, Duration::from_secs(30)).await
830    }
831
832    async fn call_async<T: Send + 'static>(&self, make: impl FnOnce(oneshot::Sender<Result<T>>) -> Cmd<Q, R>, wait: Duration) -> Result<T> {
833        let (tx, rx) = oneshot::channel();
834        self.tx.send(make(tx)).map_err(|_| stopped())?;
835        let rt = self.streams.0.clone();
836        rt.spawn(async move { tokio::time::timeout(wait, rx).await })
837            .await
838            .map_err(|_| stopped())?
839            .map_err(|_| NetError::Network("timed out".into()))?
840            .map_err(|_| stopped())?
841    }
842
843    /// The connections to `peer` now, by kind (one entry per connection).
844    pub fn paths(&self, peer: PeerId) -> Result<Vec<Path>> {
845        self.call(|reply| Cmd::Paths { peer, reply }, Duration::from_secs(5))
846    }
847
848    /// Accept streams of `protocol` (an id of the application's, such as `/myapp/sync/1`).
849    /// Other peers' streams of protocols nobody accepts are refused.
850    pub fn accept_streams(&self, protocol: &str, limits: Limits) -> Result<Incoming> {
851        let p = StreamProtocol::try_from_owned(protocol.to_string()).map_err(|e| NetError::Network(format!("bad protocol id {protocol}: {e}")))?;
852        let (rt, control) = &self.streams;
853        crate::stream::accept(control.clone(), p, limits, rt)
854    }
855
856    /// Open a stream of `protocol` to `peer` (connecting through `addrs` if needed). It starts
857    /// on a direct connection when there is one and moves there later if one comes up.
858    pub fn open_stream(&self, peer: PeerId, addrs: &[Multiaddr], protocol: &str, limits: Limits) -> Result<Stream> {
859        futures::executor::block_on(self.open_stream_async(peer, addrs, protocol, limits))
860    }
861
862    /// Forwarded HTTPS connections for this node's sites ([`crate::ingress`]).
863    pub fn accept_ingress(&self) -> Result<crate::ingress::IngressIncoming> {
864        Ok(crate::ingress::IngressIncoming { inc: self.accept_streams(crate::ingress::INGRESS_PROTOCOL, Limits::default())? })
865    }
866
867    /// Register this node's sites with an ingress peer: `reg` carries the user's grants for
868    /// that ingress, the user's certificate for this node and where the ingress reaches it.
869    pub fn register_ingress(&self, ingress: PeerId, addrs: &[Multiaddr], reg: &crate::ingress::Registration) -> Result<crate::ingress::Registered> {
870        use futures::AsyncWriteExt;
871        let body = serde_json::to_vec(reg).map_err(|e| NetError::invalid("registration", e.to_string()))?;
872        let mut s = self.open_stream(ingress, addrs, crate::ingress::GRANT_PROTOCOL, Limits::default())?;
873        let rt = self.streams.0.clone();
874        rt.block_on(async move {
875            crate::ingress::write_msg(&mut s, &body).await.map_err(NetError::net)?;
876            let _ = s.close().await;
877            let b = tokio::time::timeout(Duration::from_secs(60), crate::ingress::read_msg(&mut s, crate::ingress::MAX_REGISTRATION))
878                .await
879                .map_err(|_| NetError::Network("no answer from the ingress".into()))?
880                .map_err(NetError::net)?;
881            serde_json::from_slice(&b).map_err(|e| NetError::invalid("registration answer", e.to_string()))
882        })
883    }
884
885    pub(crate) fn runtime(&self) -> tokio::runtime::Handle {
886        self.streams.0.clone()
887    }
888
889    pub(crate) fn opener(&self, protocol: &str, limits: Limits) -> Opener {
890        let tx = self.tx.clone();
891        let control = self.streams.1.clone();
892        let p = StreamProtocol::try_from_owned(protocol.to_string()).expect("a valid protocol id");
893        Arc::new(move |peer, addrs| {
894            let (tx, control, p) = (tx.clone(), control.clone(), p.clone());
895            Box::pin(async move {
896                let (rtx, rrx) = oneshot::channel();
897                tx.send(Cmd::<Q, R>::Connect { peer, addrs, reply: rtx }).map_err(|_| stopped())?;
898                tokio::time::timeout(Duration::from_secs(30), rrx)
899                    .await
900                    .map_err(|_| NetError::Network(format!("cannot reach {peer} in time")))?
901                    .map_err(|_| stopped())??;
902                crate::stream::open(control, peer, p, limits).await
903            })
904        })
905    }
906
907    /// [`Node::open_stream`] for async callers (any executor).
908    pub async fn open_stream_async(&self, peer: PeerId, addrs: &[Multiaddr], protocol: &str, limits: Limits) -> Result<Stream> {
909        let p = StreamProtocol::try_from_owned(protocol.to_string()).map_err(|e| NetError::Network(format!("bad protocol id {protocol}: {e}")))?;
910        let (tx, rx) = oneshot::channel();
911        self.tx.send(Cmd::Connect { peer, addrs: addrs.to_vec(), reply: tx }).map_err(|_| stopped())?;
912        let (rt, control) = &self.streams;
913        let control = control.clone();
914        rt.spawn(async move {
915            tokio::time::timeout(Duration::from_secs(30), rx)
916                .await
917                .map_err(|_| NetError::Network(format!("cannot reach {peer} in time")))?
918                .map_err(|_| stopped())??;
919            crate::stream::open(control, peer, p, limits).await
920        })
921        .await
922        .map_err(|_| stopped())?
923    }
924
925    /// Serve app calls for `app` (`a-z`, `0-9`, `-`; up to 64 characters): calls to it go to
926    /// `handler`, and peers learn (through identify) that this node serves it. Serving
927    /// again replaces the handler. While a node serves any app it keeps its relay
928    /// reservations, even paused.
929    pub fn serve_app(&self, app: &str, handler: Arc<dyn AppHandler>) -> std::result::Result<(), AppError> {
930        let (rt, control) = &self.streams;
931        self.apps.serve(rt, control, app, handler, self.app_limits)
932    }
933
934    /// Stop serving `app`; returns whether it was served. Calls under way carry on.
935    pub fn stop_serving_app(&self, app: &str) -> bool {
936        self.apps.unserve(app)
937    }
938
939    /// The apps this node serves.
940    pub fn served_apps(&self) -> Vec<String> {
941        self.apps.apps()
942    }
943
944    /// The apps a connected peer announced (`None`: not connected, or not identified yet).
945    pub fn peer_apps(&self, peer: PeerId) -> Option<Vec<String>> {
946        self.call(|reply| Cmd::PeerApps { peer, reply }, Duration::from_secs(5)).ok().flatten()
947    }
948
949    /// The peers that serve `app` for `locator`: a peer id, a user id (32 hex digits) or a
950    /// name bound to a user by a `_weirdnet.<name>` TXT record. Users are found through the
951    /// names servers (relays this node holds a reservation on, and the configured ones) and
952    /// the DHT. Connects to each peer (directly first, then through the relay circuits in its
953    /// record) to learn what it serves; the addresses are kept for [`Node::app_call`].
954    pub fn resolve_app(&self, app: &str, locator: &str) -> std::result::Result<Vec<(PeerId, Vec<Multiaddr>)>, AppError> {
955        crate::app::Server::check_app(app)?;
956        let locator = locator.trim();
957        let mut found: Vec<(PeerId, Vec<Multiaddr>)> = vec![];
958        if let Ok(peer) = locator.parse::<PeerId>() {
959            let mut addrs = self.find_peer(peer).unwrap_or_default();
960            for (_, a) in self.names_servers() {
961                for base in a {
962                    let base: Multiaddr = base.iter().take_while(|p| *p != Protocol::P2pCircuit).collect();
963                    addrs.push(base.with(Protocol::P2pCircuit).with(Protocol::P2p(peer)));
964                }
965            }
966            found.push((peer, addrs));
967        } else {
968            let user = if is_user_id(locator) { locator.to_string() } else { self.resolve_name(locator)? };
969            match self.lookup(&user) {
970                Lookup::Found(rec) => {
971                    let peer: PeerId = rec.cert.peer_id.parse().map_err(|_| AppError::Protocol("a record with a bad peer id".into()))?;
972                    let mut addrs: Vec<Multiaddr> = rec.addrs.iter().filter_map(|a| a.parse().ok()).collect();
973                    if let Some(home) = rec.home_relay.as_deref().and_then(|a| a.parse::<Multiaddr>().ok()) {
974                        let c = home.with(Protocol::P2pCircuit).with(Protocol::P2p(peer));
975                        if !addrs.contains(&c) {
976                            addrs.push(c);
977                        }
978                    }
979                    found.push((peer, addrs));
980                }
981                Lookup::Withdrawn(_) | Lookup::NotFound => return Err(AppError::NotFound),
982            }
983        }
984        let mut out = vec![];
985        let mut reached = false;
986        let mut last = AppError::NotFound;
987        for (peer, addrs) in found {
988            if peer == self.peer_id {
989                if self.apps.serves(app) {
990                    out.push((peer, vec![]));
991                } else {
992                    last = AppError::NoHandler;
993                }
994                continue;
995            }
996            let wait = self.request_timeout;
997            let rt = self.streams.0.clone();
998            let tx = self.tx.clone();
999            let a2 = addrs.clone();
1000            let r = futures::executor::block_on(rt.spawn(async move { connect_phased(tx, peer, a2, tokio::time::Instant::now() + wait).await }));
1001            match r.unwrap_or_else(|_| Err(AppError::Unreachable("the node stopped".into()))) {
1002                Ok(()) => reached = true,
1003                Err(e) => {
1004                    last = e;
1005                    continue;
1006                }
1007            }
1008            // identify comes right after connecting
1009            let until = std::time::Instant::now() + Duration::from_secs(5);
1010            let apps = loop {
1011                if let Some(a) = self.peer_apps(peer) {
1012                    break a;
1013                }
1014                if std::time::Instant::now() > until {
1015                    break vec![];
1016                }
1017                std::thread::sleep(Duration::from_millis(20));
1018            };
1019            self.app_addrs.lock().unwrap().insert(peer, addrs.clone());
1020            if apps.iter().any(|a| a == app) {
1021                out.push((peer, addrs));
1022            } else {
1023                last = AppError::NoHandler;
1024            }
1025        }
1026        if out.is_empty() {
1027            return Err(if reached { AppError::NoHandler } else { last });
1028        }
1029        Ok(out)
1030    }
1031
1032    /// The user a name is bound to (`_weirdnet.<name>` TXT, through the node's DNS servers).
1033    fn resolve_name(&self, name: &str) -> std::result::Result<String, AppError> {
1034        let servers = self.dns_servers.clone();
1035        let q = crate::names::binding_name(name);
1036        let rt = self.streams.0.clone();
1037        futures::executor::block_on(rt.spawn(async move { txt_records(&servers, &q).await }))
1038            .map_err(|_| AppError::Unreachable("the node stopped".into()))??
1039            .iter()
1040            .find_map(|t| crate::names::parse_binding(t).ok())
1041            .ok_or(AppError::NotFound)
1042    }
1043
1044    /// Call `app` on `peer`: connect if needed (directly first, then through the relay
1045    /// circuits [`Node::resolve_app`] found), open a stream and send `req`. `timeout` covers
1046    /// getting the response head; the bodies then may go on as long as bytes keep flowing
1047    /// (see [`NodeConfig::app_idle_timeout`]). Dropping the future or the response body
1048    /// cancels the call. Works on any executor.
1049    pub async fn app_call(&self, peer: PeerId, req: AppRequest, timeout: Duration) -> std::result::Result<AppResponse, AppError> {
1050        let addrs = self.app_addrs.lock().unwrap().get(&peer).cloned().unwrap_or_default();
1051        self.app_call_via(peer, &addrs, req, timeout).await
1052    }
1053
1054    /// [`Node::app_call`] trying `addrs` (direct addresses and circuits) to reach the peer.
1055    pub async fn app_call_via(
1056        &self,
1057        peer: PeerId,
1058        addrs: &[Multiaddr],
1059        req: AppRequest,
1060        timeout: Duration,
1061    ) -> std::result::Result<AppResponse, AppError> {
1062        if peer == self.peer_id {
1063            return Err(AppError::Unreachable("this node".into()));
1064        }
1065        let (rt, control) = &self.streams;
1066        let (rt, control, tx, limits, addrs) = (rt.clone(), control.clone(), self.tx.clone(), self.app_limits, addrs.to_vec());
1067        let rt2 = rt.clone();
1068        let task = rt.spawn(async move {
1069            let deadline = tokio::time::Instant::now() + timeout;
1070            connect_phased(tx, peer, addrs, deadline).await?;
1071            crate::app::call(rt2, control, peer, req, limits, deadline).await
1072        });
1073        let _guard = crate::app::AbortOnDrop(task.abort_handle());
1074        task.await.map_err(|_| AppError::Unreachable("the node stopped".into()))?
1075    }
1076
1077    /// [`Node::app_call`] for blocking callers.
1078    pub fn app_call_blocking(&self, peer: PeerId, req: AppRequest, timeout: Duration) -> std::result::Result<AppResponse, AppError> {
1079        futures::executor::block_on(self.app_call(peer, req, timeout))
1080    }
1081
1082    /// Listen on one more address; returns the address it got.
1083    pub fn listen(&self, addr: Multiaddr) -> Result<Multiaddr> {
1084        self.call(|reply| Cmd::Listen { addr, reply }, Duration::from_secs(20))
1085    }
1086
1087    /// Reserve a slot on a relay (`…/p2p/RELAY`).
1088    pub fn add_relay(&self, addr: Multiaddr) -> Result<()> {
1089        self.tx.send(Cmd::AddRelay { addr }).map_err(|_| stopped())
1090    }
1091
1092    /// Whether the node thread still runs.
1093    pub fn running(&self) -> bool {
1094        self.thread.as_ref().is_some_and(|t| !t.is_finished())
1095    }
1096
1097    pub fn stop(mut self) {
1098        self.shutdown();
1099    }
1100
1101    /// Ask the node to stop without waiting (others may still hold it).
1102    pub fn halt(&self) {
1103        let _ = self.tx.send(Cmd::Stop);
1104    }
1105
1106    fn shutdown(&mut self) {
1107        let _ = self.tx.send(Cmd::Stop);
1108        if let Some(t) = self.thread.take() {
1109            let _ = t.join();
1110        }
1111    }
1112}
1113
1114impl<Q: Message, R: Message> Drop for Node<Q, R> {
1115    fn drop(&mut self) {
1116        self.shutdown();
1117    }
1118}
1119
1120/// The resolver: the given servers, else the system's, else Cloudflare's and Google's.
1121/// A user id: 32 lowercase hex digits.
1122fn is_user_id(s: &str) -> bool {
1123    s.len() == 32 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1124}
1125
1126/// The TXT records of `name` (none if it has none).
1127async fn txt_records(servers: &[std::net::SocketAddr], name: &str) -> std::result::Result<Vec<String>, AppError> {
1128    use hickory_resolver::proto::rr::{RData, RecordType};
1129    let (config, opts) = dns_config(servers);
1130    let r = hickory_resolver::Resolver::builder_with_config(config, hickory_resolver::net::runtime::TokioRuntimeProvider::default())
1131        .with_options(opts)
1132        .build()
1133        .map_err(|e| AppError::Unreachable(format!("dns: {e}")))?;
1134    let l = match r.lookup(name, RecordType::TXT).await {
1135        Ok(l) => l,
1136        Err(e) if e.is_no_records_found() || e.is_nx_domain() => return Ok(vec![]),
1137        Err(e) => return Err(AppError::Unreachable(format!("dns: {e}"))),
1138    };
1139    Ok(l.answers()
1140        .iter()
1141        .filter_map(|rec| match &rec.data {
1142            RData::TXT(t) => Some(t.txt_data.iter().map(|b| String::from_utf8_lossy(b)).collect::<String>()),
1143            _ => None,
1144        })
1145        .collect())
1146}
1147
1148/// Connect to `peer` by `addrs`: the direct ones first (a few seconds when circuits are
1149/// left), then the relay circuits (the relay is dialed on all its addresses).
1150async fn connect_phased<Q: Message, R: Message>(
1151    tx: mpsc::UnboundedSender<Cmd<Q, R>>,
1152    peer: PeerId,
1153    addrs: Vec<Multiaddr>,
1154    deadline: tokio::time::Instant,
1155) -> std::result::Result<(), AppError> {
1156    let (circuits, direct): (Vec<Multiaddr>, Vec<Multiaddr>) = addrs.into_iter().partition(|a| a.iter().any(|p| p == Protocol::P2pCircuit));
1157    let connect = |addrs: Vec<Multiaddr>, until: tokio::time::Instant| {
1158        let tx = tx.clone();
1159        async move {
1160            let (rtx, rrx) = oneshot::channel();
1161            tx.send(Cmd::Connect { peer, addrs, reply: rtx }).map_err(|_| AppError::Unreachable("the node stopped".into()))?;
1162            match tokio::time::timeout_at(until, rrx).await {
1163                Err(_) => Err(AppError::TimedOut),
1164                Ok(Err(_)) => Err(AppError::Unreachable("the node stopped".into())),
1165                Ok(Ok(Err(e))) => Err(AppError::Unreachable(e.to_string())),
1166                Ok(Ok(Ok(_))) => Ok(()),
1167            }
1168        }
1169    };
1170    if circuits.is_empty() {
1171        return connect(direct, deadline).await;
1172    }
1173    let first = (tokio::time::Instant::now() + DIRECT_FIRST).min(deadline);
1174    let direct_err = match connect(direct, first).await {
1175        Ok(()) => return Ok(()),
1176        Err(e) => e,
1177    };
1178    if tokio::time::Instant::now() >= deadline {
1179        return Err(direct_err);
1180    }
1181    connect(circuits, deadline).await
1182}
1183
1184/// How long app calls try a peer's direct addresses before its relay circuits.
1185const DIRECT_FIRST: Duration = Duration::from_secs(4);
1186
1187fn dns_config(servers: &[std::net::SocketAddr]) -> (libp2p::dns::ResolverConfig, libp2p::dns::ResolverOpts) {
1188    use hickory_resolver::config::{CLOUDFLARE, GOOGLE, NameServerConfig, ResolverConfig};
1189    if !servers.is_empty() {
1190        let ns = servers
1191            .iter()
1192            .map(|a| {
1193                let mut n = NameServerConfig::udp_and_tcp(a.ip());
1194                for c in &mut n.connections {
1195                    c.port = a.port();
1196                }
1197                n
1198            })
1199            .collect();
1200        return (ResolverConfig::from_name_servers(ns), Default::default());
1201    }
1202    match hickory_resolver::system_conf::read_system_conf() {
1203        Ok((c, o)) if !c.name_servers().is_empty() => (c, o),
1204        _ => {
1205            let ns = CLOUDFLARE.udp_and_tcp().chain(GOOGLE.udp_and_tcp()).collect();
1206            (ResolverConfig::from_name_servers(ns), Default::default())
1207        }
1208    }
1209}
1210
1211/// Opens a stream of one protocol to a peer, connecting first (held by services like the ingress).
1212pub(crate) type Opener = Arc<dyn Fn(PeerId, Vec<Multiaddr>) -> futures::future::BoxFuture<'static, Result<Stream>> + Send + Sync>;
1213
1214/// A DHT lookup collecting entries, and who waits for them.
1215type Locating = (Vec<crate::locator::LocatorRecord>, oneshot::Sender<Result<Vec<crate::locator::LocatorRecord>>>);
1216type Gathering = (Vec<Entry>, oneshot::Sender<Result<Vec<Entry>>>);
1217/// A DHT search for one peer's addresses.
1218type Finding = (PeerId, oneshot::Sender<Result<Vec<Multiaddr>>>);
1219
1220struct Loop<Q: Message, R: Message> {
1221    profile: &'static Profile,
1222    swarm: Swarm<Behaviour<Q, R>>,
1223    cfg: NodeConfig,
1224    handler: Arc<dyn Handler<Q, R>>,
1225    status: Arc<Mutex<Status>>,
1226    pending: HashMap<OutboundRequestId, oneshot::Sender<Result<R>>>,
1227    dials: Vec<(Multiaddr, Option<PeerId>, oneshot::Sender<Result<PeerId>>)>,
1228    listens: HashMap<libp2p::core::transport::ListenerId, oneshot::Sender<Result<Multiaddr>>>,
1229    relays: HashSet<PeerId>,
1230    relay_listening: HashSet<PeerId>,
1231    /// Each relay's circuit listener and when it was asked for (to retry a stuck one).
1232    relay_listeners: HashMap<PeerId, (Multiaddr, libp2p::core::transport::ListenerId, std::time::Instant)>,
1233    resp_tx: mpsc::UnboundedSender<(request_response::ResponseChannel<R>, R)>,
1234    resp_rx: mpsc::UnboundedReceiver<(request_response::ResponseChannel<R>, R)>,
1235    names_pending: HashMap<OutboundRequestId, oneshot::Sender<Result<NamesResponse>>>,
1236    names_tx: mpsc::UnboundedSender<(request_response::ResponseChannel<NamesResponse>, NamesResponse)>,
1237    names_rx: mpsc::UnboundedReceiver<(request_response::ResponseChannel<NamesResponse>, NamesResponse)>,
1238    puts: HashMap<kad::QueryId, oneshot::Sender<Result<()>>>,
1239    gets: HashMap<kad::QueryId, Gathering>,
1240    finds: HashMap<kad::QueryId, Finding>,
1241    provs: HashMap<kad::QueryId, Providing>,
1242    lgets: HashMap<kad::QueryId, Locating>,
1243    addr_book: HashMap<PeerId, Vec<Multiaddr>>,
1244    /// What connected peers say they listen on (identify), for provider records without addresses.
1245    heard: HashMap<PeerId, Vec<Multiaddr>>,
1246    /// Commands that go through a relay we are still connecting to (a bootstrap dial to the
1247    /// same relay under way makes libp2p's relay transport skip its own dial and fail).
1248    deferred: Vec<(PeerId, std::time::Instant, Cmd<Q, R>)>,
1249    /// Open connections: whose, and whether through a relay.
1250    conns: HashMap<libp2p::swarm::ConnectionId, (PeerId, bool)>,
1251    hub: Hub,
1252    status_tx: Option<tokio::sync::watch::Sender<Status>>,
1253    /// Listeners up now (paused nodes close them).
1254    listeners: HashSet<libp2p::core::transport::ListenerId>,
1255    paused: bool,
1256    /// Relays whose reservation went away, and when to ask again.
1257    relay_retry: Vec<(Multiaddr, std::time::Instant, Duration)>,
1258    /// How long to wait before asking a relay again; reset when it accepts.
1259    relay_backoff: HashMap<PeerId, Duration>,
1260    /// Every address of each relay (all dialed at once).
1261    relay_addrs: HashMap<PeerId, Vec<Multiaddr>>,
1262    /// Relays being dialed; reserve once connected.
1263    relay_pending: HashSet<PeerId>,
1264    /// The node serves apps: keep relay reservations, even paused.
1265    serving: Arc<std::sync::atomic::AtomicBool>,
1266    /// The apps each connected peer announces (identify).
1267    peer_apps: HashMap<PeerId, Vec<String>>,
1268}
1269
1270fn path_of(relayed: bool) -> Path {
1271    if relayed { Path::Relayed } else { Path::Direct }
1272}
1273
1274fn endpoint_relayed(e: &libp2p::core::ConnectedPoint) -> bool {
1275    let circuit = |a: &Multiaddr| a.iter().any(|p| p == Protocol::P2pCircuit);
1276    match e {
1277        libp2p::core::ConnectedPoint::Dialer { address, .. } => circuit(address),
1278        libp2p::core::ConnectedPoint::Listener { local_addr, send_back_addr } => circuit(local_addr) || circuit(send_back_addr),
1279    }
1280}
1281
1282/// How long a command waits for its relay connection before it is tried anyway.
1283const RELAY_WAIT: Duration = Duration::from_secs(10);
1284
1285impl<Q: Message, R: Message> Loop<Q, R> {
1286    fn new(
1287        profile: &'static Profile,
1288        swarm: Swarm<Behaviour<Q, R>>,
1289        cfg: NodeConfig,
1290        handler: Arc<dyn Handler<Q, R>>,
1291        status: Arc<Mutex<Status>>,
1292    ) -> Self {
1293        let (resp_tx, resp_rx) = mpsc::unbounded_channel();
1294        let (names_tx, names_rx) = mpsc::unbounded_channel();
1295        Loop {
1296            profile,
1297            swarm,
1298            cfg,
1299            handler,
1300            status,
1301            pending: HashMap::new(),
1302            dials: vec![],
1303            listens: HashMap::new(),
1304            relays: HashSet::new(),
1305            relay_listening: HashSet::new(),
1306            relay_listeners: HashMap::new(),
1307            resp_tx,
1308            resp_rx,
1309            names_pending: HashMap::new(),
1310            names_tx,
1311            names_rx,
1312            puts: HashMap::new(),
1313            gets: HashMap::new(),
1314            finds: HashMap::new(),
1315            provs: HashMap::new(),
1316            lgets: HashMap::new(),
1317            addr_book: HashMap::new(),
1318            heard: HashMap::new(),
1319            deferred: vec![],
1320            conns: HashMap::new(),
1321            hub: Hub::default(),
1322            status_tx: None,
1323            listeners: HashSet::new(),
1324            paused: false,
1325            relay_retry: vec![],
1326            relay_backoff: HashMap::new(),
1327            relay_addrs: HashMap::new(),
1328            relay_pending: HashSet::new(),
1329            serving: Arc::new(std::sync::atomic::AtomicBool::new(false)),
1330            peer_apps: HashMap::new(),
1331        }
1332    }
1333
1334    fn update(&self, f: impl FnOnce(&mut Status)) {
1335        if let Ok(mut s) = self.status.lock() {
1336            f(&mut s);
1337            if let Some(tx) = &self.status_tx {
1338                tx.send_if_modified(|old| {
1339                    let changed = *old != *s;
1340                    if changed {
1341                        *old = s.clone();
1342                    }
1343                    changed
1344                });
1345            }
1346        }
1347    }
1348
1349    fn refresh(&self) {
1350        let connected: Vec<String> = self.swarm.connected_peers().map(|p| p.to_string()).collect();
1351        let listening: Vec<String> = self.swarm.listeners().map(|a| a.to_string()).collect();
1352        let external: Vec<String> = self.swarm.external_addresses().map(|a| a.to_string()).collect();
1353        self.update(|s| {
1354            s.connected = connected;
1355            s.listening = listening;
1356            s.external = external;
1357        });
1358    }
1359
1360    fn seen(&self, s: Sighting) {
1361        let h = self.handler.clone();
1362        tokio::task::spawn_blocking(move || h.seen(s));
1363    }
1364
1365    async fn run(&mut self, mut rx: mpsc::UnboundedReceiver<Cmd<Q, R>>, ready: std::sync::mpsc::Sender<Result<()>>) {
1366        // listen
1367        let mut waiting = 0usize;
1368        let mut ready = Some(ready);
1369        for a in self.cfg.listen.clone() {
1370            match self.swarm.listen_on(a.clone()) {
1371                Ok(_) => waiting += 1,
1372                Err(e) => tracing::warn!("network: cannot listen on {a}: {e}"),
1373            }
1374        }
1375        if !self.cfg.listen.is_empty() && waiting == 0 {
1376            if let Some(r) = ready.take() {
1377                let _ = r.send(Err(NetError::Network("could not listen on any address".into())));
1378            }
1379            return;
1380        }
1381        // relays first: a reservation dials its relay, and a second dial to the same peer
1382        // already under way would make the relay client skip its own
1383        for r in &self.cfg.relays {
1384            if let Some(p) = addr_peer(r) {
1385                let v = self.relay_addrs.entry(p).or_default();
1386                if !v.contains(r) {
1387                    v.push(r.clone());
1388                }
1389            }
1390        }
1391        for r in self.cfg.relays.clone() {
1392            self.add_relay(r);
1393        }
1394        if self.cfg.discovery.is_enabled() {
1395            for b in self.cfg.bootstrap.clone() {
1396                if let Some(p) = addr_peer(&b) {
1397                    self.swarm.behaviour_mut().kad.add_address(&p, b.clone());
1398                    if !self.relay_listening.contains(&p) {
1399                        let _ = self.swarm.dial(b);
1400                    }
1401                }
1402            }
1403        }
1404        for hint in self.cfg.peers.clone() {
1405            self.dial_hint(&hint);
1406        }
1407        if self.cfg.relay_server && self.cfg.discovery.is_enabled() {
1408            self.swarm.behaviour_mut().kad.set_mode(Some(kad::Mode::Server));
1409        }
1410        if waiting == 0
1411            && let Some(r) = ready.take()
1412        {
1413            let _ = r.send(Ok(()));
1414        }
1415        let ready_deadline = tokio::time::sleep(Duration::from_secs(5));
1416        tokio::pin!(ready_deadline);
1417        let mut tick = tokio::time::interval(Duration::from_secs(60));
1418        let mut check = tokio::time::interval(Duration::from_secs(1));
1419        loop {
1420            tokio::select! {
1421                cmd = rx.recv() => match cmd {
1422                    None | Some(Cmd::Stop) => break,
1423                    Some(c) => self.command(c),
1424                },
1425                Some((ch, resp)) = self.resp_rx.recv() => {
1426                    let _ = self.swarm.behaviour_mut().rr.send_response(ch, resp);
1427                }
1428                Some((ch, resp)) = self.names_rx.recv() => {
1429                    let _ = self.swarm.behaviour_mut().names.send_response(ch, resp);
1430                }
1431                ev = self.swarm.select_next_some() => {
1432                    let new_listen = matches!(ev, SwarmEvent::NewListenAddr { .. });
1433                    self.event(ev);
1434                    if new_listen && waiting > 0 {
1435                        waiting -= 1;
1436                        if waiting == 0 && let Some(r) = ready.take() {
1437                            let _ = r.send(Ok(()));
1438                        }
1439                    }
1440                }
1441                _ = &mut ready_deadline, if ready.is_some() => {
1442                    if let Some(r) = ready.take() {
1443                        let _ = r.send(Ok(()));
1444                    }
1445                }
1446                _ = tick.tick() => self.periodic(),
1447                _ = check.tick() => {
1448                    self.retry_stuck_reservations();
1449                    self.retry_lost_reservations();
1450                    self.release_deferred(None);
1451                }
1452            }
1453        }
1454        for (_, tx) in self.pending.drain() {
1455            let _ = tx.send(Err(NetError::Network("the node stopped".into())));
1456        }
1457        for (_, tx) in self.names_pending.drain() {
1458            let _ = tx.send(Err(NetError::Network("the node stopped".into())));
1459        }
1460    }
1461
1462    fn periodic(&mut self) {
1463        if let Some(n) = &self.cfg.names_server {
1464            n.0.prune(crate::now_ms());
1465        }
1466        if self.paused {
1467            return;
1468        }
1469        if !self.cfg.discovery.is_enabled() {
1470            return;
1471        }
1472        let k = &mut self.swarm.behaviour_mut().kad;
1473        // With an empty routing table there is no one to bootstrap from; asking
1474        // anyway only makes libp2p warn "No known peers" every tick.
1475        if routing_empty(k) {
1476            return;
1477        }
1478        if k.bootstrap().is_ok() {
1479            k.get_providers(kad::RecordKey::new(&self.profile.relay_key));
1480            if self.cfg.relay_server {
1481                let _ = k.start_providing(kad::RecordKey::new(&self.profile.relay_key));
1482            }
1483        }
1484    }
1485
1486    fn add_relay(&mut self, addr: Multiaddr) {
1487        let Some(peer) = addr_peer(&addr) else {
1488            tracing::warn!("network: relay address {addr} has no /p2p/ peer id");
1489            return;
1490        };
1491        if peer == *self.swarm.local_peer_id() {
1492            return;
1493        }
1494        let known = self.relay_addrs.entry(peer).or_default();
1495        if !known.contains(&addr) {
1496            known.push(addr.clone());
1497        }
1498        self.swarm.add_peer_address(peer, addr.clone());
1499        if !self.relay_listening.insert(peer) {
1500            return;
1501        }
1502        self.relays.insert(peer);
1503        if self.swarm.is_connected(&peer) {
1504            return self.reserve_on(peer);
1505        }
1506        // dial every address of the relay at once (TCP, QUIC, WSS…) and reserve once one
1507        // connects: the relay client would dial only the one address it was given
1508        use libp2p::swarm::dial_opts::{DialOpts, PeerCondition};
1509        let addrs = self.relay_addrs.get(&peer).cloned().unwrap_or_default();
1510        match self.swarm.dial(DialOpts::peer_id(peer).addresses(addrs).condition(PeerCondition::DisconnectedAndNotDialing).build()) {
1511            Ok(()) | Err(libp2p::swarm::DialError::DialPeerConditionFalse(_)) => {
1512                self.relay_pending.insert(peer);
1513            }
1514            Err(e) => {
1515                tracing::warn!("network: cannot dial relay {peer}: {e}");
1516                self.relay_listening.remove(&peer);
1517                self.retry_relay_later(peer, addr);
1518            }
1519        }
1520    }
1521
1522    /// Ask a connected relay for a reservation (listen through it).
1523    fn reserve_on(&mut self, peer: PeerId) {
1524        let Some(addr) = self.relay_addrs.get(&peer).and_then(|v| v.first().cloned()) else { return };
1525        let circuit = addr.with(Protocol::P2pCircuit);
1526        match self.swarm.listen_on(circuit.clone()) {
1527            Ok(id) => {
1528                self.relay_listeners.insert(peer, (circuit, id, std::time::Instant::now()));
1529            }
1530            Err(e) => {
1531                tracing::warn!("network: cannot listen through relay {circuit}: {e}");
1532                self.relay_listening.remove(&peer);
1533            }
1534        }
1535    }
1536
1537    /// Dial a relay again later, backing off to a minute.
1538    fn retry_relay_later(&mut self, relay: PeerId, addr: Multiaddr) {
1539        let wait = self.relay_backoff.get(&relay).copied().unwrap_or(Duration::from_secs(1));
1540        self.relay_backoff.insert(relay, (wait * 2).min(Duration::from_secs(60)));
1541        self.relay_retry.retain(|(a, _, _)| addr_peer(a) != Some(relay));
1542        self.relay_retry.push((addr, std::time::Instant::now() + wait, wait));
1543    }
1544
1545    fn keeps_relays(&self) -> bool {
1546        self.serving.load(std::sync::atomic::Ordering::SeqCst)
1547    }
1548
1549    /// A relay's circuit listener closed (its connection went away, or we paused): the
1550    /// reservation is gone; ask again later unless paused.
1551    fn relay_listener_closed(&mut self, id: libp2p::core::transport::ListenerId) {
1552        let Some(relay) = self.relay_listeners.iter().find(|(_, (_, l, _))| *l == id).map(|(p, _)| *p) else { return };
1553        let Some((mut circuit, _, _)) = self.relay_listeners.remove(&relay) else { return };
1554        self.relay_listening.remove(&relay);
1555        let r = relay.to_string();
1556        self.update(|s| s.reservations.retain(|x| *x != r));
1557        self.hub.send(Event::ReservationLost { relay });
1558        circuit.pop();
1559        if !self.paused || self.keeps_relays() {
1560            let wait = self.relay_backoff.get(&relay).copied().unwrap_or(Duration::from_secs(1));
1561            self.relay_backoff.insert(relay, (wait * 2).min(Duration::from_secs(60)));
1562            self.relay_retry.retain(|(a, _, _)| *a != circuit);
1563            self.relay_retry.push((circuit, std::time::Instant::now() + wait, wait));
1564        }
1565    }
1566
1567    fn retry_lost_reservations(&mut self) {
1568        if self.paused && !self.keeps_relays() {
1569            return;
1570        }
1571        let now = std::time::Instant::now();
1572        let (due, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut self.relay_retry).into_iter().partition(|(_, at, _)| *at <= now);
1573        self.relay_retry = keep;
1574        for (addr, _, wait) in due {
1575            let peer = addr_peer(&addr);
1576            self.add_relay(addr.clone());
1577            // not listening through it (couldn't ask): try again, backing off to a minute
1578            if peer.is_some_and(|p| !self.relay_listening.contains(&p)) {
1579                let wait = (wait * 2).min(Duration::from_secs(60));
1580                self.relay_retry.push((addr, now + wait, wait));
1581            }
1582        }
1583    }
1584
1585    /// Close every connection and listener (relay circuits too).
1586    fn go_quiet(&mut self) {
1587        // a node serving apps stays reachable through its relays
1588        let keep = self.keeps_relays();
1589        let kept: HashSet<_> = if keep { self.relay_listeners.values().map(|(_, id, _)| *id).collect() } else { HashSet::new() };
1590        for id in self.listeners.clone() {
1591            if !kept.contains(&id) {
1592                self.swarm.remove_listener(id);
1593            }
1594        }
1595        if !keep {
1596            for (_, (_, id, _)) in self.relay_listeners.clone() {
1597                self.swarm.remove_listener(id);
1598            }
1599        }
1600        let peers: Vec<PeerId> = self.swarm.connected_peers().copied().filter(|p| !(keep && self.relays.contains(p))).collect();
1601        for p in peers {
1602            let _ = self.swarm.disconnect_peer_id(p);
1603        }
1604    }
1605
1606    /// Listen, reserve and bootstrap again.
1607    fn wake(&mut self, listen: bool) {
1608        if listen {
1609            for a in self.cfg.listen.clone() {
1610                if let Err(e) = self.swarm.listen_on(a.clone()) {
1611                    tracing::warn!("network: cannot listen on {a}: {e}");
1612                }
1613            }
1614        }
1615        let relays: Vec<Multiaddr> = self.cfg.relays.iter().cloned().chain(self.relay_retry.drain(..).map(|(a, _, _)| a)).collect();
1616        for r in relays {
1617            self.add_relay(r);
1618        }
1619        if self.cfg.discovery.is_enabled() {
1620            for b in self.cfg.bootstrap.clone() {
1621                if let Some(p) = addr_peer(&b)
1622                    && !self.relay_listening.contains(&p)
1623                {
1624                    let _ = self.swarm.dial(b);
1625                }
1626            }
1627            let k = &mut self.swarm.behaviour_mut().kad;
1628            if !routing_empty(k) {
1629                let _ = k.bootstrap();
1630            }
1631        }
1632        for hint in self.cfg.peers.clone() {
1633            self.dial_hint(&hint);
1634        }
1635    }
1636
1637    /// A reservation asked for while another dial to the relay was under way is never sent
1638    /// (libp2p's relay client skips its own dial then); once connected, ask again.
1639    fn retry_stuck_reservations(&mut self) {
1640        let reserved = self.status.lock().map(|s| s.reservations.clone()).unwrap_or_default();
1641        let stuck: Vec<PeerId> = self
1642            .relay_listeners
1643            .iter()
1644            .filter(|(p, (_, _, at))| at.elapsed() > Duration::from_secs(3) && !reserved.contains(&p.to_string()) && self.swarm.is_connected(p))
1645            .map(|(p, _)| *p)
1646            .collect();
1647        for p in stuck {
1648            if let Some((circuit, id, _)) = self.relay_listeners.remove(&p) {
1649                tracing::debug!("network: asking relay {p} for a reservation again");
1650                self.swarm.remove_listener(id);
1651                match self.swarm.listen_on(circuit.clone()) {
1652                    Ok(id) => {
1653                        self.relay_listeners.insert(p, (circuit, id, std::time::Instant::now()));
1654                    }
1655                    Err(e) => tracing::warn!("network: cannot listen through relay {circuit}: {e}"),
1656                }
1657            }
1658        }
1659    }
1660
1661    fn command(&mut self, c: Cmd<Q, R>) {
1662        let addrs: Vec<Multiaddr> = match &c {
1663            Cmd::Request { addrs, .. } | Cmd::Names { addrs, .. } => addrs.clone(),
1664            Cmd::Dial { addr, .. } => vec![addr.clone()],
1665            Cmd::Connect { peer, addrs, .. } if !self.swarm.is_connected(peer) => addrs.clone(),
1666            _ => vec![],
1667        };
1668        // through a relay we aren't connected to yet: connect to it first (or wait for the
1669        // dial already under way), then send
1670        let waiting = addrs.iter().filter_map(circuit_relay).find(|(r, _)| *r != *self.swarm.local_peer_id() && !self.swarm.is_connected(r));
1671        if let Some((relay, raddr)) = waiting {
1672            use libp2p::swarm::dial_opts::{DialOpts, PeerCondition};
1673            let mut all = vec![raddr];
1674            for a in self.relay_addrs.get(&relay).into_iter().flatten() {
1675                if !all.contains(a) {
1676                    all.push(a.clone());
1677                }
1678            }
1679            let _ = self.swarm.dial(DialOpts::peer_id(relay).addresses(all).condition(PeerCondition::DisconnectedAndNotDialing).build());
1680            self.deferred.push((relay, std::time::Instant::now(), c));
1681            return;
1682        }
1683        self.execute(c);
1684    }
1685
1686    /// Send the commands that waited for `relay` (connected, or its dial failed), or every
1687    /// one that waited too long (`None`).
1688    fn release_deferred(&mut self, relay: Option<PeerId>) {
1689        let (ready, keep): (Vec<_>, Vec<_>) =
1690            std::mem::take(&mut self.deferred).into_iter().partition(|(r, at, _)| relay.map_or(at.elapsed() > RELAY_WAIT, |p| p == *r));
1691        self.deferred = keep;
1692        for (_, _, c) in ready {
1693            self.execute(c);
1694        }
1695    }
1696
1697    fn require_discovery(&self) -> Result<()> {
1698        if self.cfg.discovery.is_enabled() { Ok(()) } else { Err(NetError::Network("peer discovery is disabled".into())) }
1699    }
1700
1701    /// Remember addresses and dial; does not reserve a relay or grant trust.
1702    fn dial_hint(&mut self, hint: &PeerHint) {
1703        let Ok(peer) = hint.peer_id() else {
1704            tracing::warn!("network: invalid manual peer id {}", hint.peer_id);
1705            return;
1706        };
1707        if peer == *self.swarm.local_peer_id() {
1708            return;
1709        }
1710        let Ok(addrs) = hint.multiaddrs() else {
1711            tracing::warn!("network: invalid manual peer addresses for {peer}");
1712            return;
1713        };
1714        for a in &addrs {
1715            self.swarm.add_peer_address(peer, a.clone());
1716            if self.cfg.discovery.is_enabled() {
1717                self.swarm.behaviour_mut().kad.add_address(&peer, a.clone());
1718            }
1719        }
1720        if self.paused || self.swarm.is_connected(&peer) {
1721            return;
1722        }
1723        use libp2p::swarm::dial_opts::{DialOpts, PeerCondition};
1724        let _ = self.swarm.dial(DialOpts::peer_id(peer).addresses(addrs).condition(PeerCondition::DisconnectedAndNotDialing).build());
1725    }
1726
1727    fn remember_peer(&mut self, hint: PeerHint) -> Result<()> {
1728        hint.multiaddrs()?;
1729        if let Some(existing) = self.cfg.peers.iter_mut().find(|p| p.peer_id == hint.peer_id) {
1730            for a in &hint.addrs {
1731                if !existing.addrs.contains(a) {
1732                    existing.addrs.push(a.clone());
1733                }
1734            }
1735            let merged = existing.clone();
1736            self.dial_hint(&merged);
1737        } else {
1738            self.dial_hint(&hint);
1739            self.cfg.peers.push(hint);
1740        }
1741        Ok(())
1742    }
1743
1744    fn execute(&mut self, c: Cmd<Q, R>) {
1745        match c {
1746            Cmd::Request { peer, addrs, wire, reply } => {
1747                for a in addrs {
1748                    self.swarm.add_peer_address(peer, a);
1749                }
1750                let id = self.swarm.behaviour_mut().rr.send_request(&peer, wire);
1751                self.pending.insert(id, reply);
1752            }
1753            Cmd::Names { peer, addrs, req, reply } => {
1754                for a in addrs {
1755                    self.swarm.add_peer_address(peer, a);
1756                }
1757                let id = self.swarm.behaviour_mut().names.send_request(&peer, req);
1758                self.names_pending.insert(id, reply);
1759            }
1760            Cmd::PutEntry { entry, reply } => {
1761                if let Err(e) = self.require_discovery() {
1762                    let _ = reply.send(Err(e));
1763                    return;
1764                }
1765                let key = kad::RecordKey::new(&self.profile.record_key(entry.user_id()));
1766                let existing = self.swarm.behaviour_mut().kad.store_mut().get(&key).and_then(|r| Entry::decode(&r.value).ok());
1767                if let Err(e) = self.profile.accept(existing.as_ref(), &entry, crate::now_ms()) {
1768                    let _ = reply.send(Err(e));
1769                    return;
1770                }
1771                let rec = record_of(key, &entry);
1772                match self.swarm.behaviour_mut().kad.put_record(rec, kad::Quorum::One) {
1773                    Ok(q) => {
1774                        self.puts.insert(q, reply);
1775                    }
1776                    Err(e) => {
1777                        let _ = reply.send(Err(net_err(e)));
1778                    }
1779                }
1780            }
1781            Cmd::PutLocator { rec, reply } => {
1782                if let Err(e) = self.require_discovery() {
1783                    let _ = reply.send(Err(e));
1784                    return;
1785                }
1786                let now = crate::now_ms();
1787                let key = match rec.key() {
1788                    Ok(k) => k,
1789                    Err(e) => {
1790                        let _ = reply.send(Err(e));
1791                        return;
1792                    }
1793                };
1794                let rkey = kad::RecordKey::new(&key);
1795                let existing =
1796                    self.swarm.behaviour_mut().kad.store_mut().get(&rkey).and_then(|r| crate::locator::LocatorRecord::decode(&r.value).ok());
1797                if let Err(e) = crate::locator::accept_locator(&key, existing.as_ref(), &rec, now) {
1798                    let _ = reply.send(Err(e));
1799                    return;
1800                }
1801                match self.swarm.behaviour_mut().kad.put_record(locator_record_of(rkey, &rec), kad::Quorum::One) {
1802                    Ok(q) => {
1803                        self.puts.insert(q, reply);
1804                    }
1805                    Err(e) => {
1806                        let _ = reply.send(Err(net_err(e)));
1807                    }
1808                }
1809            }
1810            Cmd::GetLocators { key, reply } => {
1811                if let Err(e) = self.require_discovery() {
1812                    let _ = reply.send(Err(e));
1813                    return;
1814                }
1815                let q = self.swarm.behaviour_mut().kad.get_record(kad::RecordKey::new(&key));
1816                self.lgets.insert(q, (vec![], reply));
1817            }
1818            Cmd::GetEntries { user, reply } => {
1819                if let Err(e) = self.require_discovery() {
1820                    let _ = reply.send(Err(e));
1821                    return;
1822                }
1823                let q = self.swarm.behaviour_mut().kad.get_record(kad::RecordKey::new(&self.profile.record_key(&user)));
1824                self.gets.insert(q, (vec![], reply));
1825            }
1826            Cmd::FindPeer { peer, reply } => {
1827                if let Err(e) = self.require_discovery() {
1828                    let _ = reply.send(Err(e));
1829                    return;
1830                }
1831                let q = self.swarm.behaviour_mut().kad.get_closest_peers(peer);
1832                self.finds.insert(q, (peer, reply));
1833            }
1834            Cmd::PeerApps { peer, reply } => {
1835                let _ = reply.send(Ok(self.peer_apps.get(&peer).cloned()));
1836            }
1837            Cmd::KnownAddrs { reply } => {
1838                let v = self.addr_book.iter().flat_map(|(p, a)| a.iter().map(|a| (*p, a.clone()))).collect();
1839                let _ = reply.send(Ok(v));
1840            }
1841            Cmd::Dial { addr, reply } => {
1842                let peer = addr_peer(&addr);
1843                match self.swarm.dial(addr.clone()) {
1844                    Ok(()) => self.dials.push((addr, peer, reply)),
1845                    Err(e) => {
1846                        let _ = reply.send(Err(net_err(e)));
1847                    }
1848                }
1849            }
1850            Cmd::Connect { peer, addrs, reply } => {
1851                use libp2p::swarm::dial_opts::{DialOpts, PeerCondition};
1852                if self.swarm.is_connected(&peer) {
1853                    let _ = reply.send(Ok(peer));
1854                    return;
1855                }
1856                for a in &addrs {
1857                    self.swarm.add_peer_address(peer, a.clone());
1858                }
1859                let first = addrs.first().cloned().unwrap_or_else(|| Multiaddr::empty().with(Protocol::P2p(peer)));
1860                match self.swarm.dial(DialOpts::peer_id(peer).addresses(addrs).condition(PeerCondition::DisconnectedAndNotDialing).build()) {
1861                    Ok(()) | Err(libp2p::swarm::DialError::DialPeerConditionFalse(_)) => self.dials.push((first, Some(peer), reply)),
1862                    Err(e) => {
1863                        let _ = reply.send(Err(net_err(e)));
1864                    }
1865                }
1866            }
1867            Cmd::DropPath { peer, path, reply } => {
1868                let ids: Vec<_> =
1869                    self.conns.iter().filter(|(_, (p, relayed))| *p == peer && (*relayed == (path == Path::Relayed))).map(|(c, _)| *c).collect();
1870                let n = ids.iter().filter(|c| self.swarm.close_connection(**c)).count();
1871                let _ = reply.send(Ok(n));
1872            }
1873            Cmd::Pause { reply } => {
1874                if !self.paused {
1875                    self.paused = true;
1876                    // relays to come back to
1877                    let keep = self.keeps_relays();
1878                    let mut back: Vec<Multiaddr> = self
1879                        .relay_listeners
1880                        .values()
1881                        .filter(|_| !keep)
1882                        .map(|(c, _, _)| {
1883                            let mut c = c.clone();
1884                            c.pop();
1885                            c
1886                        })
1887                        .collect();
1888                    back.extend(self.relay_retry.drain(..).map(|(a, _, _)| a));
1889                    self.go_quiet();
1890                    let now = std::time::Instant::now();
1891                    self.relay_retry = back.into_iter().map(|a| (a, now, Duration::from_secs(1))).collect();
1892                    self.update(|s| s.paused = true);
1893                    self.hub.send(Event::Paused);
1894                }
1895                let _ = reply.send(Ok(()));
1896            }
1897            Cmd::Resume { reply } => {
1898                if self.paused {
1899                    self.paused = false;
1900                    self.update(|s| s.paused = false);
1901                    self.wake(true);
1902                    self.hub.send(Event::Resumed);
1903                }
1904                let _ = reply.send(Ok(()));
1905            }
1906            Cmd::NetworkChanged { reply } => {
1907                if !self.paused {
1908                    let peers: Vec<PeerId> = self.swarm.connected_peers().copied().collect();
1909                    for p in peers {
1910                        let _ = self.swarm.disconnect_peer_id(p);
1911                    }
1912                    self.wake(false);
1913                }
1914                self.hub.send(Event::NetworkChanged);
1915                let _ = reply.send(Ok(()));
1916            }
1917            Cmd::Paths { peer, reply } => {
1918                let v = self.conns.values().filter(|(p, _)| *p == peer).map(|(_, r)| if *r { Path::Relayed } else { Path::Direct }).collect();
1919                let _ = reply.send(Ok(v));
1920            }
1921            Cmd::Listen { addr, reply } => match self.swarm.listen_on(addr) {
1922                Ok(id) => {
1923                    self.listens.insert(id, reply);
1924                }
1925                Err(e) => {
1926                    let _ = reply.send(Err(net_err(e)));
1927                }
1928            },
1929            Cmd::AddRelay { addr } => self.add_relay(addr),
1930            Cmd::AddPeer { hint, reply } => {
1931                let _ = reply.send(self.remember_peer(hint));
1932            }
1933            Cmd::RemovePeer { peer, reply } => {
1934                let id = peer.to_string();
1935                self.cfg.peers.retain(|p| p.peer_id != id);
1936                let _ = reply.send(Ok(()));
1937            }
1938            Cmd::ListPeers { reply } => {
1939                let _ = reply.send(Ok(self.cfg.peers.clone()));
1940            }
1941            Cmd::Provide { key, reply } => {
1942                if let Err(e) = self.require_discovery() {
1943                    let _ = reply.send(Err(e));
1944                    return;
1945                }
1946                let r = self.swarm.behaviour_mut().kad.start_providing(kad::RecordKey::new(&key)).map(|_| ()).map_err(net_err);
1947                let _ = reply.send(r);
1948            }
1949            Cmd::StopProviding { key } => {
1950                if self.cfg.discovery.is_enabled() {
1951                    self.swarm.behaviour_mut().kad.stop_providing(&kad::RecordKey::new(&key));
1952                }
1953            }
1954            Cmd::Providers { key, reply } => {
1955                if let Err(e) = self.require_discovery() {
1956                    let _ = reply.send(Err(e));
1957                    return;
1958                }
1959                let q = self.swarm.behaviour_mut().kad.get_providers(kad::RecordKey::new(&key));
1960                self.provs.insert(q, (vec![], reply));
1961            }
1962            Cmd::Stop => {}
1963        }
1964    }
1965
1966    fn event(&mut self, ev: SwarmEvent<BehaviourEvent<Q, R>>) {
1967        match ev {
1968            SwarmEvent::NewListenAddr { listener_id, address } => {
1969                tracing::info!("network: listening on {address}");
1970                self.listeners.insert(listener_id);
1971                self.hub.send(Event::Listening(address.clone()));
1972                // a relay announces where it listens: reservations carry those addresses
1973                if self.cfg.relay_server && self.cfg.external.is_empty() && routable(&address) && !address.iter().any(|p| p == Protocol::P2pCircuit) {
1974                    self.swarm.add_external_address(address.clone());
1975                }
1976                if let Some(tx) = self.listens.remove(&listener_id) {
1977                    let _ = tx.send(Ok(address));
1978                }
1979                self.refresh();
1980            }
1981            SwarmEvent::ListenerClosed { listener_id, addresses, .. } => {
1982                self.listeners.remove(&listener_id);
1983                for a in addresses {
1984                    self.hub.send(Event::ListenClosed(a));
1985                }
1986                if let Some(tx) = self.listens.remove(&listener_id) {
1987                    let _ = tx.send(Err(NetError::Network("listener closed".into())));
1988                }
1989                self.relay_listener_closed(listener_id);
1990                self.refresh();
1991            }
1992            SwarmEvent::ExternalAddrConfirmed { address } => {
1993                // a relay keeps to its configured addresses (or at least routable ones)
1994                if self.cfg.relay_server && (!routable(&address) || (!self.cfg.external.is_empty() && !self.cfg.external.contains(&address))) {
1995                    self.swarm.remove_external_address(&address);
1996                } else {
1997                    self.hub.send(Event::External { addr: address, confirmed: true });
1998                }
1999                self.refresh()
2000            }
2001            SwarmEvent::ExternalAddrExpired { address } => {
2002                self.hub.send(Event::External { addr: address, confirmed: false });
2003                self.refresh()
2004            }
2005            SwarmEvent::ExpiredListenAddr { address, .. } => {
2006                self.hub.send(Event::ListenClosed(address));
2007                self.refresh()
2008            }
2009            SwarmEvent::ConnectionEstablished { peer_id, endpoint, connection_id, .. } => {
2010                self.release_deferred(Some(peer_id));
2011                if self.relay_pending.remove(&peer_id) {
2012                    if !self.paused || self.keeps_relays() {
2013                        self.reserve_on(peer_id);
2014                    } else if let Some(a) = self.relay_addrs.get(&peer_id).and_then(|v| v.first().cloned()) {
2015                        // paused meanwhile: reserve when the app comes back
2016                        self.relay_listening.remove(&peer_id);
2017                        self.relay_retry.push((a, std::time::Instant::now(), Duration::from_secs(1)));
2018                    }
2019                }
2020                let relayed = endpoint_relayed(&endpoint);
2021                self.conns.insert(connection_id, (peer_id, relayed));
2022                self.hub.send(Event::Connected { peer: peer_id, path: path_of(relayed) });
2023                let addr = endpoint.get_remote_address().clone();
2024                if endpoint.is_dialer() {
2025                    let a = if addr_peer(&addr) == Some(peer_id) { addr.clone() } else { addr.clone().with(Protocol::P2p(peer_id)) };
2026                    let book = self.addr_book.entry(peer_id).or_default();
2027                    if !book.contains(&a) {
2028                        book.push(a);
2029                    }
2030                }
2031                let mut i = 0;
2032                while i < self.dials.len() {
2033                    let (a, p, _) = &self.dials[i];
2034                    if *a == addr || p.is_some_and(|p| p == peer_id) {
2035                        let (_, _, tx) = self.dials.remove(i);
2036                        let _ = tx.send(Ok(peer_id));
2037                    } else {
2038                        i += 1;
2039                    }
2040                }
2041                self.refresh();
2042            }
2043            SwarmEvent::ConnectionClosed { connection_id, peer_id, num_established, .. } => {
2044                if let Some((_, relayed)) = self.conns.remove(&connection_id) {
2045                    self.hub.send(Event::Disconnected { peer: peer_id, path: path_of(relayed), remaining: num_established });
2046                }
2047                if num_established == 0 {
2048                    self.heard.remove(&peer_id);
2049                    self.peer_apps.remove(&peer_id);
2050                }
2051                self.refresh()
2052            }
2053            SwarmEvent::OutgoingConnectionError { peer_id, error, .. } => {
2054                if let Some(p) = peer_id
2055                    && !self.swarm.is_connected(&p)
2056                {
2057                    self.release_deferred(Some(p));
2058                    if self.relay_pending.remove(&p) {
2059                        self.relay_listening.remove(&p);
2060                        if let Some(a) = self.relay_addrs.get(&p).and_then(|v| v.first().cloned()) {
2061                            self.retry_relay_later(p, a);
2062                        }
2063                    }
2064                }
2065                let msg = error.to_string();
2066                let mut i = 0;
2067                while i < self.dials.len() {
2068                    if peer_id.is_some() && self.dials[i].1 == peer_id {
2069                        let (_, _, tx) = self.dials.remove(i);
2070                        let _ = tx.send(Err(net_err(&msg)));
2071                    } else {
2072                        i += 1;
2073                    }
2074                }
2075                if peer_id.is_none() && !self.dials.is_empty() {
2076                    // an address without /p2p/: the oldest dial failed
2077                    let (_, _, tx) = self.dials.remove(0);
2078                    let _ = tx.send(Err(net_err(&msg)));
2079                }
2080            }
2081            SwarmEvent::Behaviour(b) => self.behaviour(b),
2082            _ => {}
2083        }
2084    }
2085
2086    fn behaviour(&mut self, ev: BehaviourEvent<Q, R>) {
2087        match ev {
2088            BehaviourEvent::Rr(request_response::Event::Message { peer, message, .. }) => match message {
2089                request_response::Message::Request { request, channel, .. } => {
2090                    let h = self.handler.clone();
2091                    let tx = self.resp_tx.clone();
2092                    tokio::task::spawn_blocking(move || {
2093                        let resp = h.request(&peer, request);
2094                        let _ = tx.send((channel, resp));
2095                    });
2096                }
2097                request_response::Message::Response { request_id, response } => {
2098                    if let Some(tx) = self.pending.remove(&request_id) {
2099                        let _ = tx.send(Ok(response));
2100                    }
2101                }
2102            },
2103            BehaviourEvent::Rr(request_response::Event::OutboundFailure { request_id, error, peer, .. }) => {
2104                if let Some(tx) = self.pending.remove(&request_id) {
2105                    let _ = tx.send(Err(NetError::Network(format!("{} could not be reached ({error})", crate::short_peer_id(&peer)))));
2106                }
2107            }
2108            BehaviourEvent::Rr(request_response::Event::InboundFailure { peer, error, .. }) => {
2109                tracing::debug!("network: inbound request from {peer} failed: {error}");
2110            }
2111            BehaviourEvent::Names(request_response::Event::Message { peer, message, .. }) => match message {
2112                request_response::Message::Request { request, channel, .. } => {
2113                    let Some(store) = self.cfg.names_server.clone() else { return };
2114                    let tx = self.names_tx.clone();
2115                    let profile = self.profile;
2116                    tokio::task::spawn_blocking(move || {
2117                        let resp = crate::names::serve(profile, &*store.0, &peer, request, crate::now_ms());
2118                        let _ = tx.send((channel, resp));
2119                    });
2120                }
2121                request_response::Message::Response { request_id, response } => {
2122                    if let Some(tx) = self.names_pending.remove(&request_id) {
2123                        let _ = tx.send(Ok(response));
2124                    }
2125                }
2126            },
2127            BehaviourEvent::Names(request_response::Event::OutboundFailure { request_id, error, peer, .. }) => {
2128                if let Some(tx) = self.names_pending.remove(&request_id) {
2129                    let _ = tx.send(Err(NetError::Network(format!("names server {} could not be reached ({error})", crate::short_peer_id(&peer)))));
2130                }
2131            }
2132            BehaviourEvent::Kad(kad::Event::InboundRequest { request }) => match request {
2133                kad::InboundRequest::PutRecord { record: Some(rec), source, .. } => self.inbound_put(rec, source),
2134                // nodes announce the relay key and content roots, nothing else
2135                kad::InboundRequest::AddProvider { record: Some(mut rec) }
2136                    if rec.key.as_ref() == self.profile.relay_key.as_bytes() || crate::content::is_provider_key(rec.key.as_ref()) =>
2137                {
2138                    // a provider that sent no addresses is answered with the ones we know,
2139                    // or others could not reach it
2140                    if rec.addresses.is_empty() {
2141                        rec.addresses = self.heard.get(&rec.provider).or_else(|| self.addr_book.get(&rec.provider)).cloned().unwrap_or_default();
2142                    }
2143                    let _ = self.swarm.behaviour_mut().kad.store_mut().add_provider(rec);
2144                }
2145                _ => {}
2146            },
2147            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::PutRecord(r), .. }) => {
2148                if let Some(tx) = self.puts.remove(&id) {
2149                    let _ = tx.send(r.map(|_| ()).map_err(net_err));
2150                }
2151            }
2152            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::GetRecord(r), step, .. }) => {
2153                let now = crate::now_ms();
2154                let done = match r {
2155                    Ok(kad::GetRecordOk::FoundRecord(pr)) => {
2156                        if let Some((v, _)) = self.lgets.get_mut(&id)
2157                            && let Ok(l) = crate::locator::LocatorRecord::decode(&pr.record.value)
2158                            && crate::locator::accept_locator(pr.record.key.as_ref(), None, &l, now).is_ok()
2159                        {
2160                            v.push(l);
2161                        }
2162                        if let Some((v, _)) = self.gets.get_mut(&id)
2163                            && let Ok(e) = Entry::decode(&pr.record.value)
2164                        {
2165                            v.push(e);
2166                        }
2167                        step.last
2168                    }
2169                    _ => true,
2170                };
2171                if done && let Some((v, tx)) = self.lgets.remove(&id) {
2172                    let _ = tx.send(Ok(v));
2173                    if let Some(mut q) = self.swarm.behaviour_mut().kad.query_mut(&id) {
2174                        q.finish();
2175                    }
2176                }
2177                if done && let Some((v, tx)) = self.gets.remove(&id) {
2178                    let _ = tx.send(Ok(v));
2179                    if let Some(mut q) = self.swarm.behaviour_mut().kad.query_mut(&id) {
2180                        q.finish();
2181                    }
2182                }
2183            }
2184            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::GetClosestPeers(r), .. }) => {
2185                if let Some((peer, tx)) = self.finds.remove(&id) {
2186                    let addrs = match r {
2187                        Ok(ok) => ok.peers,
2188                        Err(kad::GetClosestPeersError::Timeout { peers, .. }) => peers,
2189                    }
2190                    .into_iter()
2191                    .filter(|i| i.peer_id == peer)
2192                    .flat_map(|i| i.addrs)
2193                    .map(|a| if addr_peer(&a) == Some(peer) { a } else { a.with(Protocol::P2p(peer)) })
2194                    .collect();
2195                    let _ = tx.send(Ok(addrs));
2196                }
2197            }
2198            BehaviourEvent::Mdns(mdns::Event::Discovered(list)) => {
2199                let mut by_peer: HashMap<PeerId, Vec<Multiaddr>> = HashMap::new();
2200                for (p, a) in list {
2201                    by_peer.entry(p).or_default().push(a);
2202                }
2203                for (p, addrs) in by_peer {
2204                    for a in &addrs {
2205                        self.swarm.add_peer_address(p, a.clone());
2206                        if self.cfg.discovery.is_enabled() {
2207                            self.swarm.behaviour_mut().kad.add_address(&p, a.clone());
2208                        }
2209                    }
2210                    if self.cfg.discovery.is_enabled() && !self.paused && !self.swarm.is_connected(&p) {
2211                        let _ = self.swarm.dial(p);
2212                    }
2213                    self.seen(Sighting { peer: p, addrs: addrs.iter().map(|a| a.to_string()).collect(), caps: None, agent: None, source: "mdns" });
2214                }
2215            }
2216            BehaviourEvent::Identify(identify::Event::Received { peer_id, info, .. }) => {
2217                let protos: Vec<String> = info.protocols.iter().map(|p| p.to_string()).collect();
2218                let mut caps = vec![];
2219                if protos.iter().any(|p| p == self.profile.protocol) {
2220                    caps.push(self.profile.name.to_string());
2221                }
2222                if protos.iter().any(|p| *p == relay::HOP_PROTOCOL_NAME.to_string()) {
2223                    caps.push("relay".to_string());
2224                }
2225                if protos.iter().any(|p| p == self.profile.kad) {
2226                    caps.push("kad".to_string());
2227                    if self.cfg.discovery.is_enabled() {
2228                        for a in &info.listen_addrs {
2229                            self.swarm.behaviour_mut().kad.add_address(&peer_id, a.clone());
2230                        }
2231                    }
2232                }
2233                let apps: Vec<String> = protos.iter().filter_map(|p| crate::app::announced(p)).map(str::to_string).collect();
2234                caps.extend(apps.iter().map(|a| format!("app:{a}")));
2235                self.peer_apps.insert(peer_id, apps);
2236                let is_relay = caps.iter().any(|c| c == "relay");
2237                let addrs: Vec<String> = info.listen_addrs.iter().filter(|a| shareable(a)).map(|a| a.to_string()).collect();
2238                self.heard.insert(peer_id, info.listen_addrs.iter().filter(|a| shareable(a)).take(8).cloned().collect());
2239                self.seen(Sighting { peer: peer_id, addrs, caps: Some(caps), agent: Some(info.agent_version), source: "identify" });
2240                // behind NAT: use relays we meet
2241                let private = self.status.lock().map(|s| s.nat == "private").unwrap_or(false);
2242                if self.cfg.discovery.is_enabled()
2243                    && is_relay
2244                    && private
2245                    && !self.paused
2246                    && self.relay_listening.is_empty()
2247                    && let Some(a) = info.listen_addrs.iter().filter(|a| shareable(a)).min_by_key(|a| reach_rank(a))
2248                {
2249                    self.add_relay(a.clone().with(Protocol::P2p(peer_id)));
2250                }
2251            }
2252            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed { id, result: kad::QueryResult::GetProviders(r), step, .. })
2253                if self.provs.contains_key(&id) =>
2254            {
2255                let me = *self.swarm.local_peer_id();
2256                let done = step.last || !matches!(r, Ok(kad::GetProvidersOk::FoundProviders { .. }));
2257                if let Some((found, _)) = self.provs.get_mut(&id)
2258                    && let Ok(kad::GetProvidersOk::FoundProviders { providers, .. }) = r
2259                {
2260                    for p in providers {
2261                        if p != me && !found.contains(&p) {
2262                            found.push(p);
2263                        }
2264                    }
2265                }
2266                if done && let Some((found, reply)) = self.provs.remove(&id) {
2267                    let _ = reply.send(Ok(found));
2268                }
2269            }
2270            BehaviourEvent::Kad(kad::Event::OutboundQueryProgressed {
2271                result: kad::QueryResult::GetProviders(Ok(kad::GetProvidersOk::FoundProviders { providers, .. })),
2272                ..
2273            }) => {
2274                for p in providers {
2275                    if p != *self.swarm.local_peer_id() {
2276                        self.seen(Sighting { peer: p, addrs: vec![], caps: Some(vec!["relay".into(), "kad".into()]), agent: None, source: "kad" });
2277                    }
2278                }
2279            }
2280            BehaviourEvent::Autonat(autonat::Event::StatusChanged { new, .. }) => {
2281                let nat = match new {
2282                    autonat::NatStatus::Public(_) => "public",
2283                    autonat::NatStatus::Private => "private",
2284                    autonat::NatStatus::Unknown => "unknown",
2285                };
2286                self.update(|s| s.nat = nat.into());
2287                self.hub.send(Event::Nat(nat.into()));
2288                if nat == "private" {
2289                    let relays: Vec<PeerId> = self.relays.iter().copied().collect();
2290                    tracing::info!("network: behind NAT; {} relay(s) known", relays.len());
2291                }
2292            }
2293            BehaviourEvent::RelayClient(relay::client::Event::ReservationReqAccepted { relay_peer_id, .. }) => {
2294                tracing::info!("network: reservation on relay {relay_peer_id}");
2295                self.hub.send(Event::Reserved { relay: relay_peer_id });
2296                self.relay_backoff.remove(&relay_peer_id);
2297                self.update(|s| {
2298                    let r = relay_peer_id.to_string();
2299                    if !s.reservations.contains(&r) {
2300                        s.reservations.push(r);
2301                    }
2302                });
2303            }
2304            BehaviourEvent::Streams(e) => match e {},
2305            BehaviourEvent::Dcutr(e) => {
2306                tracing::debug!("network: hole punch with {}: {}", e.remote_peer_id, if e.result.is_ok() { "direct" } else { "failed" });
2307            }
2308            _ => {}
2309        }
2310    }
2311}
2312
2313/// A Kademlia record holding a names entry, expiring with it.
2314fn record_of(key: kad::RecordKey, entry: &Entry) -> kad::Record {
2315    let mut rec = kad::Record::new(key, entry.encode());
2316    let left = (entry.expires() - crate::now_ms()).max(0) as u64;
2317    rec.expires = Some(std::time::Instant::now() + Duration::from_millis(left));
2318    rec
2319}
2320
2321/// A Kademlia record holding a locator record, expiring with it.
2322fn locator_record_of(key: kad::RecordKey, l: &crate::locator::LocatorRecord) -> kad::Record {
2323    let mut rec = kad::Record::new(key, l.encode());
2324    let left = (l.expires - crate::now_ms()).max(0) as u64;
2325    rec.expires = Some(std::time::Instant::now() + Duration::from_millis(left));
2326    rec
2327}
2328
2329impl<Q: Message, R: Message> Loop<Q, R> {
2330    /// A peer put a locator record: keep it only if it checks out under its key.
2331    fn inbound_locator(&mut self, rec: kad::Record, l: crate::locator::LocatorRecord, source: PeerId) {
2332        let store = self.swarm.behaviour_mut().kad.store_mut();
2333        let existing = store.get(&rec.key).and_then(|r| crate::locator::LocatorRecord::decode(&r.value).ok());
2334        match crate::locator::accept_locator(rec.key.as_ref(), existing.as_ref(), &l, crate::now_ms()) {
2335            Ok(()) => {
2336                let mut r = locator_record_of(rec.key.clone(), &l);
2337                r.publisher = rec.publisher;
2338                let _ = store.put(r);
2339            }
2340            Err(e) => tracing::debug!("network: refused a locator record from {source}: {e}"),
2341        }
2342    }
2343
2344    /// A peer put a record: keep it only if it is a valid names entry under its own key
2345    /// that supersedes what we hold (see [`Profile::accept`]).
2346    fn inbound_put(&mut self, rec: kad::Record, source: PeerId) {
2347        let Ok(entry) = Entry::decode(&rec.value) else {
2348            if let Ok(l) = crate::locator::LocatorRecord::decode(&rec.value) {
2349                return self.inbound_locator(rec, l, source);
2350            }
2351            tracing::debug!("network: refused a DHT record from {source}: not a names entry");
2352            return;
2353        };
2354        let key = kad::RecordKey::new(&self.profile.record_key(entry.user_id()));
2355        if rec.key != key {
2356            tracing::debug!("network: refused a DHT record from {source}: wrong key");
2357            return;
2358        }
2359        let store = self.swarm.behaviour_mut().kad.store_mut();
2360        let existing = store.get(&key).and_then(|r| Entry::decode(&r.value).ok());
2361        match self.profile.accept(existing.as_ref(), &entry, crate::now_ms()) {
2362            Ok(()) => {
2363                let mut r = record_of(key, &entry);
2364                r.publisher = rec.publisher;
2365                let _ = store.put(r);
2366            }
2367            Err(e) => tracing::debug!("network: refused a DHT record from {source}: {e}"),
2368        }
2369    }
2370}
2371
2372/// True when the Kademlia routing table holds no peers yet.
2373fn routing_empty<S: kad::store::RecordStore + Send + 'static>(k: &mut kad::Behaviour<S>) -> bool {
2374    k.kbuckets().all(|b| b.num_entries() == 0)
2375}