Skip to main content

fedimint_connectors/
iroh.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt;
3use std::net::SocketAddr;
4use std::pin::Pin;
5use std::str::FromStr;
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8
9use async_trait::async_trait;
10use fedimint_core::config::ALEPH_BFT_UNIT_BYTE_LIMIT;
11use fedimint_core::envs::{
12    FM_GW_IROH_CONNECT_OVERRIDES_PLAIN_ENV, FM_IROH_CONNECT_OVERRIDES_PLAIN_ENV,
13    FM_IROH_N0_DISCOVERY_ENABLE_ENV, FM_IROH_PKARR_RESOLVER_ENABLE_ENV, is_env_var_set_opt,
14    parse_kv_list_from_env,
15};
16use fedimint_core::module::{
17    ApiError, ApiMethod, ApiRequestErased, FEDIMINT_API_ALPN, FEDIMINT_GATEWAY_ALPN,
18    IrohApiRequest, IrohGatewayRequest, IrohGatewayResponse,
19};
20use fedimint_core::net::iroh::{IROH_IDLE_TIMEOUT, IROH_KEEP_ALIVE_INTERVAL};
21
22/// The maximum number of bytes we are willing to buffer when reading an API
23/// response from an iroh QUIC stream. This must be large enough to accommodate
24/// the largest possible signed session outcome. A session can contain up to
25/// `broadcast_rounds_per_session` (default 3600) rounds, each peer produces one
26/// unit per round, and each unit can be up to `ALEPH_BFT_UNIT_BYTE_LIMIT`
27/// bytes. The response is JSON-serialized which hex-encodes the consensus
28/// bytes, roughly doubling the size. We use 2x the raw max as a conservative
29/// upper bound. For a 4-peer federation this is ~1.44 GB.
30const IROH_MAX_RESPONSE_BYTES: usize = ALEPH_BFT_UNIT_BYTE_LIMIT * 3600 * 4 * 2;
31
32/// Wall-clock budget for a single iroh API request to make it through the QUIC
33/// bi-stream (open + write + finish + read response). If exceeded we close the
34/// underlying [`Connection`], which causes [`IConnection::is_connected`] to
35/// return false on the next pool lookup so a fresh connection is established
36/// for the retry. Used for endpoints that respond promptly (`block_count`,
37/// `status`, etc).
38const IROH_REQUEST_TIMEOUT_DEFAULT: Duration = Duration::from_secs(60);
39
40/// Wall-clock budget for an iroh API request to a server-side long-poll
41/// endpoint (`await_*` / `wait_*`). These wait on the server until an event
42/// fires (block height reached, contract cancelled, etc.) before responding,
43/// so they need a generous bound. Set well above realistic mainnet block
44/// intervals; if a long-poll legitimately needs longer than this the upstream
45/// `request_current_consensus_retry` loop will reconnect and retry.
46const IROH_REQUEST_TIMEOUT_LONG_POLL: Duration = Duration::from_secs(60 * 60);
47
48/// Application-level QUIC error code we use when closing a [`Connection`]
49/// after a request timeout. Recorded by the peer as the close reason; chosen
50/// arbitrarily but stable across stable and `iroh_next` impls so the two
51/// emit identical telemetry. The value 1 distinguishes us from a graceful
52/// close (0).
53const IROH_REQUEST_TIMEOUT_ERROR_CODE: u32 = 1;
54const IROH_REQUEST_TIMEOUT_ERROR_REASON: &[u8] = b"request timeout";
55
56/// Request timeout strategy: long-poll endpoints (`await_*` / `wait_*`)
57/// get the long bound, everything else gets the default. The string match
58/// is a heuristic; it covers all currently-defined fedimint long-poll
59/// endpoints and stays correct if new ones follow the existing naming
60/// convention. False positives (a non-long-poll endpoint that happens to
61/// match the prefix) just give that one method a longer leash; the worse
62/// case is a false negative — a long-poll method that doesn't match
63/// either prefix would get the 60s default and fail fast on legitimate
64/// waits, but the upstream retry loop would reconnect and try again.
65fn request_timeout_for_method(method: &ApiMethod) -> Duration {
66    let name = match method {
67        ApiMethod::Core(name) => name.as_str(),
68        ApiMethod::Module(_, name) => name.as_str(),
69    };
70    if name.starts_with("await_") || name.starts_with("wait_") {
71        IROH_REQUEST_TIMEOUT_LONG_POLL
72    } else {
73        IROH_REQUEST_TIMEOUT_DEFAULT
74    }
75}
76use fedimint_core::task::spawn;
77use fedimint_core::util::{FmtCompact as _, SafeUrl};
78use fedimint_core::{apply, async_trait_maybe_send};
79use fedimint_logging::LOG_NET_IROH;
80use futures::Future;
81use futures::stream::{FuturesUnordered, StreamExt};
82use iroh::discovery::pkarr::PkarrResolver;
83use iroh::endpoint::Connection;
84use iroh::{Endpoint, NodeAddr, NodeId, PublicKey};
85use reqwest::{Method, StatusCode};
86use serde_json::Value;
87use tokio::sync::watch;
88use tracing::{debug, trace, warn};
89
90use super::{DynGuaridianConnection, IGuardianConnection, ServerError, ServerResult};
91use crate::error::ConnectorError;
92use crate::{Connectivity, DynGatewayConnection, IConnection, IGatewayConnection, IrohPeerInfo};
93
94#[derive(Clone)]
95pub(crate) struct IrohConnector {
96    stable: iroh::endpoint::Endpoint,
97    next: iroh_next::endpoint::Endpoint,
98
99    /// List of overrides to use when attempting to connect to given
100    /// `NodeId`
101    ///
102    /// This is useful for testing, or forcing non-default network
103    /// connectivity.
104    connection_overrides: BTreeMap<NodeId, NodeAddr>,
105
106    /// Registry-owned signal bumped whenever any per-connection monitoring
107    /// task observes a transport-level path change (e.g. iroh relay →
108    /// direct). Consumers of [`crate::ConnectorRegistry`] subscribe via
109    /// [`crate::ConnectorRegistry::connectivity_change_notifier`].
110    path_change: Arc<watch::Sender<u64>>,
111
112    /// Live connections dialed over the next stack, kept so
113    /// [`crate::Connector::connectivity`] can read their paths back.
114    ///
115    /// Iroh 1.0 exposes path state per connection rather than per endpoint,
116    /// so unlike the stable stack there is no `endpoint.conn_type(node_id)`
117    /// to consult after the fact. Entries are keyed by the stable [`NodeId`]
118    /// because that is what callers derive from a peer url, and are replaced
119    /// on redial, so the map stays bounded by the number of distinct peers.
120    next_connections: Arc<Mutex<BTreeMap<NodeId, iroh_next::endpoint::Connection>>>,
121}
122
123impl fmt::Debug for IrohConnector {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.debug_struct("IrohEndpoint")
126            .field("stable-id", &self.stable.node_id())
127            .field("next-id", &self.next.id())
128            .finish_non_exhaustive()
129    }
130}
131
132impl IrohConnector {
133    pub(crate) async fn new(
134        iroh_dns: Option<SafeUrl>,
135        iroh_enable_dht: bool,
136        iroh_p2p: bool,
137        path_change: Arc<watch::Sender<u64>>,
138    ) -> Result<Self, ConnectorError> {
139        let mut s =
140            Self::new_no_overrides(iroh_dns, iroh_enable_dht, iroh_p2p, path_change).await?;
141
142        // Overrides are `<node-id>=<socket-addr>` pairs: the node id is the key
143        // and the value is a single direct address. iroh 1.0 no longer ships
144        // the `NodeTicket` format, so we keep the override wire format version
145        // agnostic and build the (legacy) `NodeAddr` from its parts. Pre-0.12
146        // binaries read the `NodeTicket`-format `FM_IROH_CONNECT_OVERRIDES`
147        // instead; devimint emits both side by side.
148        for env_var in [
149            FM_IROH_CONNECT_OVERRIDES_PLAIN_ENV,
150            FM_GW_IROH_CONNECT_OVERRIDES_PLAIN_ENV,
151        ] {
152            for (k, v) in parse_kv_list_from_env::<NodeId, SocketAddr>(env_var) {
153                s = s.with_connection_override(k, NodeAddr::new(k).with_direct_addresses([v]));
154            }
155        }
156
157        Ok(s)
158    }
159
160    #[allow(clippy::too_many_lines)]
161    pub(crate) async fn new_no_overrides(
162        iroh_dns: Option<SafeUrl>,
163        iroh_enable_dht: bool,
164        iroh_p2p: bool,
165        path_change: Arc<watch::Sender<u64>>,
166    ) -> Result<Self, ConnectorError> {
167        let endpoint_stable = Box::pin({
168            let iroh_dns = iroh_dns.clone();
169            async {
170                let mut builder = Endpoint::builder();
171
172                if let Some(iroh_dns) = iroh_dns.map(SafeUrl::to_unsafe) {
173                    builder = builder.add_discovery(|_| Some(PkarrResolver::new(iroh_dns)));
174                }
175
176                // As a client, we don't need to register on any relays
177                let mut builder = builder.relay_mode(iroh::RelayMode::Disabled);
178
179                #[cfg(not(target_family = "wasm"))]
180                if iroh_enable_dht {
181                    builder = builder.discovery_dht();
182                }
183
184                // Add only resolver services here; the stable n0 convenience also
185                // installs a publisher.
186                {
187                    if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
188                        builder = builder.add_discovery(move |_| Some(PkarrResolver::n0_dns()));
189                    } else {
190                        warn!(
191                            target: LOG_NET_IROH,
192                            "Iroh pkarr resolver is disabled"
193                        );
194                    }
195
196                    if is_env_var_set_opt(FM_IROH_N0_DISCOVERY_ENABLE_ENV).unwrap_or(true) {
197                        #[cfg(not(target_family = "wasm"))]
198                        {
199                            builder = builder.add_discovery(move |_| {
200                                Some(iroh::discovery::dns::DnsDiscovery::n0_dns())
201                            });
202                        }
203                    } else {
204                        warn!(
205                            target: LOG_NET_IROH,
206                            "Iroh n0 discovery is disabled"
207                        );
208                    }
209                }
210
211                let endpoint = builder
212                    .transport_config(quic_transport_config())
213                    .bind()
214                    .await
215                    .map_err(|err| ConnectorError::Transport(err.into()))?;
216                debug!(
217                    target: LOG_NET_IROH,
218                    node_id = %endpoint.node_id(),
219                    node_id_pkarr = %z32::encode(endpoint.node_id().as_bytes()),
220                    "Iroh api client endpoint (stable)"
221                );
222                Ok::<_, ConnectorError>(endpoint)
223            }
224        });
225        let endpoint_next = Box::pin(async {
226            let mut builder = iroh_next::Endpoint::builder(iroh_next::endpoint::presets::Minimal);
227
228            if let Some(iroh_dns) = iroh_dns.map(SafeUrl::to_unsafe) {
229                builder = builder
230                    .address_lookup(iroh_next::address_lookup::PkarrResolver::builder(iroh_dns));
231            }
232
233            // Server iroh-next endpoints publish relay-only address records by
234            // default (the iroh 1.0 publishers filter out direct addresses), so
235            // the client must be able to dial via relays; `RelayMode::Disabled`
236            // would disable dialing them, not just registration.
237            let mut builder = builder.relay_mode(iroh_next::RelayMode::Default);
238
239            // Browsers have no IP transports to clear: wasm is always relay-only.
240            #[cfg(not(target_family = "wasm"))]
241            if !iroh_p2p {
242                builder = builder.clear_ip_transports();
243            }
244            #[cfg(target_family = "wasm")]
245            let _ = iroh_p2p;
246
247            // iOS prompts for Local Network access when the port mapper probes
248            // the router, and another crate can turn iroh's `portmapper` on.
249            #[cfg(target_os = "ios")]
250            {
251                builder =
252                    builder.portmapper_config(iroh_next::endpoint::PortmapperConfig::Disabled);
253            }
254
255            #[cfg(not(target_family = "wasm"))]
256            if iroh_enable_dht {
257                builder = builder
258                    .address_lookup(iroh_mainline_address_lookup::DhtAddressLookup::builder());
259            }
260
261            // Add only resolver services here; the iroh preset convenience also
262            // installs a publisher.
263            {
264                // Resolve using HTTPS requests to our DNS server's /pkarr path.
265                builder =
266                    builder.address_lookup(iroh_next::address_lookup::PkarrResolver::n0_dns());
267                // Resolve using DNS queries outside browsers.
268                #[cfg(not(target_family = "wasm"))]
269                {
270                    builder = builder
271                        .address_lookup(iroh_next::address_lookup::DnsAddressLookup::n0_dns());
272                }
273            }
274
275            let endpoint = builder
276                .transport_config(quic_transport_config_next())
277                .bind()
278                .await
279                .map_err(|err| ConnectorError::Transport(err.into()))?;
280            debug!(
281                target: LOG_NET_IROH,
282                node_id = %endpoint.id(),
283                node_id_pkarr = %z32::encode(endpoint.id().as_bytes()),
284                "Iroh api client endpoint (next)"
285            );
286            Ok(endpoint)
287        });
288
289        let (endpoint_stable, endpoint_next) = tokio::try_join!(endpoint_stable, endpoint_next)?;
290
291        Ok(Self {
292            stable: endpoint_stable,
293            next: endpoint_next,
294            connection_overrides: BTreeMap::new(),
295            path_change,
296            next_connections: Arc::new(Mutex::new(BTreeMap::new())),
297        })
298    }
299
300    pub(crate) fn with_connection_override(mut self, node: NodeId, addr: NodeAddr) -> Self {
301        self.connection_overrides.insert(node, addr);
302        self
303    }
304
305    pub(crate) fn node_id_from_url(url: &SafeUrl) -> Result<NodeId, ConnectorError> {
306        if url.scheme() != "iroh" {
307            return Err(ConnectorError::UnsupportedScheme {
308                scheme: url.scheme().to_owned(),
309            });
310        }
311        let host = url.host_str().ok_or_else(|| ConnectorError::MissingHost {
312            url: url.to_owned(),
313        })?;
314
315        PublicKey::from_str(host).map_err(|source| ConnectorError::InvalidNodeId {
316            host: host.to_owned(),
317            source: Box::new(source),
318        })
319    }
320}
321
322#[async_trait::async_trait]
323impl crate::Connector for IrohConnector {
324    async fn connect_guardian(
325        &self,
326        url: &SafeUrl,
327        api_secret: Option<&str>,
328    ) -> ServerResult<DynGuaridianConnection> {
329        if api_secret.is_some() {
330            // There seem to be no way to pass secret over current Iroh calling
331            // convention. Connecting anyway would silently drop the credential and
332            // talk to an API that never authenticates us, so refuse instead.
333            return Err(ServerError::Connection(
334                "Iroh api secrets currently not supported".into(),
335            ));
336        }
337        let node_id =
338            Self::node_id_from_url(url).map_err(|source| ServerError::InvalidPeerUrl {
339                source: Box::new(source),
340                url: url.to_owned(),
341            })?;
342        let next_only = crate::is_iroh_next_endpoint_url(url).map_err(|source| {
343            ServerError::InvalidPeerUrl {
344                source: Box::new(source),
345                url: url.to_owned(),
346            }
347        })?;
348        let mut futures = FuturesUnordered::<
349            Pin<
350                Box<
351                    dyn Future<Output = (ServerResult<DynGuaridianConnection>, &'static str)>
352                        + Send,
353                >,
354            >,
355        >::new();
356        let connection_override = self.connection_overrides.get(&node_id).cloned();
357
358        // Advertised Iroh 1.0 identities carry an internal `/v1` marker so we
359        // avoid attempting the incompatible 0.35 stack for safety and efficiency.
360        if next_only {
361            return self
362                .make_new_connection_next(&self.next, node_id, connection_override)
363                .await
364                .map(super::IGuardianConnection::into_dyn);
365        }
366
367        let self_clone = self.clone();
368        futures.push(Box::pin({
369            let connection_override = connection_override.clone();
370            async move {
371                (
372                    self_clone
373                        .make_new_connection_stable(node_id, connection_override)
374                        .await
375                        .map(super::IGuardianConnection::into_dyn),
376                    "stable",
377                )
378            }
379        }));
380
381        let self_clone = self.clone();
382        let endpoint_next = self.next.clone();
383        futures.push(Box::pin(async move {
384            (
385                self_clone
386                    .make_new_connection_next(&endpoint_next, node_id, connection_override)
387                    .await
388                    .map(super::IGuardianConnection::into_dyn),
389                "next",
390            )
391        }));
392
393        // Remember last error, so we have something to return if
394        // neither connection works.
395        let mut prev_err = None;
396
397        // Loop until first success, or running out of connections.
398        while let Some((result, iroh_stack)) = futures.next().await {
399            match result {
400                Ok(connection) => return Ok(connection),
401                Err(err) => {
402                    warn!(
403                        target: LOG_NET_IROH,
404                        err = %err.fmt_compact(),
405                        %iroh_stack,
406                        "Join error in iroh connection task"
407                    );
408                    prev_err = Some(err);
409                }
410            }
411        }
412
413        Err(prev_err.unwrap_or_else(|| {
414            ServerError::ServerError("Both iroh connection attempts failed".to_string())
415        }))
416    }
417
418    async fn connect_gateway(&self, url: &SafeUrl) -> Result<DynGatewayConnection, ConnectorError> {
419        let node_id = Self::node_id_from_url(url)?;
420        if let Some(node_addr) = self.connection_overrides.get(&node_id).cloned() {
421            let conn = self
422                .stable
423                .connect(node_addr.clone(), FEDIMINT_GATEWAY_ALPN)
424                .await
425                .map_err(|err| ConnectorError::Transport(err.into()))?;
426
427            #[cfg(not(target_family = "wasm"))]
428            Self::spawn_connection_monitoring_stable(
429                &self.stable,
430                node_id,
431                self.path_change.clone(),
432            );
433
434            Ok(IGatewayConnection::into_dyn(conn))
435        } else {
436            let conn = self
437                .stable
438                .connect(node_id, FEDIMINT_GATEWAY_ALPN)
439                .await
440                .map_err(|err| ConnectorError::Transport(err.into()))?;
441            Ok(IGatewayConnection::into_dyn(conn))
442        }
443    }
444
445    fn connectivity(&self, url: &SafeUrl) -> Connectivity {
446        let Ok(node_id) = Self::node_id_from_url(url) else {
447            return Connectivity::Unknown;
448        };
449
450        // The next stack is consulted first: a peer reached over an advertised
451        // Iroh 1.0 endpoint never has a stable connection to report, and when
452        // both stacks were raced the next connection is the live one. Falling
453        // through to the stable endpoint in that case would report
454        // `Unknown`, which callers render as a disconnected peer.
455        if let Some(connectivity) = self.connectivity_next(node_id) {
456            return connectivity;
457        }
458
459        let Ok(watcher) = self.stable.conn_type(node_id) else {
460            return Connectivity::Unknown;
461        };
462        match watcher.get() {
463            Ok(iroh::endpoint::ConnectionType::Direct(_)) => Connectivity::Direct,
464            Ok(iroh::endpoint::ConnectionType::Relay(_)) => Connectivity::Relay,
465            Ok(iroh::endpoint::ConnectionType::Mixed(..)) => Connectivity::Mixed,
466            Ok(iroh::endpoint::ConnectionType::None) | Err(_) => Connectivity::Unknown,
467        }
468    }
469
470    async fn iroh_peer_info(
471        &self,
472        url: &SafeUrl,
473        path_timeout: Duration,
474    ) -> ServerResult<Option<IrohPeerInfo>> {
475        let node_id =
476            Self::node_id_from_url(url).map_err(|source| ServerError::InvalidPeerUrl {
477                source: Box::new(source),
478                url: url.to_owned(),
479            })?;
480        let connection_override = self.connection_overrides.get(&node_id).cloned();
481        let _connection = self
482            .make_new_connection_stable(node_id, connection_override)
483            .await?;
484
485        let mut conn_type_watcher = self
486            .stable
487            .conn_type(node_id)
488            .map_err(|err| ServerError::Connection(err.into()))?;
489        let mut conn_type = conn_type_watcher
490            .get()
491            .unwrap_or(iroh::endpoint::ConnectionType::None);
492
493        if path_timeout > Duration::ZERO {
494            let timeout = fedimint_core::runtime::sleep(path_timeout);
495            tokio::pin!(timeout);
496
497            while !matches!(
498                conn_type,
499                iroh::endpoint::ConnectionType::Direct(_)
500                    | iroh::endpoint::ConnectionType::Mixed(..)
501            ) {
502                tokio::select! {
503                    () = &mut timeout => break,
504                    updated = conn_type_watcher.updated() => {
505                        match updated {
506                            Ok(updated) => conn_type = updated,
507                            Err(_) => break,
508                        }
509                    }
510                }
511            }
512        }
513
514        Ok(Some(self.iroh_peer_info_from_conn_type(node_id, conn_type)))
515    }
516}
517
518impl IrohConnector {
519    /// Report how a retained next-stack connection is reaching `node_id`.
520    ///
521    /// Returns `None` when the next stack has nothing to say about the peer,
522    /// so the caller can fall back to the stable stack: no connection held,
523    /// one that has since closed, or one whose paths cannot be classified.
524    /// None of those mean "disconnected", which is what answering
525    /// [`Connectivity::Unknown`] would tell callers.
526    fn connectivity_next(&self, node_id: NodeId) -> Option<Connectivity> {
527        let connections = self
528            .next_connections
529            .lock()
530            .expect("Next connection mutex is never held across a panic");
531
532        let connection = connections.get(&node_id)?;
533
534        if connection.close_reason().is_some() {
535            return None;
536        }
537
538        // A path carries application data over either an IP or a relay
539        // address, so holding one of each is the next-stack spelling of the
540        // stable stack's `Mixed`.
541        let paths = connection.paths();
542        let direct = paths.iter().any(|path| path.is_ip());
543        let relay = paths.iter().any(|path| path.is_relay());
544
545        Some(match (direct, relay) {
546            (true, true) => Connectivity::Mixed,
547            (true, false) => Connectivity::Direct,
548            (false, true) => Connectivity::Relay,
549            // Nothing to classify. Fall back to the stable stack rather than
550            // answering `Unknown`, which callers render as a disconnected
551            // peer — the very thing this lookup exists to avoid.
552            (false, false) => return None,
553        })
554    }
555
556    fn iroh_peer_info_from_conn_type(
557        &self,
558        node_id: NodeId,
559        conn_type: iroh::endpoint::ConnectionType,
560    ) -> IrohPeerInfo {
561        let remote_info = self.stable.remote_info(node_id);
562
563        let direct_addr = match &conn_type {
564            iroh::endpoint::ConnectionType::Direct(addr)
565            | iroh::endpoint::ConnectionType::Mixed(addr, _) => Some(*addr),
566            iroh::endpoint::ConnectionType::Relay(_) | iroh::endpoint::ConnectionType::None => None,
567        };
568
569        let mut known_direct_addrs = remote_info
570            .as_ref()
571            .map(|info| {
572                info.addrs
573                    .iter()
574                    .map(|addr_info| addr_info.addr)
575                    .collect::<BTreeSet<_>>()
576            })
577            .unwrap_or_default();
578        if let Some(direct_addr) = direct_addr {
579            known_direct_addrs.insert(direct_addr);
580        }
581
582        let relay_url = match &conn_type {
583            iroh::endpoint::ConnectionType::Relay(relay_url)
584            | iroh::endpoint::ConnectionType::Mixed(_, relay_url) => Some(relay_url.to_string()),
585            iroh::endpoint::ConnectionType::Direct(_) | iroh::endpoint::ConnectionType::None => {
586                remote_info.and_then(|info| info.relay_url.map(|relay| relay.relay_url.to_string()))
587            }
588        };
589
590        IrohPeerInfo {
591            node_id: node_id.to_string(),
592            connectivity: connectivity_from_iroh_conn_type(&conn_type),
593            direct_addr,
594            known_direct_addrs: known_direct_addrs.into_iter().collect(),
595            relay_url,
596        }
597    }
598
599    #[cfg(not(target_family = "wasm"))]
600    fn spawn_connection_monitoring_stable(
601        endpoint: &Endpoint,
602        node_id: NodeId,
603        path_change: Arc<watch::Sender<u64>>,
604    ) {
605        if let Ok(mut conn_type_watcher) = endpoint.conn_type(node_id) {
606            #[allow(clippy::let_underscore_future)]
607            let _ = spawn("iroh connection (stable)", async move {
608                if let Ok(conn_type) = conn_type_watcher.get() {
609                    debug!(target: LOG_NET_IROH, %node_id, type = %conn_type, "Connection type (initial)");
610                }
611                while let Ok(event) = conn_type_watcher.updated().await {
612                    debug!(target: LOG_NET_IROH, %node_id, type = %event, "Connection type (changed)");
613                    path_change.send_modify(|c| *c = c.wrapping_add(1));
614                }
615            });
616        }
617    }
618
619    #[cfg(not(target_family = "wasm"))]
620    fn spawn_connection_monitoring_next(
621        conn: &iroh_next::endpoint::Connection,
622        node_id: iroh_next::EndpointId,
623        path_change: Arc<watch::Sender<u64>>,
624    ) {
625        let conn = conn.clone();
626        #[allow(clippy::let_underscore_future)]
627        let _ = spawn("iroh connection (next)", async move {
628            let mut paths = conn.paths_stream();
629            if let Some(paths) = paths.next().await {
630                debug!(target: LOG_NET_IROH, %node_id, ?paths, "Connection paths (initial)");
631            }
632            while let Some(paths) = paths.next().await {
633                debug!(target: LOG_NET_IROH, %node_id, ?paths, "Connection paths changed");
634                path_change.send_modify(|c| *c = c.wrapping_add(1));
635            }
636        });
637    }
638
639    async fn make_new_connection_stable(
640        &self,
641        node_id: NodeId,
642        node_addr: Option<NodeAddr>,
643    ) -> ServerResult<Connection> {
644        trace!(target: LOG_NET_IROH, %node_id, "Creating new stable connection");
645        let conn = match node_addr.clone() {
646            Some(node_addr) => {
647                trace!(target: LOG_NET_IROH, %node_id, "Using a connectivity override for connection");
648                let conn = self.stable
649                    .connect(node_addr.clone(), FEDIMINT_API_ALPN)
650                    .await;
651
652                #[cfg(not(target_family = "wasm"))]
653                if conn.is_ok() {
654                    Self::spawn_connection_monitoring_stable(
655                        &self.stable,
656                        node_id,
657                        self.path_change.clone(),
658                    );
659                }
660                conn
661            }
662            None => self.stable.connect(node_id, FEDIMINT_API_ALPN).await,
663        }.map_err(|err| ServerError::Connection(err.into()))?;
664
665        Ok(conn)
666    }
667
668    async fn make_new_connection_next(
669        &self,
670        endpoint_next: &iroh_next::Endpoint,
671        node_id: NodeId,
672        node_addr: Option<NodeAddr>,
673    ) -> ServerResult<iroh_next::endpoint::Connection> {
674        let next_node_id =
675            iroh_next::EndpointId::from_bytes(node_id.as_bytes()).expect("Can't fail");
676
677        let endpoint_next = endpoint_next.clone();
678
679        trace!(target: LOG_NET_IROH, %node_id, "Creating new next connection");
680        let conn = match node_addr.clone() {
681            Some(node_addr) => {
682                trace!(target: LOG_NET_IROH, %node_id, "Using a connectivity override for connection");
683                let node_addr = node_addr_stable_to_next(&node_addr);
684                let conn = endpoint_next
685                    .connect(node_addr.clone(), FEDIMINT_API_ALPN)
686                    .await;
687
688                #[cfg(not(target_family = "wasm"))]
689                if let Ok(conn) = &conn {
690                    Self::spawn_connection_monitoring_next(
691                        conn,
692                        node_addr.id,
693                        self.path_change.clone(),
694                    );
695                }
696
697                conn
698            }
699            None => endpoint_next.connect(
700                next_node_id,
701                FEDIMINT_API_ALPN
702            ).await,
703        }
704        .map_err(|err| ServerError::Connection(err.into()))?;
705
706        // Retain the connection so `connectivity` can read its paths back;
707        // iroh 1.0 offers no endpoint-level lookup to recover it from.
708        self.next_connections
709            .lock()
710            .expect("Next connection mutex is never held across a panic")
711            .insert(node_id, conn.clone());
712
713        Ok(conn)
714    }
715}
716
717/// QUIC transport config with explicit idle timeout and keep-alive
718/// for the stable iroh endpoint.
719fn quic_transport_config() -> iroh::endpoint::TransportConfig {
720    let mut config = iroh::endpoint::TransportConfig::default();
721    config.max_idle_timeout(Some(
722        IROH_IDLE_TIMEOUT
723            .try_into()
724            .expect("idle timeout fits in IdleTimeout"),
725    ));
726    config.keep_alive_interval(Some(IROH_KEEP_ALIVE_INTERVAL));
727    config
728}
729
730/// QUIC transport config with explicit idle timeout and keep-alive
731/// for the next iroh endpoint.
732fn quic_transport_config_next() -> iroh_next::endpoint::QuicTransportConfig {
733    iroh_next::endpoint::QuicTransportConfig::builder()
734        .max_idle_timeout(Some(
735            IROH_IDLE_TIMEOUT
736                .try_into()
737                .expect("idle timeout fits in IdleTimeout"),
738        ))
739        .keep_alive_interval(IROH_KEEP_ALIVE_INTERVAL)
740        .build()
741}
742
743fn connectivity_from_iroh_conn_type(conn_type: &iroh::endpoint::ConnectionType) -> Connectivity {
744    match conn_type {
745        iroh::endpoint::ConnectionType::Direct(_) => Connectivity::Direct,
746        iroh::endpoint::ConnectionType::Relay(_) => Connectivity::Relay,
747        iroh::endpoint::ConnectionType::Mixed(..) => Connectivity::Mixed,
748        iroh::endpoint::ConnectionType::None => Connectivity::Unknown,
749    }
750}
751
752fn node_addr_stable_to_next(stable: &iroh::NodeAddr) -> iroh_next::EndpointAddr {
753    let next_node_id =
754        iroh_next::EndpointId::from_bytes(stable.node_id.as_bytes()).expect("Can't fail");
755    let relay_addrs = stable.relay_url.iter().map(|u| {
756        iroh_next::TransportAddr::Relay(
757            iroh_next::RelayUrl::from_str(&u.to_string()).expect("Can't fail"),
758        )
759    });
760    let direct_addrs = stable
761        .direct_addresses
762        .iter()
763        .copied()
764        .map(iroh_next::TransportAddr::Ip);
765
766    iroh_next::EndpointAddr::from_parts(next_node_id, relay_addrs.chain(direct_addrs))
767}
768
769#[apply(async_trait_maybe_send!)]
770impl IConnection for Connection {
771    async fn await_disconnection(&self) {
772        self.closed().await;
773    }
774
775    fn is_connected(&self) -> bool {
776        self.close_reason().is_none()
777    }
778}
779
780#[async_trait]
781impl IGuardianConnection for Connection {
782    async fn request(&self, method: ApiMethod, request: ApiRequestErased) -> ServerResult<Value> {
783        let timeout = request_timeout_for_method(&method);
784        let method_str = method.to_string();
785        let json = serde_json::to_vec(&IrohApiRequest { method, request })
786            .expect("Serialization to vec can't fail");
787
788        let result = fedimint_core::runtime::timeout(timeout, async {
789            let (mut sink, mut stream) = self
790                .open_bi()
791                .await
792                .map_err(|e| ServerError::Transport(e.into()))?;
793
794            sink.write_all(&json)
795                .await
796                .map_err(|e| ServerError::Transport(e.into()))?;
797
798            sink.finish()
799                .map_err(|e| ServerError::Transport(e.into()))?;
800
801            stream
802                .read_to_end(IROH_MAX_RESPONSE_BYTES)
803                .await
804                .map_err(|e| ServerError::Transport(e.into()))
805        })
806        .await;
807
808        let response = match result {
809            Ok(Ok(bytes)) => bytes,
810            Ok(Err(err)) => return Err(err),
811            Err(_) => {
812                // The bi-stream stalled past our budget. Close the QUIC
813                // connection so [`Self::is_connected`] (which reads
814                // `close_reason`) starts returning false; the connection
815                // pool's `get_or_init_pool_entry` will then evict this
816                // entry on the next access and the upstream retry loop
817                // will get a fresh connection.
818                warn!(
819                    target: LOG_NET_IROH,
820                    method = %method_str,
821                    timeout_secs = timeout.as_secs(),
822                    "iroh request timed out, closing connection",
823                );
824                self.close(
825                    iroh::endpoint::VarInt::from_u32(IROH_REQUEST_TIMEOUT_ERROR_CODE),
826                    IROH_REQUEST_TIMEOUT_ERROR_REASON,
827                );
828                return Err(ServerError::Transport(
829                    format!("iroh request {method_str} timed out after {timeout:?}").into(),
830                ));
831            }
832        };
833
834        // TODO: We should not be serializing Results on the wire
835        let response = serde_json::from_slice::<Result<Value, ApiError>>(&response)
836            .map_err(|e| ServerError::InvalidResponse(e.fmt_compact().to_string()))?;
837
838        response.map_err(|e| ServerError::InvalidResponse(format!("Api Error: {e:?}")))
839    }
840}
841
842#[apply(async_trait_maybe_send!)]
843impl IConnection for iroh_next::endpoint::Connection {
844    async fn await_disconnection(&self) {
845        self.closed().await;
846    }
847
848    fn is_connected(&self) -> bool {
849        self.close_reason().is_none()
850    }
851}
852
853#[async_trait]
854impl IGuardianConnection for iroh_next::endpoint::Connection {
855    async fn request(&self, method: ApiMethod, request: ApiRequestErased) -> ServerResult<Value> {
856        let timeout = request_timeout_for_method(&method);
857        let method_str = method.to_string();
858        let json = serde_json::to_vec(&IrohApiRequest { method, request })
859            .expect("Serialization to vec can't fail");
860
861        let result = fedimint_core::runtime::timeout(timeout, async {
862            let (mut sink, mut stream) = self
863                .open_bi()
864                .await
865                .map_err(|e| ServerError::Transport(e.into()))?;
866
867            sink.write_all(&json)
868                .await
869                .map_err(|e| ServerError::Transport(e.into()))?;
870
871            sink.finish()
872                .map_err(|e| ServerError::Transport(e.into()))?;
873
874            stream
875                .read_to_end(IROH_MAX_RESPONSE_BYTES)
876                .await
877                .map_err(|e| ServerError::Transport(e.into()))
878        })
879        .await;
880
881        let response = match result {
882            Ok(Ok(bytes)) => bytes,
883            Ok(Err(err)) => return Err(err),
884            Err(_) => {
885                warn!(
886                    target: LOG_NET_IROH,
887                    method = %method_str,
888                    timeout_secs = timeout.as_secs(),
889                    "iroh request timed out, closing connection",
890                );
891                self.close(
892                    iroh_next::endpoint::VarInt::from_u32(IROH_REQUEST_TIMEOUT_ERROR_CODE),
893                    IROH_REQUEST_TIMEOUT_ERROR_REASON,
894                );
895                return Err(ServerError::Transport(
896                    format!("iroh request {method_str} timed out after {timeout:?}").into(),
897                ));
898            }
899        };
900
901        // TODO: We should not be serializing Results on the wire
902        let response = serde_json::from_slice::<Result<Value, ApiError>>(&response)
903            .map_err(|e| ServerError::InvalidResponse(e.fmt_compact().to_string()))?;
904
905        response.map_err(|e| ServerError::InvalidResponse(format!("Api Error: {e:?}")))
906    }
907}
908
909#[apply(async_trait_maybe_send!)]
910impl IGatewayConnection for Connection {
911    async fn request(
912        &self,
913        password: Option<String>,
914        _method: Method,
915        route: &str,
916        payload: Option<Value>,
917    ) -> ServerResult<Value> {
918        let iroh_request = IrohGatewayRequest {
919            route: route.to_string(),
920            params: payload,
921            password,
922        };
923        let json = serde_json::to_vec(&iroh_request).expect("serialization cant fail");
924
925        let (mut sink, mut stream) = self
926            .open_bi()
927            .await
928            .map_err(|e| ServerError::Transport(e.into()))?;
929
930        sink.write_all(&json)
931            .await
932            .map_err(|e| ServerError::Transport(e.into()))?;
933
934        sink.finish()
935            .map_err(|e| ServerError::Transport(e.into()))?;
936
937        let response = stream
938            .read_to_end(IROH_MAX_RESPONSE_BYTES)
939            .await
940            .map_err(|e| ServerError::Transport(e.into()))?;
941
942        let response = serde_json::from_slice::<IrohGatewayResponse>(&response)
943            .map_err(|e| ServerError::InvalidResponse(e.fmt_compact().to_string()))?;
944        match StatusCode::from_u16(response.status)
945            .map_err(|e| ServerError::InvalidResponse(format!("Invalid status code: {e}")))?
946        {
947            StatusCode::OK => Ok(response.body),
948            status => Err(ServerError::ServerError(format!(
949                "Server returned status code: {status}"
950            ))),
951        }
952    }
953}
954
955#[cfg(test)]
956mod tests;