Skip to main content

fedimint_server/net/p2p_connector/iroh/
endpoint.rs

1//! Guardian P2P endpoint construction for Iroh 1.0.
2//!
3//! This server-private builder is intentionally additive. The shared
4//! `fedimint_core::net::iroh` builder remains on Iroh 0.35 for guardian API and
5//! gateway callers while guardian P2P migrates independently.
6
7use std::borrow::Cow;
8use std::net::SocketAddr;
9
10use anyhow::Context as _;
11use fedimint_connectors::iroh::default_iroh_v1_relay_mode;
12use fedimint_core::envs::{
13    FM_IROH_DHT_ENABLE_ENV, FM_IROH_N0_DISCOVERY_ENABLE_ENV, FM_IROH_PKARR_PUBLISHER_ENABLE_ENV,
14    FM_IROH_PKARR_RESOLVER_ENABLE_ENV, FM_IROH_RELAYS_ENABLE_ENV, is_env_var_set,
15    is_env_var_set_opt,
16};
17use fedimint_core::net::iroh::{IROH_IDLE_TIMEOUT, IROH_KEEP_ALIVE_INTERVAL};
18use fedimint_core::util::SafeUrl;
19use fedimint_logging::LOG_NET_IROH;
20use iroh_next::address_lookup::{AddrFilter, DnsAddressLookup, PkarrPublisher, PkarrResolver};
21use iroh_next::endpoint::presets::Minimal;
22use iroh_next::endpoint::{Builder, QuicTransportConfig};
23use iroh_next::{Endpoint, RelayMode, RelayUrl, SecretKey, TransportAddr};
24use tracing::{debug, info, warn};
25
26use crate::net::iroh::configure_iroh_ip_transports;
27
28/// Build and bind an Iroh 1.0 endpoint using guardian P2P policy.
29pub(super) async fn build_iroh_endpoint(
30    secret_key: SecretKey,
31    bind_addr: SocketAddr,
32    iroh_dns: Option<SafeUrl>,
33    iroh_relays: Vec<SafeUrl>,
34    alpn: &[u8],
35) -> anyhow::Result<Endpoint> {
36    let relay_mode = if !is_env_var_set_opt(FM_IROH_RELAYS_ENABLE_ENV).unwrap_or(true) {
37        warn!(target: LOG_NET_IROH, "Iroh relays are disabled");
38        RelayMode::Disabled
39    } else if iroh_relays.is_empty() {
40        default_iroh_v1_relay_mode()
41    } else {
42        RelayMode::Custom(
43            iroh_relays
44                .into_iter()
45                .map(|url| RelayUrl::from(url.to_unsafe()))
46                .collect(),
47        )
48    };
49
50    let mut builder = Endpoint::builder(Minimal);
51
52    if let Some(iroh_dns) = iroh_dns.map(SafeUrl::to_unsafe) {
53        if is_env_var_set_opt(FM_IROH_PKARR_PUBLISHER_ENABLE_ENV).unwrap_or(true) {
54            builder = builder.address_lookup(
55                PkarrPublisher::builder(iroh_dns.clone()).addr_filter(guardian_pkarr_addr_filter()),
56            );
57        } else {
58            warn!(target: LOG_NET_IROH, "Iroh pkarr publisher is disabled");
59        }
60
61        if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
62            builder = builder.address_lookup(PkarrResolver::builder(iroh_dns));
63        } else {
64            warn!(target: LOG_NET_IROH, "Iroh pkarr resolver is disabled");
65        }
66    }
67
68    if is_env_var_set(FM_IROH_DHT_ENABLE_ENV) {
69        debug!(target: LOG_NET_IROH, "Iroh DHT is enabled");
70        builder = builder.address_lookup(iroh_mainline_address_lookup::DhtAddressLookup::builder());
71    } else {
72        info!(target: LOG_NET_IROH, "Iroh DHT is disabled");
73    }
74
75    builder = add_n0_discovery(builder);
76
77    let transport_config = QuicTransportConfig::builder()
78        .max_idle_timeout(Some(
79            IROH_IDLE_TIMEOUT
80                .try_into()
81                .expect("idle timeout fits in IdleTimeout"),
82        ))
83        .keep_alive_interval(IROH_KEEP_ALIVE_INTERVAL)
84        .build();
85
86    let endpoint = Box::pin(
87        configure_iroh_ip_transports(
88            builder
89                .relay_mode(relay_mode)
90                .secret_key(secret_key)
91                .alpns(vec![alpn.to_vec()])
92                .transport_config(transport_config),
93            bind_addr,
94        )?
95        .bind(),
96    )
97    .await
98    .context("Failed to bind Iroh endpoint")?;
99
100    info!(
101        target: LOG_NET_IROH,
102        %bind_addr,
103        endpoint_id = %endpoint.id(),
104        endpoint_id_pkarr = %z32::encode(endpoint.id().as_bytes()),
105        "Iroh P2P server endpoint"
106    );
107
108    Ok(endpoint)
109}
110
111fn add_n0_discovery(mut builder: Builder) -> Builder {
112    if !is_env_var_set_opt(FM_IROH_N0_DISCOVERY_ENABLE_ENV).unwrap_or(true) {
113        warn!(target: LOG_NET_IROH, "Iroh n0 discovery is disabled");
114        return builder;
115    }
116
117    // Publish our address as well as resolving peer addresses. Starting from
118    // `Minimal` installs neither half automatically.
119    builder = builder
120        .address_lookup(PkarrPublisher::n0_dns().addr_filter(guardian_pkarr_addr_filter()))
121        .address_lookup(DnsAddressLookup::n0_dns());
122
123    if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
124        builder.address_lookup(PkarrResolver::n0_dns())
125    } else {
126        warn!(target: LOG_NET_IROH, "Iroh pkarr resolver is disabled");
127        builder
128    }
129}
130
131/// Preserve Iroh 0.35's Pkarr publication policy for guardian connectivity.
132///
133/// Prefer relays when available to avoid publishing direct IP addresses. When
134/// no relay is available, direct addresses must be published so relay-disabled
135/// guardians remain discoverable by endpoint ID.
136pub(super) fn guardian_pkarr_addr_filter() -> AddrFilter {
137    AddrFilter::new(|addrs| {
138        let publish_relay = addrs.iter().any(TransportAddr::is_relay);
139        Cow::Owned(
140            addrs
141                .iter()
142                .filter(|addr| {
143                    if publish_relay {
144                        addr.is_relay()
145                    } else {
146                        matches!(addr, TransportAddr::Ip(_))
147                    }
148                })
149                .cloned()
150                .collect(),
151        )
152    })
153}