diff --git a/ensemble/src/iroh.rs b/ensemble/src/iroh.rs index 10e3cbab..3cd7339c 100644 --- a/ensemble/src/iroh.rs +++ b/ensemble/src/iroh.rs @@ -21,6 +21,8 @@ pub const IROH_HINT: &str = "iroh:"; pub const IROH_IP_HINT: &str = "iroh-ip:"; +pub const IROH_RELAY_HINT: &str = "iroh-relay:"; + const PRIMING_NEWLINE: &[u8] = b"\n"; pub fn dialable_addr(bound: std::net::SocketAddr) -> std::net::SocketAddr { @@ -177,18 +179,14 @@ impl IrohTransport { Ok(Self::new(endpoint)) } - pub async fn bind_direct_with_key(humd_key: &crate::HumdKey) -> Result { - Self::bind_direct_with_key_on(humd_key, None).await + pub async fn bind_with_key(humd_key: &crate::HumdKey) -> Result { + Self::bind_with_key_on(humd_key, None).await } - pub async fn bind_direct_with_key_on( - humd_key: &crate::HumdKey, - port: Option, - ) -> Result { + pub async fn bind_with_key_on(humd_key: &crate::HumdKey, port: Option) -> Result { let sk = iroh::SecretKey::from_bytes(&humd_key.0.to_bytes()); - let mut builder = Endpoint::builder(iroh::endpoint::presets::Minimal) + let mut builder = Endpoint::builder(iroh::endpoint::presets::N0) .alpns(vec![IROH_ALPN.to_vec()]) - .relay_mode(iroh::RelayMode::Disabled) .secret_key(sk); if let Some(port) = port { let addr = std::net::SocketAddr::new( @@ -234,12 +232,29 @@ impl IrohTransport { self.endpoint.id() } - pub fn dial_hints(&self) -> Vec { + pub async fn online_within(&self, wait: std::time::Duration) -> bool { + tokio::time::timeout(wait, self.endpoint.online()) + .await + .is_ok() + } + + pub fn relay_hints(&self) -> Vec { self.endpoint + .addr() + .relay_urls() + .map(|url| format!("{IROH_RELAY_HINT}{url}")) + .collect() + } + + pub fn dial_hints(&self) -> Vec { + let mut hints: Vec = self + .endpoint .bound_sockets() .into_iter() .map(|s| format!("{IROH_IP_HINT}{}", dialable_addr(s))) - .collect() + .collect(); + hints.extend(self.relay_hints()); + hints } pub async fn accept(&self) -> Result> { @@ -268,31 +283,43 @@ impl IrohTransport { } } +pub fn endpoint_addr_from_hints(addr: &HumdAddr) -> Result { + let hint = addr + .hints + .iter() + .find_map(|h| h.strip_prefix(IROH_HINT)) + .ok_or_else(|| anyhow!("iroh transport: no `iroh:` hint in HumdAddr"))?; + let node_id_bytes = + hex::decode(hint).with_context(|| format!("iroh transport: hint `{hint}` is not hex"))?; + if node_id_bytes.len() != 32 { + return Err(anyhow!("iroh transport: NodeId must be 32 bytes")); + } + let mut arr = [0u8; 32]; + arr.copy_from_slice(&node_id_bytes); + let node_id = + PublicKey::from_bytes(&arr).map_err(|e| anyhow!("iroh transport: invalid NodeId: {e}"))?; + let direct_addrs = addr + .hints + .iter() + .filter_map(|h| h.strip_prefix(IROH_IP_HINT)) + .filter_map(|s| s.parse().ok()) + .map(TransportAddr::Ip); + let relay_addrs = addr + .hints + .iter() + .filter_map(|h| h.strip_prefix(IROH_RELAY_HINT)) + .filter_map(|s| s.parse::().ok()) + .map(TransportAddr::Relay); + Ok(EndpointAddr::from_parts( + node_id, + direct_addrs.chain(relay_addrs), + )) +} + #[async_trait] impl Transport for IrohTransport { async fn connect(&self, addr: &HumdAddr) -> Result> { - let hint = addr - .hints - .iter() - .find_map(|h| h.strip_prefix(IROH_HINT)) - .ok_or_else(|| anyhow!("iroh transport: no `iroh:` hint in HumdAddr"))?; - let node_id_bytes = hex::decode(hint) - .with_context(|| format!("iroh transport: hint `{hint}` is not hex"))?; - if node_id_bytes.len() != 32 { - return Err(anyhow!("iroh transport: NodeId must be 32 bytes")); - } - let mut arr = [0u8; 32]; - arr.copy_from_slice(&node_id_bytes); - let node_id = PublicKey::from_bytes(&arr) - .map_err(|e| anyhow!("iroh transport: invalid NodeId: {e}"))?; - let direct_addrs: Vec = addr - .hints - .iter() - .filter_map(|h| h.strip_prefix(IROH_IP_HINT)) - .filter_map(|s| s.parse().ok()) - .map(TransportAddr::Ip) - .collect(); - let endpoint_addr = EndpointAddr::from_parts(node_id, direct_addrs); + let endpoint_addr = endpoint_addr_from_hints(addr)?; let endpoint = IrohEndpoint::connect(&self.endpoint, endpoint_addr, PeerCapabilities::default()) .await?; @@ -347,3 +374,84 @@ mod dial_tests { ); } } + +#[cfg(test)] +mod hint_tests { + use super::{IROH_HINT, IROH_IP_HINT, IROH_RELAY_HINT, endpoint_addr_from_hints}; + use crate::{Hid, HumdAddr, HumdKey}; + use iroh::{RelayUrl, TransportAddr}; + use std::net::SocketAddr; + + const RELAY: &str = "https://euc1-1.relay.n0.iroh-canary.iroh.link./"; + + fn node_hint(key: &HumdKey) -> String { + format!( + "{IROH_HINT}{}", + hex::encode(key.0.verifying_key().as_bytes()) + ) + } + + #[test] + fn a_relay_hint_reaches_the_endpoint_addr() { + let key = HumdKey::generate(); + let addr = HumdAddr::new(key.hid()) + .with_hint(node_hint(&key)) + .with_hint(format!("{IROH_RELAY_HINT}{RELAY}")); + let ea = endpoint_addr_from_hints(&addr).expect("parse"); + let relay: RelayUrl = RELAY.parse().expect("relay url"); + assert_eq!(ea.relay_urls().collect::>(), vec![&relay]); + assert_eq!(ea.ip_addrs().count(), 0); + } + + #[test] + fn ip_and_relay_hints_travel_together() { + let key = HumdKey::generate(); + let ip: SocketAddr = "192.168.1.5:4556".parse().expect("ip"); + let addr = HumdAddr::new(key.hid()) + .with_hint(node_hint(&key)) + .with_hint(format!("{IROH_IP_HINT}{ip}")) + .with_hint(format!("{IROH_RELAY_HINT}{RELAY}")); + let ea = endpoint_addr_from_hints(&addr).expect("parse"); + assert_eq!(ea.ip_addrs().collect::>(), vec![&ip]); + assert_eq!(ea.relay_urls().count(), 1); + assert_eq!(ea.id.as_bytes(), key.0.verifying_key().as_bytes()); + } + + #[test] + fn a_node_id_alone_is_enough_to_dial() { + let key = HumdKey::generate(); + let addr = HumdAddr::new(key.hid()).with_hint(node_hint(&key)); + let ea = endpoint_addr_from_hints(&addr).expect("parse"); + assert!(ea.addrs.is_empty()); + } + + #[test] + fn a_relay_hint_round_trips_through_its_string() { + let relay: RelayUrl = RELAY.parse().expect("relay url"); + let hint = format!("{IROH_RELAY_HINT}{relay}"); + let back: RelayUrl = hint + .strip_prefix(IROH_RELAY_HINT) + .expect("prefix") + .parse() + .expect("reparse"); + assert_eq!(back, relay); + } + + #[test] + fn an_unparseable_relay_hint_is_skipped() { + let key = HumdKey::generate(); + let addr = HumdAddr::new(key.hid()) + .with_hint(node_hint(&key)) + .with_hint(format!("{IROH_RELAY_HINT}not a url")); + let ea = endpoint_addr_from_hints(&addr).expect("parse"); + assert!(!ea.addrs.iter().any(TransportAddr::is_relay)); + } + + #[test] + fn relay_and_ip_hints_are_not_mistaken_for_the_node_id() { + let addr = HumdAddr::new(Hid::random_humd()) + .with_hint(format!("{IROH_RELAY_HINT}{RELAY}")) + .with_hint(format!("{IROH_IP_HINT}10.0.0.1:1")); + assert!(endpoint_addr_from_hints(&addr).is_err()); + } +} diff --git a/ensemble/src/lib.rs b/ensemble/src/lib.rs index 553a2059..99cf1dc4 100644 --- a/ensemble/src/lib.rs +++ b/ensemble/src/lib.rs @@ -41,7 +41,10 @@ pub use tls::{ }; pub mod iroh; -pub use iroh::{IROH_ALPN, IROH_IP_HINT, IrohEndpoint, IrohTransport, dialable_addr}; +pub use iroh::{ + IROH_ALPN, IROH_IP_HINT, IROH_RELAY_HINT, IrohEndpoint, IrohTransport, dialable_addr, + endpoint_addr_from_hints, +}; pub mod delivery; pub mod framing; diff --git a/ensemble/tests/iroh_relay.rs b/ensemble/tests/iroh_relay.rs new file mode 100644 index 00000000..6c2e67c7 --- /dev/null +++ b/ensemble/tests/iroh_relay.rs @@ -0,0 +1,112 @@ +//! Two humds meet across the public n0 relay mesh, with no IP address +//! of the other side that works. This is the shape of two devices +//! behind separate NATs. +//! +//! These reach the live n0 relay and DNS servers, so they are +//! `#[ignore]`d and CI never depends on them. Run them by hand: +//! +//! ```text +//! cargo test -p ensemble --test iroh_relay -- --ignored --nocapture +//! ``` + +use std::sync::Arc; +use std::time::Duration; + +use ensemble::{ + HumdAddr, HumdKey, IROH_RELAY_HINT, IrohEndpoint, IrohTransport, PeerConnection, Transport, +}; +use serde_json::json; + +const ONLINE_WAIT: Duration = Duration::from_secs(20); +const DIAL_WAIT: Duration = Duration::from_secs(15); +const DIAL_ATTEMPTS: u32 = 4; + +const UNROUTABLE_IP_HINT: &str = "iroh-ip:192.0.2.1:4556"; + +async fn online_humd() -> (IrohTransport, HumdKey) { + let key = HumdKey::generate(); + let transport = IrohTransport::bind_with_key(&key) + .await + .expect("bind with key"); + assert!( + transport.online_within(ONLINE_WAIT).await, + "no home relay within {ONLINE_WAIT:?}: is the n0 relay mesh reachable from here?" + ); + (transport, key) +} + +fn node_hint(transport: &IrohTransport) -> String { + format!("iroh:{}", hex::encode(transport.node_id().as_bytes())) +} + +async fn dial_until_reached(dialer: &IrohTransport, target: &HumdAddr) -> Arc { + let mut last_err = String::new(); + for attempt in 1..=DIAL_ATTEMPTS { + match tokio::time::timeout(DIAL_WAIT, dialer.connect(target)).await { + Ok(Ok(conn)) => return conn, + Ok(Err(e)) => last_err = e.to_string(), + Err(_) => last_err = format!("no answer within {DIAL_WAIT:?}"), + } + eprintln!("iroh_relay: dial attempt {attempt} failed: {last_err}"); + } + panic!("never reached the peer over the relay: {last_err}"); +} + +async fn a_tone_crosses(listener: Arc, dialer: &IrohTransport, target: HumdAddr) { + let accepted = tokio::spawn(async move { + let peer: Arc = listener.accept().await.expect("accept"); + let mut rx = peer.take_receiver().expect("receiver"); + let tone = tokio::time::timeout(DIAL_WAIT, rx.recv()) + .await + .expect("tone within the wait") + .expect("link stayed open"); + (peer, tone) + }); + + let conn = dial_until_reached(dialer, &target).await; + conn.send_opening(json!({"chi": "ping", "rid": "across-the-relay"})) + .await + .expect("send"); + + let (_peer, tone) = tokio::time::timeout(DIAL_WAIT * DIAL_ATTEMPTS, accepted) + .await + .expect("listener heard the tone in time") + .expect("listener task"); + assert_eq!(tone["rid"], "across-the-relay"); +} + +#[tokio::test] +#[ignore = "reaches the live n0 relay mesh"] +async fn a_humd_is_reached_through_the_relay_it_advertises() { + let (listener, _listener_key) = online_humd().await; + let (dialer, _dialer_key) = online_humd().await; + + let relay_hints = listener.relay_hints(); + assert!( + !relay_hints.is_empty(), + "an online humd must advertise its home relay" + ); + assert!(relay_hints.iter().all(|h| h.starts_with(IROH_RELAY_HINT))); + + let mut target = HumdAddr::new(ensemble::iroh::humd_id_from_node_id(&listener.node_id())) + .with_hint(node_hint(&listener)) + .with_hint(UNROUTABLE_IP_HINT); + for hint in relay_hints { + target = target.with_hint(hint); + } + + a_tone_crosses(Arc::new(listener), &dialer, target).await; +} + +#[tokio::test] +#[ignore = "reaches the live n0 relay mesh and n0 DNS"] +async fn a_humd_is_reached_by_node_id_alone_through_dns() { + let (listener, _listener_key) = online_humd().await; + let (dialer, _dialer_key) = online_humd().await; + + let target = HumdAddr::new(ensemble::iroh::humd_id_from_node_id(&listener.node_id())) + .with_hint(node_hint(&listener)) + .with_hint(UNROUTABLE_IP_HINT); + + a_tone_crosses(Arc::new(listener), &dialer, target).await; +} diff --git a/humd/src/peer_transport/iroh.rs b/humd/src/peer_transport/iroh.rs index 02c0a2a9..35d23f86 100644 --- a/humd/src/peer_transport/iroh.rs +++ b/humd/src/peer_transport/iroh.rs @@ -9,8 +9,9 @@ //! //! 1. [`bind`] — build an [`IrohTransport`] using `humd_key`. Returns //! the transport plus the `peers.json` hint strings a remote peer -//! would paste in to dial this humd back (`iroh:` plus one -//! `iroh-ip:` per bound socket). +//! would paste in to dial this humd back (`iroh:`, one +//! `iroh-ip:` per local address, and `iroh-relay:` +//! for the home relay when one is reached within [`RELAY_WAIT`]). //! //! 2. [`dial_all`] — walk `peers.json`, open one iroh connection per //! entry that has an `iroh:` hint, install each via @@ -21,11 +22,17 @@ //! Each accepted connection is installed the same way, so the dial //! and accept paths converge on a single registry entry per peer. //! -//! Relay is disabled — this is the loopback/LAN/direct path. WAN over -//! a relay mesh lands later via a sibling bind path on this module. +//! The endpoint runs iroh's n0 preset: the public n0 relay mesh plus +//! n0's DNS address lookup. A humd behind NAT keeps a home relay and +//! publishes it under its node id, so a peer can dial it anywhere in +//! the world. With only an `iroh:` hint the dialer resolves the +//! current relay by DNS. An `iroh-relay:` hint skips that lookup. iroh +//! opens on whichever path answers first, then hole-punches to a +//! direct path when the NATs allow it. use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; use ensemble::{Ensemble, HumdAddr, HumdKey, IrohTransport, PeerCapabilities, PeerConnection}; use tracing::{info, warn}; @@ -36,7 +43,7 @@ pub(crate) async fn bind( humd_key: &HumdKey, port: u16, ) -> anyhow::Result<(IrohTransport, Vec)> { - let transport = match IrohTransport::bind_direct_with_key_on(humd_key, port_nonzero(port)).await { + let transport = match IrohTransport::bind_with_key_on(humd_key, port_nonzero(port)).await { Ok(t) => t, Err(e) => { warn!( @@ -44,39 +51,47 @@ pub(crate) async fn bind( err = %e, "peer.iroh.fixed_port.bind_failed — taking an ephemeral port; the address peers hold goes stale on restart" ); - IrohTransport::bind_direct_with_key(humd_key).await? + IrohTransport::bind_with_key(humd_key).await? } }; let node_id_hex = hex::encode(transport.node_id().as_bytes()); - let discovered: Vec = transport - .endpoint() - .addr() - .ip_addrs() - .copied() - .collect(); - let hints = dial_hints(&node_id_hex, &discovered); + if !transport.online_within(RELAY_WAIT).await { + warn!( + wait_ms = RELAY_WAIT.as_millis() as u64, + "peer.iroh.relay.not_yet — no home relay; peers outside this network can dial once it connects, by node id" + ); + } + let addr = transport.endpoint().addr(); + let discovered: Vec = addr.ip_addrs().copied().collect(); + let relays: Vec = addr.relay_urls().map(|u| u.to_string()).collect(); + let hints = dial_hints(&node_id_hex, &discovered, &relays); info!( node_id = %&node_id_hex[..16], - socket_count = hints.len() - 1, + socket_count = discovered.len(), + relay = relays.first().map(String::as_str).unwrap_or("none"), "peer.iroh.bound" ); Ok((transport, hints)) } +const RELAY_WAIT: Duration = Duration::from_secs(5); + fn port_nonzero(port: u16) -> Option { if port == 0 { None } else { Some(port) } } -fn dial_hints(node_id_hex: &str, addrs: &[SocketAddr]) -> Vec { - let routable: Vec = addrs +fn dial_hints(node_id_hex: &str, addrs: &[SocketAddr], relays: &[String]) -> Vec { + let routable = addrs .iter() .filter(|addr| !addr.ip().is_unspecified()) - .map(|addr| format!("iroh-ip:{addr}")) - .collect(); - let mut hints = Vec::with_capacity(1 + routable.len()); - hints.push(format!("iroh:{node_id_hex}")); - hints.extend(routable); - hints + .map(|addr| format!("{}{addr}", ensemble::IROH_IP_HINT)); + let relayed = relays + .iter() + .map(|url| format!("{}{url}", ensemble::IROH_RELAY_HINT)); + std::iter::once(format!("{}{node_id_hex}", ensemble::iroh::IROH_HINT)) + .chain(routable) + .chain(relayed) + .collect() } pub(crate) async fn dial_and_install_peer( @@ -155,11 +170,25 @@ mod tests { let routable: SocketAddr = "10.0.0.5:4556".parse().unwrap(); let wildcard: SocketAddr = "0.0.0.0:4556".parse().unwrap(); assert_eq!( - dial_hints("node", &[routable, wildcard]), + dial_hints("node", &[routable, wildcard], &[]), vec!["iroh:node".to_string(), "iroh-ip:10.0.0.5:4556".to_string()], ); } + #[test] + fn the_home_relay_is_advertised_after_the_addresses() { + let routable: SocketAddr = "10.0.0.5:4556".parse().unwrap(); + let relay = "https://use1-1.relay.n0.iroh-canary.iroh.link./".to_string(); + assert_eq!( + dial_hints("node", &[routable], std::slice::from_ref(&relay)), + vec![ + "iroh:node".to_string(), + "iroh-ip:10.0.0.5:4556".to_string(), + format!("iroh-relay:{relay}"), + ], + ); + } + use super::*; use ensemble::{Ensemble, HumdKey}; use std::time::Duration;