Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 140 additions & 32 deletions ensemble/src/iroh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -177,18 +179,14 @@ impl IrohTransport {
Ok(Self::new(endpoint))
}

pub async fn bind_direct_with_key(humd_key: &crate::HumdKey) -> Result<Self> {
Self::bind_direct_with_key_on(humd_key, None).await
pub async fn bind_with_key(humd_key: &crate::HumdKey) -> Result<Self> {
Self::bind_with_key_on(humd_key, None).await
}

pub async fn bind_direct_with_key_on(
humd_key: &crate::HumdKey,
port: Option<u16>,
) -> Result<Self> {
pub async fn bind_with_key_on(humd_key: &crate::HumdKey, port: Option<u16>) -> Result<Self> {
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(
Expand Down Expand Up @@ -234,12 +232,29 @@ impl IrohTransport {
self.endpoint.id()
}

pub fn dial_hints(&self) -> Vec<String> {
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<String> {
self.endpoint
.addr()
.relay_urls()
.map(|url| format!("{IROH_RELAY_HINT}{url}"))
.collect()
}

pub fn dial_hints(&self) -> Vec<String> {
let mut hints: Vec<String> = 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<Arc<IrohEndpoint>> {
Expand Down Expand Up @@ -268,31 +283,43 @@ impl IrohTransport {
}
}

pub fn endpoint_addr_from_hints(addr: &HumdAddr) -> Result<EndpointAddr> {
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::<iroh::RelayUrl>().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<Arc<dyn PeerConnection>> {
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<TransportAddr> = 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?;
Expand Down Expand Up @@ -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<_>>(), 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<_>>(), 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());
}
}
5 changes: 4 additions & 1 deletion ensemble/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
112 changes: 112 additions & 0 deletions ensemble/tests/iroh_relay.rs
Original file line number Diff line number Diff line change
@@ -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<dyn PeerConnection> {
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<IrohTransport>, dialer: &IrohTransport, target: HumdAddr) {
let accepted = tokio::spawn(async move {
let peer: Arc<IrohEndpoint> = 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;
}
Loading
Loading