diff --git a/Cargo.lock b/Cargo.lock index 105080d600..c56bb71bba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,21 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "acto" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "148541f13c28e3e840354ee4d6c99046c10be2c81068bbd23b9e3a38f95a917e" -dependencies = [ - "parking_lot", - "pin-project-lite", - "rustc_version", - "smol_str", - "sync_wrapper", - "tokio", - "tracing", -] - [[package]] name = "addr2line" version = "0.25.1" @@ -2360,7 +2345,6 @@ dependencies = [ "iroh-dns", "iroh-metrics", "iroh-relay", - "mainline", "n0-error", "n0-future", "n0-tracing-test", @@ -2389,7 +2373,6 @@ dependencies = [ "serde_json", "smallvec", "strum 0.28.0", - "swarm-discovery", "testdir", "time", "tokio", @@ -4722,12 +4705,6 @@ dependencies = [ "serde", ] -[[package]] -name = "smol_str" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fad6c857cbab2627dcf01ec85a623ca4e7dcb5691cbaa3d7fb7653671f0d09c9" - [[package]] name = "socket2" version = "0.6.3" @@ -4878,21 +4855,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "swarm-discovery" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5e3cb18dc0532c89b4fd9f5c9a44cb2db3c15520b6fa37d604b878ba431afb" -dependencies = [ - "acto", - "hickory-proto 0.26.0", - "rand 0.10.1", - "socket2", - "thiserror 2.0.18", - "tokio", - "tracing", -] - [[package]] name = "syn" version = "2.0.117" diff --git a/iroh/Cargo.toml b/iroh/Cargo.toml index 0b603bd7a3..949708e81f 100644 --- a/iroh/Cargo.toml +++ b/iroh/Cargo.toml @@ -40,7 +40,6 @@ netwatch = "0.16" papaya = { version = "0.2.3", default-features = false } pin-project = "1" portable-atomic = "1" -mainline = { version = "6", optional = true } noq = { version = "0.18.0", default-features = false, features = ["rustls"] } noq-proto = { version = "0.17", default-features = false } noq-udp = { version = "0.10", default-features = false } @@ -69,8 +68,6 @@ pkcs8 = "0.11.0-rc.9" # metrics iroh-metrics = { version = "0.38", default-features = false } -# mdns -swarm-discovery = { version = "0.6.0", optional = true } futures-util = "0.3" # test_utils @@ -154,8 +151,6 @@ default = ["metrics", "fast-apple-datapath", "portmapper", "tls-ring"] portmapper = ["dep:portmapper"] metrics = ["iroh-metrics/metrics", "iroh-relay/metrics", "portmapper?/metrics"] test-utils = ["iroh-relay/test-utils", "iroh-relay/server", "dep:axum"] -address-lookup-mdns = ["dep:swarm-discovery"] -address-lookup-pkarr-dht = ["dep:mainline"] # Enables fetching TLS trust anchors from the operating system platform-verifier = ["iroh-relay/platform-verifier"] qlog = ["noq/qlog"] @@ -196,14 +191,6 @@ required-features = [] name = "connect-unreliable" required-features = [] -[[example]] -name = "dht_address_lookup" -required-features = ["address-lookup-pkarr-dht"] - -[[example]] -name = "mdns_address_lookup" -required-features = ["address-lookup-mdns"] - [[example]] name = "search" required-features = [] diff --git a/iroh/examples/dht_address_lookup.rs b/iroh/examples/dht_address_lookup.rs deleted file mode 100644 index 956dd55896..0000000000 --- a/iroh/examples/dht_address_lookup.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! An example chat application using the iroh endpoint and -//! pkarr address lookup. -//! -//! Starting the example without args creates a server that publishes its -//! address to the DHT. Starting the example with an endpoint id as argument -//! looks up the address of the endpoint id in the DHT and connects to it. -//! -//! You can look at the published pkarr DNS record using . -//! -//! To see what is going on, run with `RUST_LOG=iroh_pkarr_address_lookup=debug`. -//! -//! Note that while the DhtAddressLookup by default publishes only the home -//! relay of the endpoint, this example explicitly removes the filter to publish -//! all addresses. -use clap::Parser; -use iroh::{ - Endpoint, EndpointId, - address_lookup::{AddrFilter, DhtAddressLookup}, - endpoint::presets, -}; -use n0_error::{Result, StdResultExt}; -use tracing::warn; - -const CHAT_ALPN: &[u8] = b"pkarr-address-lookup-demo-chat"; - -#[derive(Parser)] -struct Args { - /// The endpoint id to connect to. If not set, the program will start a server. - endpoint_id: Option, -} - -async fn chat_server() -> Result<()> { - let secret_key = iroh::SecretKey::generate(); - let endpoint_id = secret_key.public(); - let address_lookup = DhtAddressLookup::builder().addr_filter(AddrFilter::unfiltered()); - let endpoint = Endpoint::builder(presets::N0) - .alpns(vec![CHAT_ALPN.to_vec()]) - .secret_key(secret_key) - .address_lookup(address_lookup) - .bind() - .await?; - let zid = endpoint_id.to_z32(); - println!("Listening on {endpoint_id}"); - println!("pkarr z32: {zid}"); - println!("see https://app.pkarr.org/?pk={zid}"); - while let Some(incoming) = endpoint.accept().await { - let accepting = match incoming.accept() { - Ok(accepting) => accepting, - Err(err) => { - warn!("incoming connection failed: {err:#}"); - // we can carry on in these cases: - // this can be caused by retransmitted datagrams - continue; - } - }; - tokio::spawn(async move { - let connection = accepting.await?; - let remote_endpoint_id = connection.remote_id(); - println!("got connection from {remote_endpoint_id}"); - // just leave the tasks hanging. this is just an example. - let (mut writer, mut reader) = connection.accept_bi().await.anyerr()?; - let _copy_to_stdout = tokio::spawn(async move { - tokio::io::copy(&mut reader, &mut tokio::io::stdout()).await - }); - let _copy_from_stdin = - tokio::spawn( - async move { tokio::io::copy(&mut tokio::io::stdin(), &mut writer).await }, - ); - n0_error::Ok(()) - }); - } - Ok(()) -} - -async fn chat_client(args: Args) -> Result<()> { - let remote_endpoint_id = args.endpoint_id.unwrap(); - let secret_key = iroh::SecretKey::generate(); - let endpoint_id = secret_key.public(); - // note: we don't pass a secret key here, because we don't need to publish our address, don't spam the DHT - let address_lookup = DhtAddressLookup::builder().no_publish(); - // we do not need to specify the alpn here, because we are not going to accept connections - let endpoint = Endpoint::builder(presets::N0) - .secret_key(secret_key) - .address_lookup(address_lookup) - .bind() - .await?; - println!("We are {endpoint_id} and connecting to {remote_endpoint_id}"); - let connection = endpoint.connect(remote_endpoint_id, CHAT_ALPN).await?; - println!("connected to {remote_endpoint_id}"); - let (mut writer, mut reader) = connection.open_bi().await.anyerr()?; - let _copy_to_stdout = - tokio::spawn(async move { tokio::io::copy(&mut reader, &mut tokio::io::stdout()).await }); - let _copy_from_stdin = - tokio::spawn(async move { tokio::io::copy(&mut tokio::io::stdin(), &mut writer).await }); - _copy_to_stdout.await.anyerr()?.anyerr()?; - _copy_from_stdin.await.anyerr()?.anyerr()?; - Ok(()) -} - -#[tokio::main] -async fn main() -> Result<()> { - tracing_subscriber::fmt::init(); - let args = Args::parse(); - if args.endpoint_id.is_some() { - chat_client(args).await?; - } else { - chat_server().await?; - } - Ok(()) -} diff --git a/iroh/examples/mdns_address_lookup.rs b/iroh/examples/mdns_address_lookup.rs deleted file mode 100644 index f60a368076..0000000000 --- a/iroh/examples/mdns_address_lookup.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! A small example showing how to get a list of endpoints that were discovered via [`iroh::address_lookup::MdnsAddressLookup`]. Mdns Address Lookup uses [`swarm-discovery`](https://crates.io/crates/swarm-discovery), an opinionated implementation of mDNS to discover other endpoints in the local network. -//! -//! This example creates an iroh endpoint, a few additional iroh endpoints to discover, waits a few seconds, and reports all of the iroh EndpointIds (also called `[iroh::key::PublicKey]`s) it has discovered. -//! -//! This is an async, non-determinate process, so the number of EndpointIDs discovered each time may be different. If you have other iroh endpoints or iroh endpoints with [`address_lookup::MdnsAddressLookup`] enabled, it may discover those endpoints as well. -use std::time::Duration; - -use iroh::{Endpoint, EndpointId, address_lookup, endpoint::presets, endpoint_info::UserData}; -use n0_error::Result; -use n0_future::StreamExt; -use tokio::task::JoinSet; - -#[tokio::main] -async fn main() -> Result<()> { - tracing_subscriber::fmt::init(); - println!("Discovering Local Endpoints Example!"); - - let ep = Endpoint::bind(presets::N0).await?; - let endpoint_id = ep.id(); - - let mdns = address_lookup::MdnsAddressLookup::builder().build(endpoint_id)?; - ep.address_lookup()?.add(mdns.clone()); - - println!("Created endpoint {}", endpoint_id.fmt_short()); - - let user_data = UserData::try_from(String::from("local-endpoints-example"))?; - - let ud = user_data.clone(); - let address_lookup_stream_task = tokio::spawn(async move { - let mut address_lookup_stream = mdns.subscribe().await; - let mut discovered_endpoints: Vec = vec![]; - while let Some(event) = address_lookup_stream.next().await { - match event { - address_lookup::DiscoveryEvent::Discovered { endpoint_info, .. } => { - // if there is no user data, or the user data - // does not indicate that the discovered endpoint - // is a part of the example, ignore it - match endpoint_info.data.user_data() { - Some(user_data) if &ud == user_data => {} - _ => { - tracing::error!( - "found endpoint with unexpected user data, ignoring it" - ); - continue; - } - } - - // if we've already found this endpoint, ignore it - // otherwise announce that we have found a new endpoint - if discovered_endpoints.contains(&endpoint_info.endpoint_id) { - continue; - } else { - discovered_endpoints.push(endpoint_info.endpoint_id); - println!("Found endpoint {}!", endpoint_info.endpoint_id.fmt_short()); - } - } - address_lookup::DiscoveryEvent::Expired { .. } => {} - _ => {} - }; - } - }); - - let mut set = JoinSet::new(); - let endpoint_count = 5; - for _ in 0..endpoint_count { - let ud = user_data.clone(); - set.spawn(async move { - let ep = Endpoint::bind(presets::N0).await?; - ep.address_lookup()? - .add(address_lookup::MdnsAddressLookup::builder().build(ep.id())?); - ep.set_user_data_for_address_lookup(Some(ud)); - tokio::time::sleep(Duration::from_secs(3)).await; - ep.close().await; - n0_error::Ok(()) - }); - } - - set.join_all().await.iter().for_each(|res| { - if let Err(e) = res { - tracing::error!("{e}"); - } - }); - ep.close().await; - address_lookup_stream_task.abort(); - Ok(()) -} diff --git a/iroh/examples/transfer.rs b/iroh/examples/transfer.rs index 98f088cc77..1be123c437 100644 --- a/iroh/examples/transfer.rs +++ b/iroh/examples/transfer.rs @@ -581,18 +581,9 @@ impl EndpointArgs { let endpoint = builder.alpns(vec![TRANSFER_ALPN.to_vec()]).bind().await?; if self.mdns { - #[cfg(feature = "address-lookup-mdns")] - { - use iroh::address_lookup::MdnsAddressLookup; - - endpoint - .address_lookup()? - .add(MdnsAddressLookup::builder().build(endpoint.id())?); - } - #[cfg(not(feature = "address-lookup-mdns"))] - { - n0_error::bail_any!("Must have the `mdns` enabled when using the `--mdns` flag"); - } + n0_error::bail_any!( + "mDNS address lookup is no longer built into iroh; use the `iroh-mdns-address-lookup` crate instead", + ); } if self.relay_only { diff --git a/iroh/src/address_lookup.rs b/iroh/src/address_lookup.rs index 7348ae4d97..d32e8651ec 100644 --- a/iroh/src/address_lookup.rs +++ b/iroh/src/address_lookup.rs @@ -43,11 +43,12 @@ //! - The [`PkarrResolver`] which can perform lookups from designated [pkarr relay servers] //! using HTTP. //! -//! - [`address_lookup::MdnsAddressLookup`]: mdns::MdnsAddressLookup which uses the crate `swarm-discovery`, an -//! opinionated mDNS implementation, to discover endpoints on the local network. +//! mDNS-based and Mainline-DHT-based Address Lookup services live in +//! separate crates: [`iroh-mdns-address-lookup`] and +//! [`iroh-mainline-address-lookup`]. //! -//! - The [`address_lookup::DhtAddressLookup`] also uses the [`pkarr`] system but can also publish and lookup -//! records to/from the Mainline DHT. It requires enabling the `address-lookup-pkarr-dht` feature. +//! [`iroh-mdns-address-lookup`]: https://docs.rs/iroh-mdns-address-lookup +//! [`iroh-mainline-address-lookup`]: https://docs.rs/iroh-mainline-address-lookup //! //! To use multiple Address Lookup'ssimultaneously you can call [`Builder::address_lookup`]. //! This will use [`AddressLookupServices`] under the hood, which performs lookups to all @@ -89,31 +90,6 @@ //! # } //! ``` //! -//! To also enable [`address_lookup::MdnsAddressLookup`] it can be added as another service. -//! -//! ```no_run -//! #[cfg(feature = "address-lookup-mdns")] -//! # { -//! # use iroh::{ -//! # address_lookup::{self, AddrFilter, PkarrPublisher}, -//! # endpoint::{presets, RelayMode}, -//! # Endpoint, SecretKey, -//! # }; -//! # -//! # async fn wrapper() -> n0_error::Result<()> { -//! let ep = Endpoint::builder(presets::Minimal) -//! .relay_mode(RelayMode::Default) -//! .addr_filter(AddrFilter::relay_only()) -//! .address_lookup(PkarrPublisher::n0_dns()) -//! .address_lookup(address_lookup::DnsAddressLookup::n0_dns()) -//! .address_lookup(address_lookup::MdnsAddressLookup::builder()) -//! .bind() -//! .await?; -//! # Ok(()) -//! # } -//! # } -//! ``` -//! //! [`EndpointAddr`]: iroh_base::EndpointAddr //! [`RelayUrl`]: crate::RelayUrl //! [`Builder::address_lookup`]: crate::endpoint::Builder::address_lookup @@ -122,9 +98,7 @@ //! [`PkarrResolver`]: pkarr::PkarrResolver //! [`PkarrPublisher`]: pkarr::PkarrPublisher //! [`PkarrPublisherBuilder::addr_filter`]: pkarr::PkarrPublisherBuilder::addr_filter -//! [`address_lookup::DhtAddressLookup`]: crate::address_lookup::DhtAddressLookup //! [pkarr relay servers]: https://pkarr.org/#servers -//! [`address_lookup::MdnsAddressLookup`]: crate::address_lookup::MdnsAddressLookup //! [`MemoryLookup`]: memory::MemoryLookup use std::{ @@ -145,18 +119,12 @@ use crate::{Endpoint, endpoint::EndpointError}; #[cfg(not(wasm_browser))] pub mod dns; -#[cfg(feature = "address-lookup-mdns")] -pub mod mdns; pub mod memory; pub mod pkarr; #[cfg(not(wasm_browser))] pub use dns::*; -#[cfg(feature = "address-lookup-mdns")] -pub use mdns::*; pub use memory::*; -#[cfg(feature = "address-lookup-pkarr-dht")] -pub use pkarr::dht::*; pub use pkarr::*; /// Trait for structs that can be converted into [`AddressLookup`]s. diff --git a/iroh/src/address_lookup/mdns.rs b/iroh/src/address_lookup/mdns.rs deleted file mode 100644 index 44e4175afc..0000000000 --- a/iroh/src/address_lookup/mdns.rs +++ /dev/null @@ -1,944 +0,0 @@ -//! An address lookup service that uses an mdns-like service to discover and lookup the addresses of local endpoints. -//! -//! This allows you to use an mdns-like swarm discovery service to find address information about endpoints that are on your local network, no relay or outside internet needed. -//! See the [`swarm-discovery`](https://crates.io/crates/swarm-discovery) crate for more details. -//! -//! When [`MdnsAddressLookup`] is enabled, it's possible to get a list of the locally discovered endpoints by filtering a list of `RemoteInfo`s. -//! -//! In order to get a list of locally discovered addresses, you must call `MdnsAddressLookup::subscribe` to subscribe -//! to a stream of discovered addresses. -//! -//! ```no_run -//! use std::time::Duration; -//! -//! use iroh::{ -//! RelayMode, SecretKey, -//! address_lookup::{DiscoveryEvent, MdnsAddressLookup}, -//! endpoint::{Endpoint, Source, presets}, -//! }; -//! use n0_future::StreamExt; -//! -//! #[tokio::main] -//! async fn main() { -//! let recent = Duration::from_secs(600); // 10 minutes in seconds -//! let endpoint = Endpoint::bind(presets::Minimal).await.unwrap(); -//! -//! // Register the Address Lookupwith the endpoint -//! let mdns = MdnsAddressLookup::builder().build(endpoint.id()).unwrap(); -//! endpoint.address_lookup().unwrap().add(mdns.clone()); -//! -//! // Subscribe to the mdns discovery events -//! let mut events = mdns.subscribe().await; -//! while let Some(event) = events.next().await { -//! match event { -//! DiscoveryEvent::Discovered { endpoint_info, .. } => { -//! println!("MDNS discovered: {:?}", endpoint_info); -//! } -//! DiscoveryEvent::Expired { endpoint_id } => { -//! println!("MDNS expired: {endpoint_id}"); -//! } -//! _ => {} -//! } -//! } -//! } -//! ``` -//! -//! ## Filtering -//! -//! By default, [`MdnsAddressLookup`] publishes all addresses it receives: -//! direct IP addresses and up to one [`RelayUrl`]. The following constraints apply regardless -//! of any user-supplied filter: -//! -//! - Only the first [`RelayUrl`] in the address set is published. -//! - A [`RelayUrl`] longer than 249 bytes is silently dropped. -//! -//! You can supply an [`AddrFilter`] via [`MdnsAddressLookupBuilder::addr_filter`] to -//! control which addresses are published and in what order. The filter is applied before the -//! constraints above, so for example you can use it to exclude relay URLs entirely or to -//! prioritize certain addresses. -//! -//! [`AddrFilter`]: crate::address_lookup::AddrFilter -//! [`RelayUrl`]: iroh_base::RelayUrl -use std::{ - collections::{BTreeSet, HashMap}, - net::{IpAddr, SocketAddr}, - str::FromStr, - sync::Arc, -}; - -use iroh_base::{EndpointId, PublicKey}; -use n0_future::{ - Stream, - boxed::BoxStream, - task::{self, AbortOnDropHandle, JoinSet}, - time::{self, Duration}, -}; -use n0_watcher::{Watchable, Watcher as _}; -use swarm_discovery::{Discoverer, DropGuard, IpClass, Peer}; -use tokio::sync::mpsc::{self, error::TrySendError}; -use tracing::{Instrument, debug, error, info_span, trace, warn}; - -use super::AddressLookupBuilder; -use crate::{ - Endpoint, - address_lookup::{ - AddrFilter, AddressLookup, AddressLookupBuilderError, EndpointData, EndpointInfo, - Error as AddressLookupError, Item as AddressLookupItem, - }, -}; - -/// The n0 local service name. -const N0_SERVICE_NAME: &str = "irohv1"; - -/// Name of this address lookup service. -/// -/// Used as the `provenance` field in [`AddressLookupItem`]s. -/// -/// Used in the [`crate::endpoint::Source::AddressLookup`] enum variant as the `name`. -pub const NAME: &str = "mdns"; - -/// The key of the attribute under which the `UserData` is stored in -/// the TXT record supported by swarm-discovery. -const USER_DATA_ATTRIBUTE: &str = "user-data"; - -/// How long we will wait before we stop attempting to resolve an endpoint ID to an address. -const LOOKUP_DURATION: Duration = Duration::from_secs(10); - -/// The key of the attribute under which the `RelayUrl` is stored in -/// the TXT record supported by swarm-discovery. -const RELAY_URL_ATTRIBUTE: &str = "relay"; - -/// Address Lookup using `swarm-discovery`, a variation on mdns. -#[derive(Debug, Clone)] -pub struct MdnsAddressLookup { - #[allow(dead_code)] - handle: Arc>, - sender: mpsc::Sender, - advertise: bool, - /// When `local_addrs` changes, we re-publish our info. - local_addrs: Watchable>, -} - -#[derive(Debug)] -enum Message { - Discovered(String, Peer), - Resolve( - EndpointId, - mpsc::Sender>, - ), - Timeout(EndpointId, usize), - Subscribe(mpsc::Sender), -} - -/// Manages the list of subscribers that are subscribed to this Address Lookup. -#[derive(Debug)] -struct Subscribers(Vec>); - -impl Subscribers { - fn new() -> Self { - Self(vec![]) - } - - /// Add the subscriber to the list of subscribers. - fn push(&mut self, subscriber: mpsc::Sender) { - self.0.push(subscriber); - } - - /// Sends the `endpoint_id` and `item` to each subscriber. - /// - /// Cleans up any subscribers that have been dropped. - fn send(&mut self, item: DiscoveryEvent) { - let mut clean_up = vec![]; - for (i, subscriber) in self.0.iter().enumerate() { - // assume subscriber was dropped - if let Err(err) = subscriber.try_send(item.clone()) { - match err { - TrySendError::Full(_) => { - warn!(?item, idx = i, "mdns subscriber is blocked, dropping item") - } - TrySendError::Closed(_) => clean_up.push(i), - } - } - } - for i in clean_up.into_iter().rev() { - self.0.swap_remove(i); - } - } -} - -/// Builder for [`MdnsAddressLookup`]. -#[derive(Debug)] -pub struct MdnsAddressLookupBuilder { - advertise: bool, - service_name: String, - filter: AddrFilter, -} - -impl MdnsAddressLookupBuilder { - /// Creates a new [`MdnsAddressLookupBuilder`] with default settings. - fn new() -> Self { - Self { - advertise: true, - service_name: N0_SERVICE_NAME.to_string(), - filter: AddrFilter::default(), - } - } - - /// Sets whether this endpoint should advertise its presence. - /// - /// Default is true. - pub fn advertise(mut self, advertise: bool) -> Self { - self.advertise = advertise; - self - } - - /// Sets a custom service name. - /// - /// The default is `irohv1`, which will show up on a record in the - /// following form, for example: - /// `7rutqynuzu65fcdgoerbt4uoh3p62wuto2mp56x3uvhitqzssxga._irohv1._udp.local` - /// - /// Any custom service name will take the form, for example: - /// `7rutqynuzu65fcdgoerbt4uoh3p62wuto2mp56x3uvhitqzssxga._{service_name}._udp.local` - pub fn service_name(mut self, service_name: impl Into) -> Self { - self.service_name = service_name.into(); - self - } - - /// Sets a filter to control which addresses are published by this service. - pub fn addr_filter(mut self, filter: AddrFilter) -> Self { - self.filter = filter; - self - } - - /// Builds an [`MdnsAddressLookup`] instance with the configured settings. - /// - /// # Errors - /// Returns an error if the network does not allow ipv4 OR ipv6. - /// - /// # Panics - /// This relies on [`tokio::runtime::Handle::current`] and will panic if called outside of the context of a tokio runtime. - pub fn build( - self, - endpoint_id: EndpointId, - ) -> Result { - MdnsAddressLookup::new(endpoint_id, self.advertise, self.service_name, self.filter) - } -} - -impl Default for MdnsAddressLookupBuilder { - fn default() -> Self { - Self::new() - } -} - -impl AddressLookupBuilder for MdnsAddressLookupBuilder { - fn into_address_lookup( - self, - endpoint: &Endpoint, - ) -> Result { - self.build(endpoint.id()) - } -} - -/// An event emitted from the [`MdnsAddressLookup`] service. -#[derive(Debug, Clone, Eq, PartialEq)] -#[non_exhaustive] -pub enum DiscoveryEvent { - /// A peer was discovered or it's information was updated. - Discovered { - /// The endpoint info for the endpoint, as discovered. - endpoint_info: EndpointInfo, - /// Optional timestamp when this endpoint address info was last updated. - last_updated: Option, - }, - /// A peer was expired due to being inactive, unreachable, or otherwise - /// unavailable. - Expired { - /// The id of the endpoint that expired. - endpoint_id: EndpointId, - }, -} - -impl MdnsAddressLookup { - /// Returns a [`MdnsAddressLookupBuilder`] used to construct [`MdnsAddressLookup`]. - pub fn builder() -> MdnsAddressLookupBuilder { - MdnsAddressLookupBuilder::default() - } - - /// Create a new [`MdnsAddressLookup`] Service. - /// - /// This starts a [`Discoverer`] that broadcasts your addresses (if advertise is set to true) - /// and receives addresses from other endpoints in your local network. - /// - /// # Errors - /// Returns an error if the network does not allow ipv4 OR ipv6. - /// - /// # Panics - /// This relies on [`tokio::runtime::Handle::current`] and will panic if called outside of the context of a tokio runtime. - fn new( - endpoint_id: EndpointId, - advertise: bool, - service_name: String, - filter: AddrFilter, - ) -> Result { - debug!("Creating new Mdns service"); - let (send, mut recv) = mpsc::channel(64); - let task_sender = send.clone(); - let rt = tokio::runtime::Handle::current(); - let address_lookup = MdnsAddressLookup::spawn_discoverer( - endpoint_id, - advertise, - task_sender.clone(), - BTreeSet::new(), - service_name, - &rt, - )?; - - let local_addrs: Watchable> = Watchable::default(); - let mut addrs_change = local_addrs.watch(); - let address_lookup_fut = async move { - let mut endpoint_addrs: HashMap = HashMap::default(); - let mut subscribers = Subscribers::new(); - let mut last_id = 0; - let mut senders: HashMap< - PublicKey, - HashMap>>, - > = HashMap::default(); - let mut timeouts = JoinSet::new(); - loop { - trace!(?endpoint_addrs, "Mdns Service loop tick"); - let msg = tokio::select! { - msg = recv.recv() => { - msg - } - Ok(Some(data)) = addrs_change.updated() => { - tracing::trace!(?data, "Mdns address changed"); - address_lookup.remove_all(); - - // apply user-supplied filter - let data = data.apply_filter(&filter).into_owned(); - - - let addrs = - MdnsAddressLookup::socketaddrs_to_addrs(data.ip_addrs()); - for addr in addrs { - address_lookup.add(addr.0, addr.1) - } - if let Some(relay) = data.relay_urls().next() - && let Err(err) = address_lookup.set_txt_attribute(RELAY_URL_ATTRIBUTE.to_string(), Some(relay.to_string())) { - warn!("Failed to set the relay url in mDNS: {err:?}"); - } - if let Some(user_data) = data.user_data() - && let Err(err) = address_lookup.set_txt_attribute(USER_DATA_ATTRIBUTE.to_string(), Some(user_data.to_string())) { - warn!("Failed to set the user-defined data in mDNS: {err:?}"); - } - continue; - } - }; - let msg = match msg { - None => { - error!("Mdns channel closed"); - error!("closing Mdns"); - timeouts.abort_all(); - address_lookup.remove_all(); - return; - } - Some(msg) => msg, - }; - match msg { - Message::Discovered(discovered_endpoint_id, peer_info) => { - trace!( - ?discovered_endpoint_id, - ?peer_info, - "Mdns Message::Discovered" - ); - let discovered_endpoint_id = - match PublicKey::from_str(&discovered_endpoint_id) { - Ok(endpoint_id) => endpoint_id, - Err(e) => { - warn!( - discovered_endpoint_id, - "couldn't parse endpoint_id from mdns Address Lookup: {e:?}" - ); - continue; - } - }; - - if discovered_endpoint_id == endpoint_id { - continue; - } - - if peer_info.is_expiry() { - trace!( - ?discovered_endpoint_id, - "removing endpoint from Mdns address book" - ); - endpoint_addrs.remove(&discovered_endpoint_id); - subscribers.send(DiscoveryEvent::Expired { - endpoint_id: discovered_endpoint_id, - }); - continue; - } - - let entry = endpoint_addrs.entry(discovered_endpoint_id); - if let std::collections::hash_map::Entry::Occupied(ref entry) = entry - && entry.get() == &peer_info - { - // this is a republish we already know about - continue; - } - - debug!( - ?discovered_endpoint_id, - ?peer_info, - "adding endpoint to Mdns address book" - ); - - let mut resolved = false; - let item = peer_to_discovery_item(&peer_info, &discovered_endpoint_id); - if let Some(senders) = senders.get(&discovered_endpoint_id) { - trace!(?item, senders = senders.len(), "sending AddressLookupItem"); - resolved = true; - for sender in senders.values() { - sender.send(Ok(item.clone())).await.ok(); - } - } - entry.or_insert(peer_info); - - // only send endpoints to the `subscriber` if they weren't explicitly resolved - // in other words, endpoints sent to the `subscribers` should only be the ones that - // have been "passively" discovered - if !resolved { - subscribers.send(DiscoveryEvent::Discovered { - endpoint_info: item.endpoint_info, - last_updated: item.last_updated, - }); - } - } - Message::Resolve(endpoint_id, sender) => { - let id = last_id + 1; - last_id = id; - trace!(?endpoint_id, "Mdns Message::SendAddrs"); - if let Some(peer_info) = endpoint_addrs.get(&endpoint_id) { - let item = peer_to_discovery_item(peer_info, &endpoint_id); - debug!(?item, "sending AddressLookupItem"); - sender.send(Ok(item)).await.ok(); - } - if let Some(senders_for_endpoint_id) = senders.get_mut(&endpoint_id) { - senders_for_endpoint_id.insert(id, sender); - } else { - let mut senders_for_endpoint_id = HashMap::new(); - senders_for_endpoint_id.insert(id, sender); - senders.insert(endpoint_id, senders_for_endpoint_id); - } - let timeout_sender = task_sender.clone(); - timeouts.spawn(async move { - time::sleep(LOOKUP_DURATION).await; - trace!(?endpoint_id, "resolution timeout"); - timeout_sender - .send(Message::Timeout(endpoint_id, id)) - .await - .ok(); - }); - } - Message::Timeout(endpoint_id, id) => { - trace!(?endpoint_id, "Mdns Message::Timeout"); - if let Some(senders_for_endpoint_id) = senders.get_mut(&endpoint_id) { - senders_for_endpoint_id.remove(&id); - if senders_for_endpoint_id.is_empty() { - senders.remove(&endpoint_id); - } - } - } - Message::Subscribe(subscriber) => { - trace!("Mdns Message::Subscribe"); - subscribers.push(subscriber); - } - } - } - }; - let handle = - task::spawn(address_lookup_fut.instrument(info_span!("swarm-discovery.actor"))); - Ok(Self { - handle: Arc::new(AbortOnDropHandle::new(handle)), - sender: send, - advertise, - local_addrs, - }) - } - - /// Subscribe to discovered endpoints. - pub async fn subscribe(&self) -> impl Stream + Unpin + use<> { - let (sender, recv) = mpsc::channel(20); - let address_lookup_sender = self.sender.clone(); - address_lookup_sender - .send(Message::Subscribe(sender)) - .await - .ok(); - tokio_stream::wrappers::ReceiverStream::new(recv) - } - - fn spawn_discoverer( - endpoint_id: PublicKey, - advertise: bool, - sender: mpsc::Sender, - socketaddrs: BTreeSet, - service_name: String, - rt: &tokio::runtime::Handle, - ) -> Result { - let spawn_rt = rt.clone(); - let callback = move |endpoint_id: &str, peer: &Peer| { - trace!(endpoint_id, ?peer, "Received peer information from Mdns"); - - let sender = sender.clone(); - let endpoint_id = endpoint_id.to_string(); - let peer = peer.clone(); - spawn_rt.spawn(async move { - sender - .send(Message::Discovered(endpoint_id, peer)) - .await - .ok(); - }); - }; - let endpoint_id_str = data_encoding::BASE32_NOPAD - .encode(endpoint_id.as_bytes()) - .to_ascii_lowercase(); - let mut discoverer = Discoverer::new_interactive(service_name, endpoint_id_str) - .with_callback(callback) - .with_ip_class(IpClass::Auto); - if advertise { - let addrs = MdnsAddressLookup::socketaddrs_to_addrs(socketaddrs.iter()); - for addr in addrs { - discoverer = discoverer.with_addrs(addr.0, addr.1); - } - } - discoverer - .spawn(rt) - .map_err(|e| AddressLookupBuilderError::from_err("mdns", e)) - } - - fn socketaddrs_to_addrs<'a>( - socketaddrs: impl Iterator, - ) -> HashMap> { - let mut addrs: HashMap> = HashMap::default(); - for socketaddr in socketaddrs { - addrs - .entry(socketaddr.port()) - .and_modify(|a| a.push(socketaddr.ip())) - .or_insert(vec![socketaddr.ip()]); - } - addrs - } -} - -fn peer_to_discovery_item(peer: &Peer, endpoint_id: &EndpointId) -> AddressLookupItem { - let ip_addrs: BTreeSet = peer - .addrs() - .iter() - .map(|(ip, port)| SocketAddr::new(*ip, *port)) - .collect(); - - // Get the relay url from the resolved peer info. We expect an attribute that parses as - // a `RelayUrl`. Otherwise, omit. - let relay_url = if let Some(Some(relay_url)) = peer.txt_attribute(RELAY_URL_ATTRIBUTE) { - match relay_url.parse() { - Err(err) => { - debug!("failed to parse relay url from TXT attribute: {err}"); - None - } - Ok(url) => Some(url), - } - } else { - None - }; - - // Get the user-defined data from the resolved peer info. We expect an attribute with a value - // that parses as `UserData`. Otherwise, omit. - let user_data = if let Some(Some(user_data)) = peer.txt_attribute(USER_DATA_ATTRIBUTE) { - match user_data.parse() { - Err(err) => { - debug!("failed to parse user data from TXT attribute: {err}"); - None - } - Ok(data) => Some(data), - } - } else { - None - }; - - let mut data = EndpointData::from(ip_addrs); - if let Some(relay_url) = relay_url { - data.add_relay_url(relay_url); - } - data.set_user_data(user_data); - - let endpoint_info = EndpointInfo::from_parts(*endpoint_id, data); - AddressLookupItem::new(endpoint_info, NAME, None) -} - -impl AddressLookup for MdnsAddressLookup { - fn resolve( - &self, - endpoint_id: EndpointId, - ) -> Option>> { - use futures_util::FutureExt; - - let (send, recv) = mpsc::channel(20); - let address_lookup_sender = self.sender.clone(); - let stream = async move { - address_lookup_sender - .send(Message::Resolve(endpoint_id, send)) - .await - .ok(); - tokio_stream::wrappers::ReceiverStream::new(recv) - }; - Some(Box::pin(stream.flatten_stream())) - } - - fn publish(&self, data: &EndpointData) { - if self.advertise { - self.local_addrs.set(Some(data.clone())).ok(); - } - } -} - -#[cfg(test)] -mod tests { - - /// This module's name signals nextest to run test in a single thread (no other concurrent - /// tests). - mod run_in_isolation { - use iroh_base::{SecretKey, TransportAddr}; - use n0_error::{AnyError as Error, Result, StdResultExt, bail_any}; - use n0_future::StreamExt; - use n0_tracing_test::traced_test; - use rand::{CryptoRng, RngExt, SeedableRng}; - - use super::super::*; - use crate::address_lookup::UserData; - - #[tokio::test] - #[traced_test] - async fn mdns_publish_resolve() -> Result { - let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - - // Create Address LookupA with advertise=false (only listens) - let (_, address_lookup_a) = make_address_lookup(&mut rng, false)?; - // Create Address LookupB with advertise=true (will broadcast) - let (endpoint_id_b, address_lookup_b) = make_address_lookup(&mut rng, true)?; - - // make addr info for discoverer b - let user_data: UserData = "foobar".parse()?; - let endpoint_data = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:11111".parse().unwrap())]) - .with_user_data(user_data.clone()); - - // resolve twice to ensure we can create separate streams for the same endpoint_id - let mut s1 = address_lookup_a - .subscribe() - .await - .filter(|event| match event { - DiscoveryEvent::Discovered { endpoint_info, .. } => { - endpoint_info.endpoint_id == endpoint_id_b - } - _ => false, - }); - let mut s2 = address_lookup_a - .subscribe() - .await - .filter(|event| match event { - DiscoveryEvent::Discovered { endpoint_info, .. } => { - endpoint_info.endpoint_id == endpoint_id_b - } - _ => false, - }); - - tracing::debug!(?endpoint_id_b, "Discovering endpoint id b"); - // publish address_lookup_b's address - address_lookup_b.publish(&endpoint_data); - let DiscoveryEvent::Discovered { - endpoint_info: s1_endpoint_info, - .. - } = tokio::time::timeout(Duration::from_secs(5), s1.next()) - .await - .std_context("timeout")? - .unwrap() - else { - panic!("Received unexpected discovery event"); - }; - let DiscoveryEvent::Discovered { - endpoint_info: s2_endpoint_info, - .. - } = tokio::time::timeout(Duration::from_secs(5), s2.next()) - .await - .std_context("timeout")? - .unwrap() - else { - panic!("Received unexpected discovery event"); - }; - assert_eq!(s1_endpoint_info.data, endpoint_data); - assert_eq!(s2_endpoint_info.data, endpoint_data); - - Ok(()) - } - - #[tokio::test] - #[traced_test] - async fn mdns_publish_expire() -> Result { - let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - let (_, address_lookup_a) = make_address_lookup(&mut rng, false)?; - let (endpoint_id_b, address_lookup_b) = make_address_lookup(&mut rng, true)?; - - // publish address_lookup_b's address - let endpoint_data = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:11111".parse().unwrap())]) - .with_user_data("".parse()?); - address_lookup_b.publish(&endpoint_data); - - let mut s1 = address_lookup_a.subscribe().await; - tracing::debug!(?endpoint_id_b, "Discovering endpoint id b"); - - // Wait for the specific endpoint to be discovered - loop { - let event = tokio::time::timeout(Duration::from_secs(5), s1.next()) - .await - .std_context("timeout")? - .expect("Stream should not be closed"); - - match event { - DiscoveryEvent::Discovered { endpoint_info, .. } - if endpoint_info.endpoint_id == endpoint_id_b => - { - break; - } - _ => continue, // Ignore other discovery events - } - } - - // Shutdown endpoint B - drop(address_lookup_b); - tokio::time::sleep(Duration::from_secs(5)).await; - - // Wait for the expiration event for the specific endpoint - loop { - let event = tokio::time::timeout(Duration::from_secs(10), s1.next()) - .await - .std_context("timeout waiting for expiration event")? - .expect("Stream should not be closed"); - - match event { - DiscoveryEvent::Expired { - endpoint_id: expired_endpoint_id, - } if expired_endpoint_id == endpoint_id_b => { - break; - } - _ => continue, // Ignore other events - } - } - - Ok(()) - } - - #[tokio::test] - #[traced_test] - async fn mdns_subscribe() -> Result { - let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - - let num_endpoints = 5; - let mut endpoint_ids = BTreeSet::new(); - let mut address_lookup_list = vec![]; - - let (_, address_lookup) = make_address_lookup(&mut rng, false)?; - let endpoint_data = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:11111".parse().unwrap())]); - - for i in 0..num_endpoints { - let (endpoint_id, address_lookup) = make_address_lookup(&mut rng, true)?; - let user_data: UserData = format!("endpoint{i}").parse()?; - let endpoint_data = endpoint_data.clone().with_user_data(user_data.clone()); - endpoint_ids.insert((endpoint_id, Some(user_data))); - address_lookup.publish(&endpoint_data); - address_lookup_list.push(address_lookup); - } - - let mut events = address_lookup.subscribe().await; - - let test = async move { - let mut got_ids = BTreeSet::new(); - while got_ids.len() != num_endpoints { - if let Some(DiscoveryEvent::Discovered { endpoint_info, .. }) = - events.next().await - { - let data = endpoint_info.data.user_data().cloned(); - if endpoint_ids.contains(&(endpoint_info.endpoint_id, data.clone())) { - got_ids.insert((endpoint_info.endpoint_id, data)); - } - } else { - bail_any!( - "no more events, only got {} ids, expected {num_endpoints}\n", - got_ids.len() - ); - } - } - assert_eq!(got_ids, endpoint_ids); - Ok::<_, Error>(()) - }; - tokio::time::timeout(Duration::from_secs(5), test) - .await - .std_context("timeout")? - } - - #[tokio::test] - #[traced_test] - async fn non_advertising_endpoint_not_discovered() -> Result { - let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - - let (_, address_lookup_a) = make_address_lookup(&mut rng, false)?; - let (endpoint_id_b, address_lookup_b) = make_address_lookup(&mut rng, false)?; - - let (endpoint_id_c, address_lookup_c) = make_address_lookup(&mut rng, true)?; - let endpoint_data_c = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:22222".parse().unwrap())]); - address_lookup_c.publish(&endpoint_data_c); - - let endpoint_data_b = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:11111".parse().unwrap())]); - address_lookup_b.publish(&endpoint_data_b); - - let mut stream_c = address_lookup_a.resolve(endpoint_id_c).unwrap(); - let result_c = tokio::time::timeout(Duration::from_secs(2), stream_c.next()).await; - assert!( - result_c.is_ok(), - "Advertising endpoint should be discoverable" - ); - - let mut stream_b = address_lookup_a.resolve(endpoint_id_b).unwrap(); - let result_b = tokio::time::timeout(Duration::from_secs(2), stream_b.next()).await; - assert!( - result_b.is_err(), - "Expected timeout since endpoint b isn't advertising" - ); - - Ok(()) - } - - #[tokio::test] - #[traced_test] - async fn test_service_names() -> Result { - let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - - // Create an Address Lookupusing the default - // service name - let id_a = SecretKey::from_bytes(&rng.random()).public(); - let address_lookup_a = MdnsAddressLookup::builder().build(id_a)?; - - // Create a Address Lookupusing a custom - // service name - let id_b = SecretKey::from_bytes(&rng.random()).public(); - let address_lookup_b = MdnsAddressLookup::builder() - .service_name("different.name") - .build(id_b)?; - - // Create an Address Lookupusing the same - // custom service name - let id_c = SecretKey::from_bytes(&rng.random()).public(); - let address_lookup_c = MdnsAddressLookup::builder() - .service_name("different.name") - .build(id_c)?; - - let endpoint_data_a = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:11111".parse().unwrap())]); - address_lookup_a.publish(&endpoint_data_a); - - let endpoint_data_b = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:22222".parse().unwrap())]); - address_lookup_b.publish(&endpoint_data_b); - - let endpoint_data_c = - EndpointData::from_iter([TransportAddr::Ip("0.0.0.0:33333".parse().unwrap())]); - address_lookup_c.publish(&endpoint_data_c); - - let mut stream_a = address_lookup_a.resolve(id_b).unwrap(); - let result_a = tokio::time::timeout(Duration::from_secs(2), stream_a.next()).await; - assert!( - result_a.is_err(), - "Endpoint on a different service should NOT be discoverable" - ); - - let mut stream_b = address_lookup_b.resolve(id_c).unwrap(); - let result_b = tokio::time::timeout(Duration::from_secs(2), stream_b.next()).await; - assert!( - result_b.is_ok(), - "Endpoint on the same service should be discoverable" - ); - - let mut stream_b = address_lookup_b.resolve(id_a).unwrap(); - let result_b = tokio::time::timeout(Duration::from_secs(2), stream_b.next()).await; - assert!( - result_b.is_err(), - "Endpoint on a different service should NOT be discoverable" - ); - - Ok(()) - } - - #[tokio::test] - #[traced_test] - async fn mdns_publish_relay_url() -> Result { - let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); - - // Create an mdns address lookup A that only listens - let (_, mdns_a) = make_address_lookup(&mut rng, false)?; - - // Create an mdns address lookup B that includes a relay url for publishing - let (endpoint_id_b, mdns_b) = make_address_lookup(&mut rng, true)?; - let relay_url: iroh_base::RelayUrl = "https://relay.example.com".parse().unwrap(); - let endpoint_data = EndpointData::from_iter([ - TransportAddr::Ip("0.0.0.0:11111".parse().unwrap()), - TransportAddr::Relay(relay_url.clone()), - ]); - - // Subscribe to discovery events filtered for endpoint B - let mut events = mdns_a.subscribe().await.filter(|event| match event { - DiscoveryEvent::Discovered { endpoint_info, .. } => { - endpoint_info.endpoint_id == endpoint_id_b - } - _ => false, - }); - - // Publish mdns_b's address with relay URL - mdns_b.publish(&endpoint_data); - - // Wait for discovery - let DiscoveryEvent::Discovered { endpoint_info, .. } = - tokio::time::timeout(Duration::from_secs(2), events.next()) - .await - .std_context("timeout")? - .unwrap() - else { - panic!("Received unexpected discovery event"); - }; - - // Verify the relay URL was received - let discovered_relay_urls: Vec<_> = endpoint_info.data.relay_urls().collect(); - assert_eq!(discovered_relay_urls.len(), 1); - assert_eq!(discovered_relay_urls[0], &relay_url); - - Ok(()) - } - - fn make_address_lookup( - rng: &mut R, - advertise: bool, - ) -> Result<(PublicKey, MdnsAddressLookup)> { - let endpoint_id = SecretKey::from_bytes(&rng.random()).public(); - Ok(( - endpoint_id, - MdnsAddressLookup::builder() - .advertise(advertise) - .build(endpoint_id)?, - )) - } - } -} diff --git a/iroh/src/address_lookup/pkarr.rs b/iroh/src/address_lookup/pkarr.rs index 54f2032e8c..ba1788648c 100644 --- a/iroh/src/address_lookup/pkarr.rs +++ b/iroh/src/address_lookup/pkarr.rs @@ -37,9 +37,10 @@ //! //! - [`address_lookup::DnsAddressLookup`], which resolves from a DNS server. //! -//! - [`address_lookup::DhtAddressLookup`], which resolves and publishes from both pkarr relay servers and well -//! as the Mainline DHT. +//! Mainline-DHT-based pkarr publishing/lookup lives in the +//! [`iroh-mainline-address-lookup`] crate. //! +//! [`iroh-mainline-address-lookup`]: https://docs.rs/iroh-mainline-address-lookup //! [pkarr]: https://pkarr.org //! [DNS Resource Records]: https://en.wikipedia.org/wiki/Domain_Name_System#Resource_records //! [Mainline DHT]: https://en.wikipedia.org/wiki/Mainline_DHT @@ -47,7 +48,6 @@ //! [`PublicKey`]: crate::PublicKey //! [`EndpointId`]: crate::EndpointId //! [`address_lookup::DnsAddressLookup`]: crate::address_lookup::DnsAddressLookup -//! [`address_lookup::DhtAddressLookup`]: crate::address_lookup::DhtAddressLookup //! [`N0` preset]: crate::endpoint::presets::N0 //! [`AddrFilter`]: crate::address_lookup::AddrFilter //! [`AddrFilter::relay_only`]: crate::address_lookup::AddrFilter::relay_only @@ -84,9 +84,6 @@ use crate::{ util::reqwest_client_builder, }; -#[cfg(feature = "address-lookup-pkarr-dht")] -pub mod dht; - #[allow(missing_docs)] #[stack_error(derive, add_meta)] #[non_exhaustive] diff --git a/iroh/src/address_lookup/pkarr/dht.rs b/iroh/src/address_lookup/pkarr/dht.rs deleted file mode 100644 index 07719bcbde..0000000000 --- a/iroh/src/address_lookup/pkarr/dht.rs +++ /dev/null @@ -1,396 +0,0 @@ -//! Pkarr based address lookup for iroh, supporting both relay servers and the DHT. -//! -//! This module contains pkarr-based address lookup for iroh which can use both pkarr -//! relay servers as well as the Mainline DHT directly. See the [pkarr module] for an -//! overview of pkarr. -//! -//! [pkarr module]: super -use std::sync::{Arc, Mutex}; - -use iroh_base::{EndpointId, SecretKey}; -use iroh_dns::pkarr::{SignedPacket, SignedPacketVerifyError, Timestamp}; -use mainline::{Dht, DhtBuilder, MutableItem}; -use n0_future::{ - boxed::BoxStream, - stream::StreamExt, - task::{self, AbortOnDropHandle}, - time::{self, Duration}, -}; - -use crate::{ - Endpoint, - address_lookup::{ - AddrFilter, AddressLookup, AddressLookupBuilder, AddressLookupBuilderError, EndpointData, - Error as AddressLookupError, Item as AddressLookupItem, pkarr::DEFAULT_PKARR_TTL, - }, - endpoint_info::EndpointInfo, -}; - -/// Republish delay for the DHT. -/// -/// This is only for when the info does not change. If the info changes, it will be -/// published immediately. -const REPUBLISH_DELAY: Duration = Duration::from_secs(60 * 60); - -/// Convert a [`SignedPacket`] to a mainline [`MutableItem`]. -fn signed_packet_to_mutable_item(packet: &SignedPacket) -> MutableItem { - MutableItem::new_signed_unchecked( - *packet.public_key().as_bytes(), - packet.signature().to_bytes(), - packet.encoded_packet(), - packet.timestamp().as_micros() as i64, - None, - ) -} - -/// Convert a mainline [`MutableItem`] to a [`SignedPacket`]. -fn mutable_item_to_signed_packet( - item: &MutableItem, -) -> Result { - SignedPacket::from_parts_unchecked( - item.key(), - item.signature(), - Timestamp::from_micros(item.seq() as u64), - item.value(), - ) -} - -/// Pkarr Mainline DHT and relay server address lookup. -/// -/// It stores endpoint addresses in DNS records, signed by the endpoint's private key, and publishes -/// them to the BitTorrent Mainline DHT. See the [pkarr module] for more details. -/// -/// This implements the [`AddressLookup`] trait to be used as an address lookup service which can -/// be used as both a publisher and resolver. Calling [`DhtAddressLookup::publish`] will start -/// a background task that periodically publishes the endpoint address. -/// -/// [`DhtAddressLookup`] filters published addresses: only relay addresses are published by default. -/// To change this behavior, use [`Builder::addr_filter`] and set it to e.g. [`AddrFilter::unfiltered`]. -/// This can be useful to enable publishing IP addresses if the iroh endpoint is reachable via public -/// IP addresses. -/// -/// [pkarr module]: super -/// [`AddrFilter::relay_only`]: crate::address_lookup::AddrFilter::relay_only -/// [`AddrFilter::unfiltered`]: crate::address_lookup::AddrFilter::unfiltered -#[derive(Debug, Clone)] -pub struct DhtAddressLookup(Arc); - -#[derive(derive_more::Debug)] -struct Inner { - /// Mainline DHT node. - dht: Dht, - /// The background task that periodically publishes the endpoint address. - /// - /// Due to [`AbortOnDropHandle`], this will be aborted when the Address Lookup is dropped. - task: Mutex>>, - /// Optional keypair for signing the DNS packets. - /// - /// If this is None, the endpoint will not publish its address to the DHT. - secret_key: Option, - /// Time-to-live value for the DNS packets. - ttl: u32, - /// Republish delay for the DHT. - republish_delay: Duration, - /// User supplied filter to filter and reorder addresses for publishing - filter: AddrFilter, -} - -impl Inner { - async fn resolve_dht( - &self, - public_key: EndpointId, - ) -> Option> { - tracing::info!("resolving {} from DHT", public_key.to_z32()); - - let maybe_item = self - .dht - .clone() - .as_async() - .get_mutable_most_recent(public_key.as_bytes(), None) - .await; - match maybe_item { - Some(item) => { - let signed_packet = match mutable_item_to_signed_packet(&item) { - Ok(packet) => packet, - Err(err) => { - tracing::debug!("failed to parse mutable item as signed packet: {err}"); - return None; - } - }; - match EndpointInfo::from_pkarr_signed_packet(&signed_packet) { - Ok(endpoint_info) => { - tracing::info!("discovered endpoint info {:?}", endpoint_info); - Some(Ok(AddressLookupItem::new(endpoint_info, "pkarr", None))) - } - Err(_err) => { - tracing::debug!("failed to parse signed packet as endpoint info"); - None - } - } - } - None => { - tracing::debug!("no signed packet found"); - None - } - } - } -} - -/// Builder for [`DhtAddressLookup`]. -/// -/// By default, publishing to the DHT is enabled, and relay publishing is disabled. -#[derive(Debug)] -pub struct Builder { - dht_builder: Option, - secret_key: Option, - ttl: Option, - republish_delay: Duration, - enable_publish: bool, - addr_filter: AddrFilter, -} - -impl Default for Builder { - fn default() -> Self { - Self { - dht_builder: None, - secret_key: None, - ttl: None, - republish_delay: REPUBLISH_DELAY, - enable_publish: true, - addr_filter: AddrFilter::relay_only(), - } - } -} - -impl Builder { - /// Explicitly sets the DHT builder to use. - pub fn dht_builder(mut self, builder: DhtBuilder) -> Self { - self.dht_builder = Some(builder); - self - } - - /// Sets the secret key to use for signing the DNS packets. - /// - /// Without a secret key, the endpoint will not publish its address to the DHT. - pub fn secret_key(mut self, secret_key: SecretKey) -> Self { - self.secret_key = Some(secret_key); - self - } - - /// Sets the time-to-live value for the DNS packets. - pub fn ttl(mut self, ttl: u32) -> Self { - self.ttl = Some(ttl); - self - } - - /// Sets the republish delay for the DHT. - pub fn republish_delay(mut self, republish_delay: Duration) -> Self { - self.republish_delay = republish_delay; - self - } - - /// Disables publishing even if a secret key is set. - pub fn no_publish(mut self) -> Self { - self.enable_publish = false; - self - } - - /// Sets the address filter to control which addresses are published to the DHT. - /// - /// By default [`AddrFilter::relay_only`] is used. This avoids leaking IP addresses - /// to the public DHT. - /// - /// It can be useful to override this with [`AddrFilter::unfiltered`], if this is - /// not a concern, e.g. when this endpoint runs on a machine with public IP - /// addresses and without a firewall. In such cases connecting to this endpoint - /// with just an [`EndpointId`] and DHT lookup can become faster and potentially - /// even bypass a relay connection entirely. - pub fn addr_filter(mut self, filter: AddrFilter) -> Self { - self.addr_filter = filter; - self - } - - /// Builds the address lookup mechanism. - pub fn build(self) -> Result { - let dht_builder = self.dht_builder.unwrap_or_default(); - let dht = dht_builder - .build() - .map_err(|e| AddressLookupBuilderError::from_err("pkarr-dht", e))?; - let ttl = self.ttl.unwrap_or(DEFAULT_PKARR_TTL); - let secret_key = self.secret_key.filter(|_| self.enable_publish); - - Ok(DhtAddressLookup(Arc::new(Inner { - dht, - ttl, - secret_key, - republish_delay: self.republish_delay, - task: Default::default(), - filter: self.addr_filter, - }))) - } -} - -impl AddressLookupBuilder for Builder { - fn into_address_lookup( - self, - endpoint: &Endpoint, - ) -> Result { - self.secret_key(endpoint.secret_key().clone()).build() - } -} - -impl DhtAddressLookup { - /// Creates a new builder for [`DhtAddressLookup`]. - pub fn builder() -> Builder { - Builder::default() - } - - /// Periodically publishes the endpoint address to the DHT. - /// - /// The first publish uses BEP-44 compare-and-swap against the currently-stored seq - /// so we don't clobber a concurrent writer for this key. Subsequent iterations are - /// refreshes — their purpose is to reach DHT nodes that have newly joined the - /// routing table, not to write new data, so they pass `cas: None` (a stale CAS - /// would make fresh nodes reject the put). - async fn publish_loop(self, signed_packet: SignedPacket) { - let this = self; - let public_key = signed_packet.public_key(); - let z32 = public_key.to_z32(); - let item = signed_packet_to_mutable_item(&signed_packet); - let initial_cas = this - .0 - .dht - .clone() - .as_async() - .get_mutable_most_recent(public_key.as_bytes(), None) - .await - .map(|item| item.seq()); - let mut cas = initial_cas; - loop { - let res = this - .0 - .dht - .clone() - .as_async() - .put_mutable(item.clone(), cas) - .await; - match res { - Ok(_) => { - tracing::debug!("pkarr publish success. published under {z32}"); - } - Err(e) => { - // we could do a smaller delay here, but in general DHT publish - // not working is due to a network issue, and if the network changes - // the task will be restarted anyway. - // - // Being unable to publish to the DHT is something that is expected - // to happen from time to time, so this does not warrant a error log. - tracing::warn!("pkarr publish error: {}", e); - } - } - cas = None; - time::sleep(this.0.republish_delay).await; - } - } -} - -impl AddressLookup for DhtAddressLookup { - fn publish(&self, data: &EndpointData) { - let Some(keypair) = &self.0.secret_key else { - tracing::debug!("no keypair set, not publishing"); - return; - }; - - // apply user-supplied filter - let data = data.apply_filter(&self.0.filter).into_owned(); - - if !data.has_addrs() { - tracing::debug!("no relay url or direct addresses in endpoint data, not publishing"); - return; - } - - tracing::debug!("publishing {data:?}"); - let info = EndpointInfo::from_parts(keypair.public(), data); - let Ok(signed_packet) = info.to_pkarr_signed_packet(keypair, self.0.ttl) else { - tracing::warn!("failed to create signed packet"); - return; - }; - let this = self.clone(); - let curr = task::spawn(this.publish_loop(signed_packet)); - let mut task = self.0.task.lock().expect("poisoned"); - *task = Some(AbortOnDropHandle::new(curr)); - } - - fn resolve( - &self, - endpoint_id: EndpointId, - ) -> Option>> { - let z32 = endpoint_id.to_z32(); - tracing::info!("resolving {} as {}", endpoint_id, z32); - let address_lookup = self.0.clone(); - let stream = - n0_future::stream::once_future( - async move { address_lookup.resolve_dht(endpoint_id).await }, - ) - .filter_map(|x| x) - .boxed(); - Some(stream) - } -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeSet; - - use iroh_base::{RelayUrl, TransportAddr}; - use mainline::Testnet; - use n0_error::{Result, StdResultExt}; - use n0_tracing_test::traced_test; - use url::Url; - - use super::*; - - #[tokio::test] - #[ignore = "flaky"] - #[traced_test] - async fn dht_address_lookup_smoke() -> Result { - let secret = SecretKey::generate(); - let testnet = Testnet::new_async(3).await.anyerr()?; - let mut dht_builder = DhtBuilder::default(); - dht_builder.bootstrap(&testnet.bootstrap); - let address_lookup = DhtAddressLookup::builder() - .secret_key(secret.clone()) - .dht_builder(dht_builder) - .addr_filter(AddrFilter::unfiltered()) - .build()?; - - let relay_url: RelayUrl = Url::parse("https://example.com").anyerr()?.into(); - - let data = EndpointData::from_iter([TransportAddr::Relay(relay_url.clone())]); - address_lookup.publish(&data); - - // publish is fire and forget, so we have no way to wait until it is done. - tokio::time::timeout(Duration::from_secs(30), async move { - loop { - tokio::time::sleep(Duration::from_millis(200)).await; - let mut found_relay_urls = BTreeSet::new(); - let items = address_lookup - .resolve(secret.public()) - .unwrap() - .collect::>() - .await; - for item in items.into_iter().flatten() { - for url in item.relay_urls() { - found_relay_urls.insert(url.clone()); - } - } - if found_relay_urls.contains(&relay_url) { - break; - } - } - }) - .await - .expect("timeout, relay_url not found on DHT"); - Ok(()) - } -}