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