Skip to main content

fedimint_server/net/
iroh.rs

1use std::net::SocketAddr;
2
3use anyhow::Context as _;
4use fedimint_connectors::iroh::default_iroh_v1_relay_mode;
5use fedimint_connectors::{ConnectorRegistry, ConnectorRegistryBuilder};
6use fedimint_core::envs::{
7    FM_IROH_DHT_ENABLE_ENV, FM_IROH_N0_DISCOVERY_ENABLE_ENV, FM_IROH_P2P_ENABLE_ENV,
8    FM_IROH_PKARR_PUBLISHER_ENABLE_ENV, FM_IROH_PKARR_RESOLVER_ENABLE_ENV,
9    FM_IROH_RELAYS_ENABLE_ENV, is_env_var_set, is_env_var_set_opt,
10};
11use fedimint_core::net::iroh::{IROH_IDLE_TIMEOUT, IROH_KEEP_ALIVE_INTERVAL};
12use fedimint_core::secp256k1::SecretKey;
13use fedimint_core::util::SafeUrl;
14use fedimint_derive_secret::{ChildId, DerivableSecret};
15use fedimint_logging::LOG_NET_IROH;
16use iroh_next::address_lookup::{DnsAddressLookup, PkarrPublisher, PkarrResolver};
17use iroh_next::endpoint::presets::Minimal;
18use iroh_next::endpoint::{Builder, QuicTransportConfig};
19use iroh_next::{Endpoint, RelayMode};
20use tracing::{debug, info, warn};
21
22/// Child key used for the Iroh 1.0 API endpoint.
23const IROH_V1_API_CHILD_ID: ChildId = ChildId(0);
24
25fn direct_ip_transports_enabled() -> bool {
26    is_env_var_set_opt(FM_IROH_P2P_ENABLE_ENV).unwrap_or(true)
27}
28
29/// Apply the same local policy to guardian-origin API connections.
30pub(crate) fn guardian_connector_registry_builder() -> ConnectorRegistryBuilder {
31    ConnectorRegistry::build_from_server_defaults().iroh_p2p(direct_ip_transports_enabled())
32}
33
34/// Apply the local guardian IP transport policy to both Iroh 1.x listeners.
35pub(crate) fn configure_iroh_ip_transports(
36    builder: Builder,
37    bind_addr: SocketAddr,
38) -> anyhow::Result<Builder> {
39    // Remove the default wildcard sockets, including IPv6. Adding a bind
40    // address installs an IP transport again, so do that only when enabled.
41    let builder = builder.clear_ip_transports();
42    if direct_ip_transports_enabled() {
43        builder
44            .bind_addr(bind_addr)
45            .context("Invalid Iroh bind address")
46    } else {
47        info!(target: LOG_NET_IROH, "Guardian Iroh 1.x direct IP transports are disabled");
48        Ok(builder)
49    }
50}
51
52/// Derive the Iroh 1.0 API secret key from the guardian broadcast key.
53pub(crate) fn derive_iroh_v1_api_secret_key(broadcast_sk: &SecretKey) -> iroh_next::SecretKey {
54    let root = DerivableSecret::new_root(&broadcast_sk.secret_bytes(), b"fedimint-iroh-next");
55    let seed: [u8; 32] = root.child_key(IROH_V1_API_CHILD_ID).to_random_bytes();
56    iroh_next::SecretKey::from_bytes(&seed)
57}
58
59/// Build an Iroh 1.0 server endpoint.
60pub(crate) async fn build_iroh_v1_endpoint(
61    secret_key: iroh_next::SecretKey,
62    bind_addr: SocketAddr,
63    iroh_dns: Option<SafeUrl>,
64    alpn: &[u8],
65) -> anyhow::Result<Endpoint> {
66    let relay_mode = if is_env_var_set_opt(FM_IROH_RELAYS_ENABLE_ENV).unwrap_or(true) {
67        default_iroh_v1_relay_mode()
68    } else {
69        warn!(target: LOG_NET_IROH, "Iroh 1.0 relays are disabled");
70        RelayMode::Disabled
71    };
72
73    let mut builder = Endpoint::builder(Minimal);
74
75    if let Some(iroh_dns) = iroh_dns.map(SafeUrl::to_unsafe) {
76        if is_env_var_set_opt(FM_IROH_PKARR_PUBLISHER_ENABLE_ENV).unwrap_or(true) {
77            builder = builder.address_lookup(PkarrPublisher::builder(iroh_dns.clone()));
78        } else {
79            warn!(target: LOG_NET_IROH, "Iroh 1.0 pkarr publisher is disabled");
80        }
81
82        if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
83            builder = builder.address_lookup(PkarrResolver::builder(iroh_dns));
84        } else {
85            warn!(target: LOG_NET_IROH, "Iroh 1.0 pkarr resolver is disabled");
86        }
87    }
88
89    if is_env_var_set(FM_IROH_DHT_ENABLE_ENV) {
90        debug!(target: LOG_NET_IROH, "Iroh 1.0 DHT is enabled");
91        builder = builder.address_lookup(iroh_mainline_address_lookup::DhtAddressLookup::builder());
92    } else {
93        info!(target: LOG_NET_IROH, "Iroh 1.0 DHT is disabled");
94    }
95
96    if is_env_var_set_opt(FM_IROH_N0_DISCOVERY_ENABLE_ENV).unwrap_or(true) {
97        if is_env_var_set_opt(FM_IROH_PKARR_PUBLISHER_ENABLE_ENV).unwrap_or(true) {
98            builder = builder.address_lookup(PkarrPublisher::n0_dns());
99        }
100        builder = builder.address_lookup(DnsAddressLookup::n0_dns());
101
102        if is_env_var_set_opt(FM_IROH_PKARR_RESOLVER_ENABLE_ENV).unwrap_or(true) {
103            builder = builder.address_lookup(PkarrResolver::n0_dns());
104        }
105    } else {
106        warn!(target: LOG_NET_IROH, "Iroh 1.0 n0 discovery is disabled");
107    }
108
109    let transport_config = QuicTransportConfig::builder()
110        .max_idle_timeout(Some(
111            IROH_IDLE_TIMEOUT
112                .try_into()
113                .expect("idle timeout fits in IdleTimeout"),
114        ))
115        .keep_alive_interval(IROH_KEEP_ALIVE_INTERVAL)
116        .build();
117
118    let endpoint = Box::pin(
119        configure_iroh_ip_transports(
120            builder
121                .relay_mode(relay_mode)
122                .secret_key(secret_key)
123                .alpns(vec![alpn.to_vec()])
124                .transport_config(transport_config),
125            bind_addr,
126        )?
127        .bind(),
128    )
129    .await
130    .context("Failed to bind Iroh 1.0 endpoint")?;
131
132    info!(
133        target: LOG_NET_IROH,
134        %bind_addr,
135        endpoint_id = %endpoint.id(),
136        endpoint_id_pkarr = %z32::encode(endpoint.id().as_bytes()),
137        "Iroh 1.0 API server endpoint"
138    );
139
140    Ok(endpoint)
141}
142
143#[cfg(test)]
144mod tests;