From 5ee69a47e67b9f87a67270c15ee4e3f7cce52671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Klaehn?= Date: Wed, 8 Nov 2023 12:03:23 +0200 Subject: [PATCH] feat: Add ability to connect just by node id This adds a fn to the magicsock to connect just by node id. Since a node id is insufficient to connect, a configurable discovery mechanism is added that allows finding direct addresses or at least the region id for a node id. An example exercising the discovery mechanism has been added in https://github.com/n0-computer/iroh-examples/pull/2 - [x] Self-review. - [x] Documentation updates if relevant. - [ ] Tests if relevant. --- iroh-bytes/src/get.rs | 31 ++++++++++----- iroh-net/src/key.rs | 4 +- iroh-net/src/magic_endpoint.rs | 72 ++++++++++++++++++++++++++++++---- iroh-net/src/magicsock.rs | 54 ++++++++++++++++++++++++- 4 files changed, 142 insertions(+), 19 deletions(-) diff --git a/iroh-bytes/src/get.rs b/iroh-bytes/src/get.rs index c8c8136c80..e3d1ec4c15 100644 --- a/iroh-bytes/src/get.rs +++ b/iroh-bytes/src/get.rs @@ -278,7 +278,7 @@ pub mod fsm { .into() } } - None => AtClosing::new(misc, reader).into(), + None => AtClosing::new(misc, reader, true).into(), }) } } @@ -338,7 +338,7 @@ pub mod fsm { /// read the collection, or when you want to stop reading the response /// early. pub fn finish(self) -> AtClosing { - AtClosing::new(self.misc, self.reader) + AtClosing::new(self.misc, self.reader, false) } } @@ -371,7 +371,7 @@ pub mod fsm { /// Finish the get response without reading further pub fn finish(self) -> AtClosing { - AtClosing::new(self.misc, self.reader) + AtClosing::new(self.misc, self.reader, false) } } @@ -741,7 +741,7 @@ pub mod fsm { /// Immediately finish the get response without reading further pub fn finish(self) -> AtClosing { - AtClosing::new(self.misc, self.stream.finish()) + AtClosing::new(self.misc, self.stream.finish(), false) } } @@ -773,7 +773,7 @@ pub mod fsm { } .into() } else { - AtClosing::new(self.misc, self.stream).into() + AtClosing::new(self.misc, self.stream, true).into() } } } @@ -783,20 +783,33 @@ pub mod fsm { pub struct AtClosing { misc: Box, reader: TrackingReader, + check_extra_data: bool, } impl AtClosing { - fn new(misc: Box, reader: TrackingReader) -> Self { - Self { misc, reader } + fn new( + misc: Box, + reader: TrackingReader, + check_extra_data: bool, + ) -> Self { + Self { + misc, + reader, + check_extra_data, + } } /// Finish the get response, returning statistics pub async fn next(self) -> result::Result { // Shut down the stream let (mut reader, bytes_read) = self.reader.into_parts(); - if let Some(chunk) = reader.read_chunk(8, false).await? { + if self.check_extra_data { + if let Some(chunk) = reader.read_chunk(8, false).await? { + reader.stop(0u8.into()).ok(); + error!("Received unexpected data from the provider: {chunk:?}"); + } + } else { reader.stop(0u8.into()).ok(); - error!("Received unexpected data from the provider: {chunk:?}"); } Ok(Stats { elapsed: self.misc.start.elapsed(), diff --git a/iroh-net/src/key.rs b/iroh-net/src/key.rs index 07d0b8c981..c58e011409 100644 --- a/iroh-net/src/key.rs +++ b/iroh-net/src/key.rs @@ -116,8 +116,8 @@ impl<'de> Deserialize<'de> for PublicKey { D: serde::Deserializer<'de>, { if deserializer.is_human_readable() { - let s: &str = serde::Deserialize::deserialize(deserializer)?; - Self::from_str(s).map_err(serde::de::Error::custom) + let s = String::deserialize(deserializer)?; + Self::from_str(&s).map_err(serde::de::Error::custom) } else { let bytes: &serde_bytes::Bytes = serde::Deserialize::deserialize(deserializer)?; Self::try_from(bytes.as_ref()).map_err(serde::de::Error::custom) diff --git a/iroh-net/src/magic_endpoint.rs b/iroh-net/src/magic_endpoint.rs index 6dae10f386..27f0e58f39 100644 --- a/iroh-net/src/magic_endpoint.rs +++ b/iroh-net/src/magic_endpoint.rs @@ -3,6 +3,7 @@ use std::{collections::BTreeSet, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration}; use anyhow::{anyhow, ensure, Context, Result}; +use derive_more::Debug; use quinn_proto::VarInt; use serde::{Deserialize, Serialize}; use tracing::{debug, trace}; @@ -12,7 +13,7 @@ use crate::{ defaults::default_derp_map, derp::{DerpMap, DerpMode}, key::{PublicKey, SecretKey}, - magicsock::{self, Callbacks, MagicSock}, + magicsock::{self, Callbacks, Discovery, MagicSock}, tls, }; @@ -118,6 +119,7 @@ pub struct MagicEndpointBuilder { concurrent_connections: Option, keylog: bool, callbacks: Callbacks, + discovery: Option>, /// Path for known peers. See [`MagicEndpointBuilder::peers_data_path`]. peers_path: Option, } @@ -132,6 +134,7 @@ impl Default for MagicEndpointBuilder { concurrent_connections: Default::default(), keylog: Default::default(), callbacks: Default::default(), + discovery: Default::default(), peers_path: None, } } @@ -233,6 +236,12 @@ impl MagicEndpointBuilder { self } + /// Optionally set a discovery mechanism for this endpoint. + pub fn discovery(mut self, discovery: Box) -> Self { + self.discovery = Some(discovery); + self + } + /// Bind the magic endpoint on the specified socket address. /// /// The *bind_port* is the port that should be bound locally. @@ -264,6 +273,7 @@ impl MagicEndpointBuilder { derp_map, callbacks: self.callbacks, nodes_path: self.peers_path, + discovery: self.discovery, }; MagicEndpoint::bind(Some(server_config), msock_opts, self.keylog).await } @@ -348,6 +358,11 @@ impl MagicEndpoint { &self.secret_key } + /// Optional reference to the discovery mechanism. + pub fn discovery(&self) -> Option<&dyn Discovery> { + self.msock.discovery() + } + /// Get the local endpoint addresses on which the underlying magic socket is bound. /// /// Returns a tuple of the IPv4 and the optional IPv6 address. @@ -412,6 +427,40 @@ impl MagicEndpoint { self.msock.tracked_endpoint(node_id).await } + async fn resolve(&self, node_id: &PublicKey) -> Result { + if let Some(discovery) = self.msock.discovery() { + debug!("no mapping address for {node_id}, resolving via {discovery:?}"); + discovery.resolve(node_id).await + } else { + anyhow::bail!("no discovery mechanism configured"); + } + } + + /// Connect to a remote endpoint, using just the nodes's [`PublicKey`]. + pub async fn connect_by_node_id( + &self, + node_id: &PublicKey, + alpn: &[u8], + ) -> Result { + let addr = match self.msock.get_mapping_addr(node_id).await { + Some(addr) => addr, + None => { + let info = self.resolve(node_id).await?; + let peer_addr = NodeAddr { + node_id: *node_id, + info, + }; + self.add_node_addr(peer_addr)?; + self.msock.get_mapping_addr(node_id).await.ok_or_else(|| { + anyhow!("Failed to retrieve the mapped address from the magic socket. Unable to dial node {node_id:?}") + })? + } + }; + + debug!("connecting to {}: (via {})", node_id, addr); + self.connect_inner(node_id, alpn, addr).await + } + /// Connect to a remote endpoint. /// /// The PublicKey and the ALPN protocol are required. If you happen to know dialable addresses of @@ -439,11 +488,25 @@ impl MagicEndpoint { }); }; + debug!( + "connecting to {}: (via {} - {:?})", + node_id, addr, info.direct_addresses + ); + + self.connect_inner(&node_id, alpn, addr).await + } + + async fn connect_inner( + &self, + node_id: &PublicKey, + alpn: &[u8], + addr: SocketAddr, + ) -> Result { let client_config = { let alpn_protocols = vec![alpn.to_vec()]; let tls_client_config = tls::make_client_config( &self.secret_key, - Some(node_id), + Some(*node_id), alpn_protocols, self.keylog, )?; @@ -454,11 +517,6 @@ impl MagicEndpoint { client_config }; - debug!( - "connecting to {}: (via {} - {:?})", - node_id, addr, info.direct_addresses - ); - // TODO: We'd eventually want to replace "localhost" with something that makes more sense. let connect = self .endpoint diff --git a/iroh-net/src/magicsock.rs b/iroh-net/src/magicsock.rs index e7c67246d7..709b366fd0 100644 --- a/iroh-net/src/magicsock.rs +++ b/iroh-net/src/magicsock.rs @@ -34,7 +34,7 @@ use std::{ use anyhow::{anyhow, Context as _, Result}; use bytes::Bytes; -use futures::FutureExt; +use futures::{future::BoxFuture, FutureExt}; use iroh_metrics::{inc, inc_by}; use quinn::AsyncUdpSocket; use rand::{seq::SliceRandom, Rng, SeedableRng}; @@ -56,6 +56,7 @@ use crate::{ net::{ip::LocalAddresses, netmon, IpFamily}, netcheck, portmapper, stun, util::AbortingJoinHandle, + AddrInfo, }; use self::{ @@ -110,6 +111,38 @@ pub struct Options { /// Path to store known nodes. pub nodes_path: Option, + + /// Optional node discovery mechanism. + pub discovery: Option>, +} + +/// Node discovery for [`super::MagicEndpoint`]. +/// +/// The purpose of this trait is to hoop up a node discovery mechanism that +/// allows finding informations such as the derp region and current addresses +/// of a node given the id. +/// +/// To allow for discovery, the [`super::MagicEndpoint`] will call `publish` whenever +/// discovery information changes. If a discovery mechanism requires a periodic +/// refresh, it should start it's own task. +pub trait Discovery: std::fmt::Debug + Send + Sync { + /// Publish the given [`AddrInfo`] to the discovery mechanisms. + /// + /// This is fire and forget, since the magicsock can not wait for successful + /// publishing. If publishing is async, the implementation should start it's + /// own task. + /// + /// This will be called from a tokio task, so it is safe to spawn new tasks. + /// These tasks will be run on the runtime of the [`super::MagicEndpoint`]. + fn publish(&self, info: &AddrInfo); + + /// Resolve the [`AddrInfo`] for the given [`PublicKey`]. + /// + /// This is only called from [`super::MagicEndpoint::connect_by_node_id`], and only if + /// the [`AddrInfo`] is not already known. + /// + /// This is async since the connect can not proceed without the [`AddrInfo`]. + fn resolve<'a>(&'a self, node_id: &'a PublicKey) -> BoxFuture<'a, Result>; } /// Contains options for `MagicSock::listen`. @@ -137,6 +170,7 @@ impl Default for Options { derp_map: DerpMap::empty(), callbacks: Default::default(), nodes_path: None, + discovery: None, } } } @@ -221,6 +255,8 @@ struct Inner { // UDP disco (ping) queue udp_disco_sender: mpsc::Sender<(SocketAddr, PublicKey, disco::Message)>, + // optional discovery service + discovery: Option>, // Our discovered endpoints endpoints: parking_lot::RwLock, @@ -1114,6 +1150,7 @@ impl MagicSock { on_derp_active, on_net_info, }, + discovery, nodes_path, } = opts; @@ -1194,6 +1231,7 @@ impl MagicSock { udp_state, send_buffer: Default::default(), udp_disco_sender, + discovery, endpoints: Default::default(), pending_call_me_maybes: Default::default(), endpoints_update_state: EndpointUpdateState::new(), @@ -1381,6 +1419,11 @@ impl MagicSock { .unwrap(); r.await.unwrap(); } + + /// Reference to optional discovery service + pub fn discovery(&self) -> Option<&dyn Discovery> { + self.inner.discovery.as_ref().map(Box::as_ref) + } } #[derive(Debug, Default)] @@ -1970,6 +2013,15 @@ impl Actor { if let Some(ref cb) = self.inner.on_endpoints { cb(&eps[..]); } + if let Some(ref discovery) = self.inner.discovery { + let direct_addresses = eps.iter().map(|ep| ep.addr).collect(); + let derp_region = Some(self.inner.my_derp()).filter(|x| *x != 0); + let info = AddrInfo { + derp_region, + direct_addresses, + }; + discovery.publish(&info); + } self.inner.send_queued_call_me_maybes(); } }