Skip to main content

fedimint_core/net/
iroh.rs

1use std::net::SocketAddr;
2use std::time::Duration;
3
4use fedimint_core::util::SafeUrl;
5use fedimint_logging::LOG_NET_IROH;
6use iroh::defaults::DEFAULT_STUN_PORT;
7use iroh::discovery::pkarr::{PkarrPublisher, PkarrResolver};
8use iroh::endpoint::{Builder, TransportConfig};
9use iroh::{Endpoint, RelayMode, RelayNode, RelayUrl, SecretKey};
10use iroh_relay::RelayQuicConfig;
11use thiserror::Error;
12use tracing::{debug, info, warn};
13use url::Url;
14
15use crate::envs::{
16    FM_IROH_DHT_ENABLE_ENV, FM_IROH_N0_DISCOVERY_ENABLE_ENV, FM_IROH_PKARR_PUBLISHER_ENABLE_ENV,
17    FM_IROH_PKARR_RESOLVER_ENABLE_ENV, FM_IROH_RELAYS_ENABLE_ENV, is_env_var_set,
18    is_env_var_set_opt,
19};
20
21/// Fedimint-operated relays running the Iroh 0.35 relay protocol.
22const DEFAULT_IROH_RELAYS: [&str; 2] = [
23    "https://euc1-1.relay.elsirion.fedimint.iroh.link/",
24    "https://use1-1.relay.elsirion.fedimint.iroh.link/",
25];
26
27/// Fedimint-operated relays running the Iroh 1.0 relay protocol.
28///
29/// The relay wire protocol changed incompatibly between 0.35 and 1.0, so these
30/// are separate deployments from `DEFAULT_IROH_RELAYS` and the two lists must
31/// never be mixed. Kept here next to the 0.35 list so both are maintained in
32/// one place; the `RelayMode` is built by callers that have the `iroh_next`
33/// types in scope.
34///
35/// The `iroh.fedimint.org` entries are placeholders for a later migration to
36/// Fedimint-owned domains and do not resolve yet. Iroh only selects a home
37/// relay that answered the current round of probes, which run in parallel, so
38/// an unresolvable entry is never selected and costs one DNS lookup per round.
39/// Until a working Iroh 1.x relay serves them, these names must stay
40/// unresolvable: any server answering `/ping` with a 2xx status would be
41/// selected as a home relay.
42pub const DEFAULT_IROH_V1_RELAYS: [&str; 4] = [
43    "https://euc1-2.relay.elsirion.fedimint.iroh.link/",
44    "https://use1-2.relay.elsirion.fedimint.iroh.link/",
45    "https://eu01.iroh.fedimint.org/",
46    "https://us01.iroh.fedimint.org/",
47];
48
49/// QUIC idle timeout for every iroh endpoint.
50///
51/// With [`IROH_KEEP_ALIVE_INTERVAL`] underneath it, a dead connection surfaces
52/// within ~5s instead of the 30s QUIC default. The negotiated idle timeout is
53/// the minimum of both sides', so a guardian setting this caps detection
54/// latency for clients whose endpoints keep iroh's defaults. The path-level
55/// settings stay untouched — iroh tunes those for hole punching.
56pub const IROH_IDLE_TIMEOUT: Duration = Duration::from_secs(5);
57
58/// QUIC keep-alive interval for every iroh endpoint, see
59/// [`IROH_IDLE_TIMEOUT`].
60pub const IROH_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(1);
61
62pub async fn build_iroh_endpoint(
63    secret_key: SecretKey,
64    bind_addr: SocketAddr,
65    iroh_dns: Option<SafeUrl>,
66    iroh_relays: Vec<SafeUrl>,
67    alpn: &[u8],
68) -> Result<Endpoint, IrohEndpointError> {
69    let relay_mode = if !is_env_var_set_opt(FM_IROH_RELAYS_ENABLE_ENV).unwrap_or(true) {
70        warn!(
71            target: LOG_NET_IROH,
72            "Iroh relays are disabled"
73        );
74        RelayMode::Disabled
75    } else if iroh_relays.is_empty() {
76        RelayMode::Custom(
77            DEFAULT_IROH_RELAYS
78                .into_iter()
79                .map(|url| {
80                    relay_node_from_url(Url::parse(url).expect("default Iroh relay URL is valid"))
81                })
82                .collect(),
83        )
84    } else {
85        RelayMode::Custom(
86            iroh_relays
87                .into_iter()
88                .map(|url| relay_node_from_url(url.to_unsafe()))
89                .collect(),
90        )
91    };
92
93    let mut builder = Endpoint::builder();
94
95    if let Some(iroh_dns) = iroh_dns.map(SafeUrl::to_unsafe) {
96        if is_env_var_set_opt(FM_IROH_PKARR_PUBLISHER_ENABLE_ENV).unwrap_or(true) {
97            builder = builder.add_discovery({
98                let iroh_dns = iroh_dns.clone();
99                move |sk: &SecretKey| Some(PkarrPublisher::new(sk.clone(), iroh_dns))
100            });
101        } else {
102            warn!(
103                target: LOG_NET_IROH,
104                "Iroh pkarr publisher is disabled"
105            );
106        }
107
108        if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
109            builder = builder.add_discovery(|_| Some(PkarrResolver::new(iroh_dns)));
110        } else {
111            warn!(
112                target: LOG_NET_IROH,
113                "Iroh pkarr resolver is disabled"
114            );
115        }
116    }
117
118    // See <https://github.com/fedimint/fedimint/issues/7811>
119    if is_env_var_set(FM_IROH_DHT_ENABLE_ENV) {
120        #[cfg(not(target_family = "wasm"))]
121        {
122            debug!(
123                target: LOG_NET_IROH,
124                "Iroh DHT is enabled"
125            );
126            builder = builder.discovery_dht();
127        }
128    } else {
129        info!(
130            target: LOG_NET_IROH,
131            "Iroh DHT is disabled"
132        );
133    }
134
135    builder = add_n0_discovery(builder);
136
137    let mut transport_config = TransportConfig::default();
138    transport_config.max_idle_timeout(Some(
139        IROH_IDLE_TIMEOUT
140            .try_into()
141            .expect("idle timeout fits in IdleTimeout"),
142    ));
143    // Iroh's default builder sets keep_alive_interval to 1s, but since we're
144    // providing a custom TransportConfig we need to set it explicitly.
145    transport_config.keep_alive_interval(Some(IROH_KEEP_ALIVE_INTERVAL));
146
147    let builder = builder
148        .relay_mode(relay_mode)
149        .secret_key(secret_key)
150        .alpns(vec![alpn.to_vec()])
151        .transport_config(transport_config);
152
153    let builder = match bind_addr {
154        SocketAddr::V4(addr_v4) => builder.bind_addr_v4(addr_v4),
155        SocketAddr::V6(addr_v6) => builder.bind_addr_v6(addr_v6),
156    };
157
158    let endpoint = Box::pin(builder.bind())
159        .await
160        .map_err(|e| IrohEndpointError::Bind(e.into()))?;
161
162    info!(
163        target: LOG_NET_IROH,
164        %bind_addr,
165        node_id = %endpoint.node_id(),
166        node_id_pkarr = %z32::encode(endpoint.node_id().as_bytes()),
167        "Iroh p2p server endpoint"
168    );
169
170    Ok(endpoint)
171}
172
173/// Failure to set up an iroh endpoint.
174#[derive(Debug, Error)]
175#[non_exhaustive]
176pub enum IrohEndpointError {
177    /// The endpoint could not bind its socket or reach its relays.
178    #[error("Failed to bind Iroh endpoint")]
179    Bind(#[source] Box<dyn std::error::Error + Send + Sync>),
180}
181
182fn relay_node_from_url(url: Url) -> RelayNode {
183    RelayNode {
184        url: RelayUrl::from(url),
185        stun_only: false,
186        stun_port: DEFAULT_STUN_PORT,
187        quic: Some(RelayQuicConfig::default()),
188    }
189}
190
191fn add_n0_discovery(builder: Builder) -> Builder {
192    if is_env_var_set_opt(FM_IROH_N0_DISCOVERY_ENABLE_ENV).unwrap_or(true) {
193        return add_n0_pkarr_resolver(builder.discovery_n0());
194    }
195
196    warn!(target: LOG_NET_IROH, "Iroh n0 discovery is disabled");
197    builder
198}
199
200#[cfg(not(target_family = "wasm"))]
201fn add_n0_pkarr_resolver(builder: Builder) -> Builder {
202    // Native discovery_n0 only uses DNS TXT; add HTTPS pkarr fallback.
203    if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
204        return builder.add_discovery(|_| Some(PkarrResolver::n0_dns()));
205    }
206
207    warn!(
208        target: LOG_NET_IROH,
209        "Iroh pkarr resolver is disabled"
210    );
211    builder
212}
213
214#[cfg(target_family = "wasm")]
215fn add_n0_pkarr_resolver(builder: Builder) -> Builder {
216    builder
217}
218
219#[cfg(test)]
220mod tests;